1 // Copyright (c) 2020 Cisco and/or its affiliates.
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at:
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
25 // Buffer provides buffer for encoding and decoding data on wire.
31 func NewBuffer(b []byte) *Buffer {
37 func (b *Buffer) Bytes() []byte {
41 func (b *Buffer) EncodeBytes(v []byte, length int) {
45 copy(b.buf[b.pos:b.pos+length], v)
49 func (b *Buffer) DecodeBytes(length int) []byte {
50 v := b.buf[b.pos : b.pos+length]
55 func (b *Buffer) EncodeBool(v bool) {
64 func (b *Buffer) DecodeBool() bool {
65 v := b.buf[b.pos] != 0
70 func (b *Buffer) EncodeUint8(v uint8) {
75 func (b *Buffer) DecodeUint8() uint8 {
81 func (b *Buffer) EncodeUint16(v uint16) {
82 binary.BigEndian.PutUint16(b.buf[b.pos:b.pos+2], v)
86 func (b *Buffer) DecodeUint16() uint16 {
87 v := binary.BigEndian.Uint16(b.buf[b.pos : b.pos+2])
92 func (b *Buffer) EncodeUint32(v uint32) {
93 binary.BigEndian.PutUint32(b.buf[b.pos:b.pos+4], v)
97 func (b *Buffer) DecodeUint32() uint32 {
98 v := binary.BigEndian.Uint32(b.buf[b.pos : b.pos+4])
103 func (b *Buffer) EncodeUint64(v uint64) {
104 binary.BigEndian.PutUint64(b.buf[b.pos:b.pos+8], v)
108 func (b *Buffer) DecodeUint64() uint64 {
109 v := binary.BigEndian.Uint64(b.buf[b.pos : b.pos+8])
114 func (b *Buffer) EncodeFloat64(v float64) {
115 binary.BigEndian.PutUint64(b.buf[b.pos:b.pos+8], math.Float64bits(v))
119 func (b *Buffer) DecodeFloat64() float64 {
120 v := math.Float64frombits(binary.BigEndian.Uint64(b.buf[b.pos : b.pos+8]))
125 func (b *Buffer) EncodeString(v string, length int) {
127 b.EncodeUint32(uint32(len(v)))
130 copy(b.buf[b.pos:b.pos+length], v)
134 func (b *Buffer) DecodeString(length int) string {
137 length = int(b.DecodeUint32())
138 v = b.buf[b.pos : b.pos+length]
140 v = b.buf[b.pos : b.pos+length]
141 if nul := bytes.Index(v, []byte{0x00}); nul >= 0 {
149 func BytesToString(b []byte) string {
150 sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&b))
151 stringHeader := reflect.StringHeader{Data: sliceHeader.Data, Len: sliceHeader.Len}
152 return *(*string)(unsafe.Pointer(&stringHeader))
155 func DecodeString(b []byte) string {
159 func DecodeStringZero(b []byte) string {
160 nul := bytes.Index(b, []byte{0x00})