github.com/jlmucb/cloudproxy@v0.0.0-20170830161738-b5aa0b619bc4/go/apps/mixnet/encoding.go (about) 1 // Copyright (c) 2016, Google Inc. 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 mixnet 16 17 import ( 18 "encoding/binary" 19 20 "github.com/golang/protobuf/proto" 21 ) 22 23 // GetID returns the cell (circuit) ID. 24 func getID(cell []byte) uint64 { 25 id := binary.LittleEndian.Uint64(cell[ID:]) 26 return id 27 } 28 29 // Transform a directive into a cell, encoding its length and padding it to the 30 // length of a cell. 31 func marshalDirective(id uint64, d *Directive) ([]byte, error) { 32 db, err := proto.Marshal(d) 33 if err != nil { 34 return nil, err 35 } 36 dirBytes := uint64(len(db)) 37 38 cell := make([]byte, CellBytes) 39 binary.LittleEndian.PutUint64(cell[ID:], id) 40 41 cell[TYPE] = dirCell 42 binary.LittleEndian.PutUint64(cell[BODY:], dirBytes) 43 44 // Throw an error if encoded Directive doesn't fit into a cell. 45 if dirBytes+LEN_SIZE+1 > CellBytes { 46 return nil, errCellLength 47 } 48 copy(cell[BODY+LEN_SIZE:], db) 49 50 return cell, nil 51 } 52 53 // Parse a directive from a cell. 54 func unmarshalDirective(cell []byte, d *Directive) error { 55 if cell[TYPE] != dirCell { 56 return errCellType 57 } 58 59 dirBytes := binary.LittleEndian.Uint64(cell[BODY:]) 60 if err := proto.Unmarshal(cell[BODY+LEN_SIZE:BODY+LEN_SIZE+int(dirBytes)], d); err != nil { 61 return err 62 } 63 64 return nil 65 }