pack

package module
v0.0.0-...-5691c42 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2024 License: Unlicense Imports: 14 Imported by: 0

README ΒΆ

πŸ“¦ Pack

GoDoc Go Report Card

A Go lib for packing and unpacking Go types into binary data, for easy storage and network streaming.

⚑️ Basic Usage

package main

import (
    "fmt"
    
    "github.com/NublyBR/go-pack"
)

type CustomType struct {
    String string
    Number int
}

func main() {
    value := CustomType{
        String: "Hello, World!",
        Number: 123,
    }
    
    data, err := pack.Marshal(value)
    if err != nil {
        panic(err)
    }

    fmt.Printf("Value encoded as bytes: %q\n", data)
    
    var decoded CustomType
    
    err = pack.Unmarshal(&decoded)
    if err != nil {
        panic(err)
    }
    
    fmt.Printf("Value decoded from bytes: %+v\n", decoded)
}

βš™οΈ Installation

go get -u github.com/NublyBR/go-pack

πŸ“ˆ Benchmarks

$ go test -benchmem -bench=.

goos: windows
goarch: amd64
pkg: github.com/NublyBR/go-pack
cpu: Intel(R) Core(TM) i5-9600K CPU @ 3.70GHz
BenchmarkPacker-6        1200792             992.7 ns/op             168 B/op         10 allocs/op
BenchmarkUnpacker-6       599826              2010 ns/op             656 B/op         27 allocs/op
PASS
ok      github.com/NublyBR/go-pack      3.539s

The benchmarks are executed by packing/unpacking the following struct:

{
    String: "Hello, World!",
    Int:    1337_1337,
    Float:  1337.1337,
    Slice:  []any{"Hello, World!", 1337_1337, 1337.1337},
    Map: map[string]any{
        "abc": 1337_1337,
        "def": 1337.1337,
    },
}

Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

View Source
var (
	ErrInvalidPackedUint        = errors.New("invalid packed uint")
	ErrInvalidReceiver          = errors.New("invalid argument given to Decode, not a pointer type")
	ErrNil                      = errors.New("attempted to encode nil outside of pointer or interface context")
	ErrNilObject                = errors.New("may not encode nil in object mode")
	ErrMustBePointerToInterface = errors.New("in Objects mode, value given to Decode must be of type *interface{}")
)

Functions ΒΆ

func Marshal ΒΆ

func Marshal(data any, options ...Options) ([]byte, error)

Pack object into bytes

func Unmarshal ΒΆ

func Unmarshal(b []byte, data any, options ...Options) error

Unpack object from bytes

Types ΒΆ

type AfterUnpack ΒΆ

type AfterUnpack interface {
	// If a struct implements this interface, this function will be called
	// right after it was unpacked, by returning an error it will cause the
	// unpacker to early return said error and stop further unpacking.
	AfterUnpack() error
}

type BeforePack ΒΆ

type BeforePack interface {
	// If a struct implements this interface, this function will be called
	// right before it is about to be packed, by returning an error it will
	// cause the packer to early return said error and stop further packing.
	BeforePack() error
}

type ErrCantUseInInterfaceMode ΒΆ

type ErrCantUseInInterfaceMode struct {
	// contains filtered or unexported fields
}

func (*ErrCantUseInInterfaceMode) Error ΒΆ

func (e *ErrCantUseInInterfaceMode) Error() string

type ErrDataTooLarge ΒΆ

type ErrDataTooLarge struct {
	// contains filtered or unexported fields
}

func (*ErrDataTooLarge) Error ΒΆ

func (e *ErrDataTooLarge) Error() string

type ErrInvalidType ΒΆ

type ErrInvalidType struct {
	// contains filtered or unexported fields
}

func (*ErrInvalidType) Error ΒΆ

func (e *ErrInvalidType) Error() string

type ErrInvalidTypeKey ΒΆ

type ErrInvalidTypeKey struct {
	// contains filtered or unexported fields
}

func (*ErrInvalidTypeKey) Error ΒΆ

func (e *ErrInvalidTypeKey) Error() string

type ErrNotDefined ΒΆ

type ErrNotDefined struct {
	// contains filtered or unexported fields
}

func (*ErrNotDefined) Error ΒΆ

func (e *ErrNotDefined) Error() string

type Objects ΒΆ

type Objects interface {
	// Get ID of given Object
	GetID(item any) (uint, bool)

	// Get type of Object for given ID
	GetType(id uint) (reflect.Type, bool)

	// Insert new Objects
	Push(items ...any) Objects
}

func NewObjects ΒΆ

func NewObjects(items ...any) Objects

type Options ΒΆ

type Options struct {
	// Set the Packer/Unpacker to work in Object Mode, in which it will only
	// be able to pack/unpack pre-defined types stored in given `Objects`,
	// by tagging them with object IDs that are defined in `Objects`.
	//
	// In this mode each top-level object packed will come with it's ID prepended
	// to it, so you may unpack it from a stream without needing to know what object
	// is being decoded beforehand.
	WithObjects Objects

	// Allows you to defined a list of allowed types to exist within a struct field
	// with type: any, []any, [...]any or map[...]any;
	// by tagging it with `pack:"objects:mapkey"`
	WithSubObjects map[string]Objects

	// Limit the amount of bytes a packer is able to write for a top-level object
	// and the amount of bytes an unpacker is able to read.
	// Once the limit is about to be passed, an error of type ErrDataTooLarge will
	// be returned.
	SizeLimit uint64
}

type Packer ΒΆ

type Packer interface {
	// Encode object into stream
	//
	// Note: If a pointer is given to the encoder (*obj), then the decoder needs to receive a pointer to a pointer (**obj)
	// (unless object mode is enabled in the options)
	Encode(data any) error

	// Total bytes written to the underlying stream
	BytesWritten() uint64

	// Reset bytes written to 0
	ResetCounter()

	// Set objects
	SetObjects(objects Objects)

	// Set sub-objects
	SetSubObjects(subObjects map[string]Objects)

	// Set size limit
	SetSizeLimit(sizeLimit uint64)
}

func NewPacker ΒΆ

func NewPacker(writer io.Writer, options ...Options) Packer

type Socket ΒΆ

type Socket interface {
	// Read object from socket
	Read() (any, error)

	// Write object to socket
	Write(any) error

	// Read object from socket with a timeout
	ReadTimeout(timeout time.Duration) (any, error)

	// Write object to socket with a timeout
	WriteTimeout(data any, timeout time.Duration) error

	// Close socket
	Close() error

	// Get total bytes read
	BytesRead() uint64

	// Get total bytes written
	BytesWritten() uint64

	// Reset total bytes read
	ResetRead()

	// Reset total bytes written
	ResetWritten()

	// Deallocate write buffer to free memory
	ZeroBuffer()
}

func NewSocket ΒΆ

func NewSocket(conn net.Conn, options Options) Socket

type Unpacker ΒΆ

type Unpacker interface {
	// Decode object on stream into a pointer
	Decode(data any) error

	// Total bytes read from the underlying stream
	BytesRead() uint64

	// Reset bytes read to 0
	ResetCounter()

	// Set objects
	SetObjects(objects Objects)

	// Set sub-objects
	SetSubObjects(subObjects map[string]Objects)

	// Set size limit
	SetSizeLimit(sizeLimit uint64)
}

func NewUnpacker ΒΆ

func NewUnpacker(reader io.Reader, options ...Options) Unpacker

Jump to

Keyboard shortcuts

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