forked from status-im/nim-protobuf-serialization
-
Notifications
You must be signed in to change notification settings - Fork 0
/
types.nim
93 lines (73 loc) · 2.28 KB
/
types.nim
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#Types/common data exported for use outside of this library.
import
faststreams,
serialization/errors
export faststreams, errors
type
ProtobufError* = object of SerializationError
ProtobufReadError* = object of ProtobufError
ProtobufEOFError* = object of ProtobufReadError
ProtobufMessageError* = object of ProtobufReadError
ProtobufFlags* = enum
VarIntLengthPrefix
ProtobufWriter* = object
stream*: OutputStream
flags*: set[ProtobufFlags]
ProtobufReader* = ref object
stream*: InputStream
closeAfter*: bool
PBOption*[defaultValue: static[auto]] = object
some: bool
value: typeof(defaultValue)
# Message type annotations
template proto2*() {.pragma.}
template proto3*() {.pragma.}
# Field annotations
template fieldNumber*(num: int) {.pragma.}
template required*() {.pragma.}
template packed*(v: bool) {.pragma.}
template pint*() {.pragma.} # encode as `intXX`
template sint*() {.pragma.} # encode as `sintXX`
template fixed*() {.pragma.} # encode as `fixedXX`
func init*(
T: type ProtobufWriter,
stream: OutputStream,
flags: static set[ProtobufFlags] = {}
): T {.inline.} =
T(stream: stream, flags: flags)
func init*(
T: type ProtobufReader,
stream: InputStream,
# key: Option[ProtobufKey] = none(ProtobufKey),
closeAfter: bool = true
): T {.inline.} =
T(stream: stream, closeAfter: closeAfter)
#This was originally called buffer, and retuned just the output.
#That said, getting the output purges the stream, and doesn't close it.
#Now it's called finish, as there's no reason to keep the stream open at that point.
#A singly function reduces API complexity/expectations on the user.
proc finish*(writer: ProtobufWriter): seq[byte] =
result = writer.stream.getOutput()
writer.stream.close()
func isNone*(opt: PBOption): bool {.inline.} =
not opt.some
func isSome*(opt: PBOption): bool {.inline.} =
opt.some
func get*(opt: PBOption): auto =
if opt.some:
opt.value
else:
opt.defaultValue
template mget*(opt: var PBOption): untyped =
opt.some = true
opt.value
func pbSome*[T: PBOption](optType: typedesc[T], value: auto): T {.inline.} =
T(
some: true,
value: value
)
func init*(opt: var PBOption, val: auto) =
opt.some = true
opt.value = val
converter toValue*(opt: PBOption): auto {.inline.} =
opt.get()