MCPcopy Create free account
hub / github.com/WICG/webpackage / encodeTypedUint

Method encodeTypedUint

go/internal/cbor/encoder.go:24–68  ·  view source on GitHub ↗
(t Type, n uint64)

Source from the content-addressed store, hash-verified

22}
23
24func (e *Encoder) encodeTypedUint(t Type, n uint64) error {
25 // Major type 0: an unsigned integer. The 5-bit additional information
26 // is either the integer itself (for additional information values 0
27 // through 23) or the length of additional data. Additional
28 // information 24 means the value is represented in an additional
29 // uint8_t, 25 means a uint16_t, 26 means a uint32_t, and 27 means a
30 // uint64_t. For example, the integer 10 is denoted as the one byte
31 // 0b000_01010 (major type 0, additional information 10). The
32 // integer 500 would be 0b000_11001 (major type 0, additional
33 // information 25) followed by the two bytes 0x01f4, which is 500 in
34 // decimal.
35 //
36 // https://tools.ietf.org/html/rfc7049#section-2.1
37 ai := byte(0) // "additional information"
38 nfollow := 0 // length of the following bytes
39 switch {
40 case n < 24:
41 ai = byte(n)
42 nfollow = 0
43 case n < (1 << 8):
44 ai = 24
45 nfollow = 1
46 case n < (1 << 16):
47 ai = 25
48 nfollow = 2
49 case n < (1 << 32):
50 ai = 26
51 nfollow = 4
52 default:
53 ai = 27
54 nfollow = 8
55 }
56
57 encoded := make([]byte, 1+nfollow)
58 encoded[0] = byte(t) | ai
59 for i := nfollow - 1; i >= 0; i-- {
60 encoded[i+1] = byte(n)
61 n >>= 8
62 }
63
64 if _, err := e.w.Write(encoded); err != nil {
65 return err
66 }
67 return nil
68}
69
70func (e *Encoder) EncodeUint(n uint64) error {
71 return e.encodeTypedUint(TypePosInt, n)

Callers 5

EncodeUintMethod · 0.95
EncodeIntMethod · 0.95
encodeBytesMethod · 0.95
EncodeArrayHeaderMethod · 0.95
encodeMapHeaderMethod · 0.95

Calls 1

WriteMethod · 0.45

Tested by

no test coverage detected