binary

package
v0.0.0-...-fd8fd09 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 14, 2017 License: Apache-2.0 Imports: 8 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package binary implements encoding and decoding of various primitive data types to and from a binary stream. The package holds BitStream for packing and unpacking sequences of bits, Float16 for dealing with 16 bit floating- point values and Reader/Writer for encoding and decoding various value types to a binary stream. There is also the higher level Encoder/Decoder that can be used for serializing object hierarchies.

The binary package defines a POD type as something with fixed size and layout. This allows all primitive types, fixed size arrays of POD types, and structures that contain only POD types. A Simple type is allowed more structure than a POD type, it may vary in size, which allows slices and maps, but must be of known type and not be able to contain cycles (thus no pointers, interfaces or slices of slices).

pod.Reader and pod.Writer provide a symmetrical pair of methods for encoding and decoding various data types to a binary stream. They can encode all POD and Simple types, but not complex structures. For performance reasons, each data type has a separate method for encoding and decoding rather than having a single pair of methods encoding and decoding boxed values in an interface{}.

binary.Encoder and binary.Decoder extend the pod.Reader and pod.Writer interfaces by also providing a symmetrical pair of methods for encoding and decoding object types.

Example (Object)

This example shows how to write a type with custom encode and decode methods, and send it over a "connection"

package main

import (
	"bytes"
	"fmt"
	"io"
	"log"

	"github.com/google/gapid/core/data/id"
	"github.com/google/gapid/framework/binary"
	"github.com/google/gapid/framework/binary/cyclic"
	"github.com/google/gapid/framework/binary/registry"
	"github.com/google/gapid/framework/binary/schema"
	"github.com/google/gapid/framework/binary/vle"
)

type ExampleObject struct{ Data string }
type ExampleClass struct{}

var ExampleID = id.ID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14}
var ExampleEntity = &binary.Entity{
	Package:  "binary_test",
	Identity: "ExampleObject",
	Fields: []binary.Field{
		{Declared: "Data", Type: &schema.Primitive{Name: "string", Method: schema.String}},
	},
}

func (*ExampleObject) Class() binary.Class {
	return (*ExampleClass)(nil)
}

func (*ExampleClass) Schema() *binary.Entity {
	return ExampleEntity
}

func (*ExampleClass) ID() id.ID {
	return ExampleID
}

func (*ExampleClass) New() binary.Object {
	return &ExampleObject{}
}

func (*ExampleClass) Encode(e binary.Encoder, obj binary.Object) {
	o := obj.(*ExampleObject)
	e.String(o.Data)
}

func (*ExampleClass) Decode(d binary.Decoder) binary.Object {
	o := &ExampleObject{}
	o.Data = d.String()
	return o
}

func (*ExampleClass) DecodeTo(d binary.Decoder, obj binary.Object) {
	o := obj.(*ExampleObject)
	o.Data = d.String()
}

func init() {
	registry.Global.Add((*ExampleObject)(nil).Class())
}

// This example shows how to write a type with custom encode and decode
// methods, and send it over a "connection"
func main() {
	// Create a connected input and output stream for example purposes.
	in := io.Reader(&bytes.Buffer{})
	out := in.(io.Writer)

	// Build an encoder and decoder on top of the stream
	e := cyclic.Encoder(vle.Writer(out))
	d := cyclic.Decoder(vle.Reader(in))

	// Encode an object onto the stream
	e.Object(&ExampleObject{"MyObject"})
	if e.Error() != nil {
		log.Fatalf("Encode gave unexpected error: %v", e.Error())
	}

	// Read the object back
	o := d.Object()
	if d.Error() == nil {
		fmt.Printf("read %q\n", o.(*ExampleObject).Data)
	} else {
		log.Fatalf("Decode gave unexpected error: %v", d.Error())
	}

}
Output:
read "MyObject"

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func InitEntity

func InitEntity(t reflect.Type, makeType MakeTypeFun, e *Entity)

InitEntity initializes a schema entity 'e' from the Go reflect type 't'. 'makeType' is used to build schema types for sub-types.

func RegisterBoxer

func RegisterBoxer(boxer Boxer)

RegisterBoxer adds a new boxing function to the boxers attempted when an unknown type is encountered.

func TypeName

func TypeName(t reflect.Type, pkg string) string

TypeName returns a string for the typename in a form compatible with the name codegen would use for this schema type. If t is in the package pkg a relative name should be used.

func Unbox

func Unbox(o Object) (interface{}, error)

Unbox returns the value in o wrapped by a call to Box. If o is not a boxed value ErrNotBoxedValue is returned.

Types

type BitStream

type BitStream struct {
	Data     []byte // The byte slice containing the bits
	ReadPos  uint32 // The current read offset from the start of the Data slice (in bits)
	WritePos uint32 // The current write offset from the start of the Data slice (in bits)
}

BitStream provides methods for reading and writing bits to a slice of bytes. Bits are packed in a least-significant-bit to most-significant-bit order.

func (*BitStream) Read

func (s *BitStream) Read(count uint32) uint64

Read reads the specified number of bits from the BitStream, increamenting the ReadPos by the specified number of bits and returning the bits packed into a uint64. The bits are packed into the uint64 from LSB to MSB.

func (*BitStream) ReadBit

func (s *BitStream) ReadBit() uint64

ReadBit reads a single bit from the BitStream, incrementing ReadPos by one.

func (*BitStream) Write

func (s *BitStream) Write(bits uint64, count uint32)

Write writes the specified number of bits from the packed uint64, increamenting the WritePos by the specified number of bits. The bits are read from the uint64 from LSB to MSB.

func (*BitStream) WriteBit

func (s *BitStream) WriteBit(bit uint64)

WriteBit writes a single bit to the BitStream, incrementing WritePos by one.

type Boxer

type Boxer func(interface{}) Object

type Class

type Class interface {
	// Encode writes the supplied object to the supplied Encoder.
	// The object must be a type the Class understands, the implementation is
	// allowed to panic if it is not.
	Encode(Encoder, Object)

	// DecodeTo reads into the supplied object from the supplied Decoder.
	// The object must be a type the Class understands, the implementation is
	// allowed to panic if it is not.
	DecodeTo(Decoder, Object)

	// Returns the type descriptor for the class.
	Schema() *Entity
}

Class represents a struct type in the binary registry.

type Decoder

type Decoder interface {
	pod.Reader
	// Entity supports reading a binary.Entity from the stream.
	Entity() *Entity
	// Struct decodes an sub-structure from the stream. The type of the
	// sub-structure in the stream depends on the state of the decoder.
	// It must be compatible with the object passed or it will panic.
	Struct(Object)
	// Variant decodes and returns an Object from the stream. The Class in the
	// stream must have been previously registered with binary.registry.Add.
	Variant() Object
	// Object decodes and returns an Object from the stream. Object instances
	// that were encoded multiple times may be decoded and returned as a shared,
	// single instance. The Class in the stream must have been previously
	// registered with binary.registry.Add.
	Object() Object
	// Lookup the upgrade decoder for decoding this type of entity.
	Lookup(*Entity) UpgradeDecoder
	// GetMode gets the current mode of the decoder.
	GetMode() Mode
}

Decoder extends Reader with additional methods for decoding objects.

type Encoder

type Encoder interface {
	pod.Writer
	// Entity writes a binary.Entity to the stream.
	// See Entity for details of what modes are supported.
	Entity(e *Entity)
	// Struct encodes a struct with no type preamble and no sharing.
	Struct(obj Object)
	// Variant encodes an Object with no sharing. The type of obj must have
	// been previously registered with binary.registry.Add.
	Variant(obj Object)
	// Object encodes an Object, optionally encoding objects only on the first
	// time it sees them. The type of obj must have been previously registered
	// with binary.registry.Add.
	Object(obj Object)
	// GetMode gets the current mode of the encoder.
	GetMode() Mode
	// SetMode controls the current mode of the encoder.
	SetMode(mode Mode)
}

Encoder extends Writer with additional methods for encoding objects.

type Entity

type Entity struct {
	Package  string    // The package that declared the struct.
	Display  string    // The display name of the class, not set in compact form.
	Identity string    // The true name of the class.
	Version  string    // The version string of the class, if set.
	Exported bool      // Whether the class is exported from its package, not set in compact form.
	Fields   FieldList // Descriptions of the fields of the class.
	Metadata []Object  // The metadata for the class, not set in compact form
	// contains filtered or unexported fields
}

Entity represents the encodable type information for an object. In its compact mode, the entity contains only the information strictly required to generate its signature, and not any of metadata or display names.

func (*Entity) Format

func (e *Entity) Format(f fmt.State, c rune)

Format implements the fmt.Formatter interface

func (*Entity) IsPOD

func (e *Entity) IsPOD() bool

IsPOD checks if the entity is a valid POD type

func (*Entity) IsSimple

func (e *Entity) IsSimple() bool

IsSimple checks if the entity is a valid Simple type

func (*Entity) Name

func (e *Entity) Name() string

Name returns the name of the Entity.

func (*Entity) Signature

func (e *Entity) Signature() Signature

Signature returns a canonical string representations of an entities signature. If two entities have the same Signature, the are assumed to represent the same type

func (*Entity) Subspace

func (e *Entity) Subspace() *Subspace

Subspace returns the subspace for the entity. The subspace of the entity is the the catenation of the field subtypes with inlines expanded.

type ErrNotBoxedValue

type ErrNotBoxedValue struct {
	Object Object // The object that is not a boxed value.
}

ErrNotBoxedValue is returned when an Object is passed to Unbox that was not previously returned by a call to Box.

func (ErrNotBoxedValue) Error

func (e ErrNotBoxedValue) Error() string

Error returns the error message.

type ErrUnboxable

type ErrUnboxable struct {
	Value interface{} // The value that could not be encoded.
}

ErrUnboxable is returned when a non-boxable value type is passed to Box.

func (ErrUnboxable) Error

func (e ErrUnboxable) Error() string

Error returns the error message.

type Field

type Field struct {
	Declared string // The name of the field, not set in compact form.
	Type     Type   // The type stored in the field.
}

Field represents a name/type pair for a field in an Object.

func (Field) Name

func (f Field) Name() string

type FieldList

type FieldList []Field

FieldList is a slice of fields.

func (FieldList) Find

func (l FieldList) Find(name string) int

Find searches the field list of the field with the specified name, returning the index of the field if found, otherwise -1.

type Frozen

type Frozen struct{}

Frozen is used to tag structures that represent past versions of types which may appear in old capture files. Frozen must be include a "name" tag which identifies the name of the struct now in use. Manual upgrading is provided with a function of the form:

func (before *FrozenStruct) upgrade(after *GenerateStruct)

See binary/test/frozen.go for examples

func (Frozen) Class

func (Frozen) Class() Class

type FrozenClassBase

type FrozenClassBase struct{}

func (*FrozenClassBase) Encode

func (c *FrozenClassBase) Encode(e Encoder, o Object)

FrozenClassBase provides Encode() so that they satisfy the above Class interface, but they should never be called.

type Generate

type Generate struct{}

Generate is used to tag structures that need an auto generated Class. The codergen function searches packages for structs that have this type as an anonymous field, and then automatically generates the encoding and decoding functionality for those structures. For example, the following struct would create the Class with methods needed to encode and decode the Name and Value fields, and register that class. The embedding will also fully implement the binary.Object interface, but with methods that panic. This will get overridden with the generated Methods. This is important because it means the package is resolvable without the generated code, which means the types can be correctly evaluated during the generation process.

type MyNamedValue struct {
   binary.Generate
   Name  string
   Value []byte
}

Code generation can be customized with tags:

type MySomethingThatWontHaveAJavaEquivalent struct {
    binary.Generate `java:"disable"`
}

We currently use the following tags:

cpp
java
disable
display
globals
id
identity
implements
javaDefineEmptyArrays:"true"
   If applied to a struct, any slice fields being read from the wire that
   have a length of zero will be set to the same instance of an empty array
   to avoid unnecessary allocations. e.g. ...service.atom.Observations.
version

func (Generate) Class

func (Generate) Class() Class

type MakeTypeFun

type MakeTypeFun func(
	t reflect.Type, tag reflect.StructTag, makeType MakeTypeFun, pkg string) Type

MakeTypeFun is a function type for building schema types. The function makes a schema type corresponding to t. If t has sub-types then makeType will be called to build them. Names given to schema sub-types should be relative to pkg.

type Mode

type Mode uint32

Mode controls the encoded representation, adjusting which fields get encoded

const (
	Compact Mode = iota
	Full
)

func (Mode) String

func (m Mode) String() string

type Object

type Object interface {
	// Class returns the serialize information and functionality for this type.
	// The method should be valid on a nil pointer.
	Class() Class
}

Object is the interface to any class that wants to be encoded/decoded.

func Box

func Box(v interface{}) (Object, error)

Box returns v wrapped by a struct implementing binary.Object. If v is not boxable then ErrUnboxable is returned.

func ObjectCast

func ObjectCast(obj Object) Object

ObjectCast is automatically called by the generated decoders.

type Signature

type Signature string

type Subspace

type Subspace struct {
	Inline   bool     // true if the schema object inlines the encoding (arrays)
	Counted  bool     // true if the schema type is a counted (slice, map)
	SubTypes TypeList // the complete list of subtypes
	// contains filtered or unexported fields
}

Subspace represents the sub-types which need decoder support for nested types.

func (*Subspace) ExpandSubTypes

func (s *Subspace) ExpandSubTypes() TypeList

ExpandSubTypes returns the list of sub-types of this subspace with any inline sub-types expanded.

type SubspaceType

type SubspaceType interface {
	// Returns true if Subspace() will return non-nil.
	HasSubspace() bool
	// Subspace returns the subspace for this type. The subspace represents
	// the sub-types which need decoder support for nested types.
	// Nil means that this kind of schema object never has subtypes.
	Subspace() *Subspace
}

SubspaceType is the interface provides by schema types in order for them to provide sub-type information to the decoder.

type Type

type Type interface {
	SubspaceType
	String() string         // The true name of the type.
	Representation() string // The encoded representation of the type.
	EncodeValue(e Encoder, value interface{})
	DecodeValue(d Decoder) interface{}
	Format(f fmt.State, c rune)
	IsPOD() bool
	IsSimple() bool
}

Type represents the common interface to all type objects in the schema.

type TypeList

type TypeList []SubspaceType

TypeList used to represent the entities of any composed subtypes which need decoding.

type UpgradeDecoder

type UpgradeDecoder interface {
	// New constructs a new Object that this decoder handles.
	// For a frozen decoder, this would be the new version, not the frozen one, and as such the type returned may not
	// match the schema this decoder was registered against.
	New() Object
	// DecodeTo reads into the supplied object from the supplied Decoder.
	// The object must be the same concrete type that New would create, the
	// implementation is allowed to panic if it is not.
	DecodeTo(Decoder, Object)
}

UpgradeDecoder provides a decoder interface which maybe used to decode a stream from an old version into a newer version.

Directories

Path Synopsis
Package any contains Object wrappers for Plain-Old-Data types.
Package any contains Object wrappers for Plain-Old-Data types.
Object encoding details
Object encoding details
Package schema implements rtti for the binary system.
Package schema implements rtti for the binary system.
Package vle implements pod.Reader and pod.Writer using a variable length encoding format.
Package vle implements pod.Reader and pod.Writer using a variable length encoding format.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL