| 1 |
package platform |
| 2 |
|
| 3 |
import "fmt" |
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
const ( |
| 9 |
LinuxTag = uint32(iota) << platformShift |
| 10 |
WindowsTag |
| 11 |
) |
| 12 |
|
| 13 |
const ( |
| 14 |
platformMax = 1<<3 - 1 |
| 15 |
platformShift = 28 |
| 16 |
platformMask = platformMax << platformShift |
| 17 |
) |
| 18 |
|
| 19 |
func tagForPlatform(platform string) (uint32, error) { |
| 20 |
switch platform { |
| 21 |
case Linux: |
| 22 |
return LinuxTag, nil |
| 23 |
case Windows: |
| 24 |
return WindowsTag, nil |
| 25 |
default: |
| 26 |
return 0, fmt.Errorf("unrecognized platform: %s", platform) |
| 27 |
} |
| 28 |
} |
| 29 |
|
| 30 |
func platformForConstant(c uint32) string { |
| 31 |
tag := uint32(c & platformMask) |
| 32 |
switch tag { |
| 33 |
case LinuxTag: |
| 34 |
return Linux |
| 35 |
case WindowsTag: |
| 36 |
return Windows |
| 37 |
default: |
| 38 |
return "" |
| 39 |
} |
| 40 |
} |
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
func EncodeConstant[T ~uint32](platform string, c uint32) (T, error) { |
| 46 |
if c>>platformShift > 0 { |
| 47 |
return 0, fmt.Errorf("invalid constant 0x%x", c) |
| 48 |
} |
| 49 |
|
| 50 |
tag, err := tagForPlatform(platform) |
| 51 |
if err != nil { |
| 52 |
return 0, err |
| 53 |
} |
| 54 |
|
| 55 |
return T(tag | c), nil |
| 56 |
} |
| 57 |
|
| 58 |
|
| 59 |
func DecodeConstant[T ~uint32](c T) (string, uint32) { |
| 60 |
v := uint32(c) & ^uint32(platformMask) |
| 61 |
return platformForConstant(uint32(c)), v |
| 62 |
} |