/
int32.go
47 lines (36 loc) · 1.1 KB
/
int32.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package ormfield
import (
"encoding/binary"
io "io"
"google.golang.org/protobuf/reflect/protoreflect"
)
// Int32Codec encodes 32-bit integers as big-endian unsigned 32-bit integers
// by adding the maximum value of int32 (2147583647) + 1 before encoding so
// that these values can be used for ordered iteration.
type Int32Codec struct{}
var int32Codec = Int32Codec{}
const int32Max = 2147483647
const int32Offset = int32Max + 1
func (i Int32Codec) Decode(r Reader) (protoreflect.Value, error) {
var x uint32
err := binary.Read(r, binary.BigEndian, &x)
y := int64(x) - int32Offset
return protoreflect.ValueOfInt32(int32(y)), err
}
func (i Int32Codec) Encode(value protoreflect.Value, w io.Writer) error {
x := value.Int()
x += int32Offset
return binary.Write(w, binary.BigEndian, uint32(x))
}
func (i Int32Codec) Compare(v1, v2 protoreflect.Value) int {
return compareInt(v1, v2)
}
func (i Int32Codec) IsOrdered() bool {
return true
}
func (i Int32Codec) FixedBufferSize() int {
return 4
}
func (i Int32Codec) ComputeBufferSize(protoreflect.Value) (int, error) {
return i.FixedBufferSize(), nil
}