Fix codec fallback and generate type imports
[govpp.git] / codec / codec.go
1 //  Copyright (c) 2020 Cisco and/or its affiliates.
2 //
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:
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
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.
14
15 package codec
16
17 import (
18         "encoding/binary"
19         "math"
20         "reflect"
21         "unsafe"
22 )
23
24 var order = binary.BigEndian
25
26 type Buffer struct {
27         pos int
28         buf []byte
29 }
30
31 func (b *Buffer) Bytes() []byte {
32         return b.buf[:b.pos]
33 }
34
35 func (b *Buffer) EncodeBool(v bool) {
36         if v {
37                 b.buf[b.pos] = 1
38         } else {
39                 b.buf[b.pos] = 0
40         }
41         b.pos += 1
42 }
43
44 func (b *Buffer) EncodeUint8(v uint8) {
45         b.buf[b.pos] = v
46         b.pos += 1
47 }
48
49 func (b *Buffer) EncodeUint16(v uint16) {
50         order.PutUint16(b.buf[b.pos:b.pos+2], v)
51         b.pos += 2
52 }
53
54 func (b *Buffer) EncodeUint32(v uint32) {
55         order.PutUint32(b.buf[b.pos:b.pos+4], v)
56         b.pos += 4
57 }
58
59 func (b *Buffer) EncodeUint64(v uint64) {
60         order.PutUint64(b.buf[b.pos:b.pos+8], v)
61         b.pos += 8
62 }
63
64 func (b *Buffer) EncodeFloat64(v float64) {
65         order.PutUint64(b.buf[b.pos:b.pos+8], math.Float64bits(v))
66         b.pos += 8
67 }
68
69 func (b *Buffer) EncodeString(v string, length int) {
70         copy(b.buf[b.pos:b.pos+length], v)
71         b.pos += length
72 }
73
74 func DecodeString(b []byte) string {
75         sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&b))
76         stringHeader := reflect.StringHeader{Data: sliceHeader.Data, Len: sliceHeader.Len}
77         return *(*string)(unsafe.Pointer(&stringHeader))
78 }