github.com/jlmucb/cloudproxy@v0.0.0-20170830161738-b5aa0b619bc4/go/tao/auth/buffer.go (about) 1 // Copyright (c) 2014, Kevin Walsh. All rights reserved. 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 auth 16 17 import ( 18 "encoding/binary" 19 "errors" 20 "fmt" 21 "io" 22 ) 23 24 // Buffer holds partially encoded or decode auth elemnts. 25 // Note: We could do capacity-doubling, etc., but we favor simplicity for now. 26 type Buffer struct { 27 buf []byte 28 } 29 30 // Bytes returns the unconsumed portion of the buffer. 31 func (buf *Buffer) Bytes() []byte { 32 return buf.buf 33 } 34 35 // EncodeVarint encodes an int as a (non zig-zag) varint, growing the buffer. 36 func (buf *Buffer) EncodeVarint(i int64) { 37 b := make([]byte, 10) // int64 as varint is max 10 bytes 38 n := binary.PutUvarint(b, uint64(i)) 39 buf.buf = append(buf.buf, b[0:n]...) 40 } 41 42 // DecodeVarint decodes an int, shrinking the buffer. 43 func (buf *Buffer) DecodeVarint() (int64, error) { 44 i, n := binary.Uvarint(buf.buf) 45 if n == 0 { 46 return 0, io.ErrUnexpectedEOF 47 } else if n < 0 { 48 return 0, errors.New("varint overflow") 49 } 50 buf.buf = buf.buf[n:] 51 return int64(i), nil 52 } 53 54 // EncodeBool converts b to an int then calls EncodeVarint. 55 func (buf *Buffer) EncodeBool(b bool) { 56 if b { 57 buf.EncodeVarint(1) 58 } else { 59 buf.EncodeVarint(0) 60 } 61 } 62 63 // DecodeBool calls DecodeVarint then converts the result to a bool. 64 func (buf *Buffer) DecodeBool() (bool, error) { 65 i, err := buf.DecodeVarint() 66 return (i == 1), err 67 } 68 69 // EncodeString encodes a string as a length and byte array, growing the buffer. 70 func (buf *Buffer) EncodeString(s string) { 71 bytes := []byte(s) 72 buf.EncodeVarint(int64(len(bytes))) 73 buf.buf = append(buf.buf, bytes...) 74 } 75 76 // DecodeString decodes a string, shrinking the buffer. 77 func (buf *Buffer) DecodeString() (string, error) { 78 n, err := buf.DecodeVarint() 79 if err != nil { 80 return "", err 81 } 82 if n < int64(0) || n > int64(len(buf.buf)) { 83 return "", fmt.Errorf("invalid length: %d", n) 84 } 85 s := string(buf.buf[:n]) 86 buf.buf = buf.buf[n:] 87 return s, nil 88 }