bogo

package module
v0.0.0-...-eca9833 Latest Latest
Warning

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

Go to latest
Published: Dec 22, 2025 License: MIT Imports: 8 Imported by: 0

README

Bogo - High-Performance Binary Serialization for Go

Bogo is a fast, compact binary serialization format with embedded key fields and type information. It provides efficient encoding and decoding of data types with high performance and zero-copy operations.

Bogo is ideal when you need JSON-like simplicity with binary format performance, especially for selective field deserialization in complex data types.

Features

  • JSON-Compatible API: Drop-in replacement for encoding/json with familiar Marshal/Unmarshal functions
  • High Performance: Up to 3x faster deserialization compared to JSON
  • Compact Binary Format: Efficient variable-length encoding reduces payload size
  • Comprehensive Type Support: Supports all primitive types plus arrays, objects, and binary data
  • Streaming API: Memory-efficient streaming encoding and decoding
  • Configurable Validation: Optional UTF-8 validation, depth limits, and size constraints
  • Field-Specific Optimization: Revolutionary selective field decoding with up to 334x performance improvement and 113x memory reduction

Supported Types

Primitive Type Bogo Type Description
nil TypeNull Null values
bool TypeBoolTrue/TypeBoolFalse Boolean values
string TypeString UTF-8 strings with variable-length encoding
byte TypeByte Single byte values
int, int8, int16, int32, int64 TypeInt Signed integers with VarInt encoding
uint, uint8, uint16, uint32, uint64 TypeUint Unsigned integers with VarInt encoding
float32, float64 TypeFloat IEEE 754 floating-point numbers
[]byte TypeBlob Binary data with length prefix
time TypeTimestamp Unix timestamps
[]any{} TypeArray Heterogeneous arrays
[]int{} TypeTypedArray Homogeneous typed arrays
object TypeObject Key-value objects

Installation

go get github.com/bubunyo/bogo

Quick Start

Basic Usage
package main

import (
    "fmt"
    "log"
    "github.com/bubunyo/bogo"
)

type User struct {
    ID       int    `json:"id"`
    Name     string `json:"name"`
    Email    string `json:"email"`
    Active   bool   `json:"active"`
}

func main() {
    user := User{
        ID:     123,
        Name:   "John Doe",
        Email:  "john@example.com",
        Active: true,
    }

    // Marshal to binary format
    data, err := bogo.Marshal(user)
    if err != nil {
        log.Fatal(err)
    }

    // Unmarshal from binary format
    var decoded User
    err = bogo.Unmarshal(data, &decoded)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Original: %+v\n", user)
    fmt.Printf("Decoded:  %+v\n", decoded)
}
Streaming API
package main

import (
    "bytes"
    "log"
    "github.com/bubunyo/bogo"
)

func main() {
    data := map[string]interface{}{
        "message": "Hello, World!",
        "count":   42,
        "active":  true,
    }

    // Streaming encoding
    var buf bytes.Buffer
    encoder := bogo.NewEncoder(&buf)
    if err := encoder.Encode(data); err != nil {
        log.Fatal(err)
    }

    // Streaming decoding
    decoder := bogo.NewDecoder(&buf)
    var result map[string]interface{}
    if err := decoder.Decode(&result); err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Streamed data: %+v\n", result)
}

Performance

Bogo delivers significant performance improvements over JSON serialization:

Benchmark Results (Apple M2, 8 cores)
Simple Data (small objects):
- JSON Serialize:         709 ns/op    272 B/op    3 allocs/op
- Bogo Serialize:         964 ns/op   1088 B/op   18 allocs/op  (0.74x speed)
- MessagePack:            442 ns/op    320 B/op    4 allocs/op

- JSON Deserialize:      1910 ns/op    336 B/op    7 allocs/op
- Bogo Deserialize:       564 ns/op    488 B/op   16 allocs/op  (3.39x faster)
- MessagePack:            623 ns/op    168 B/op    4 allocs/op

Complex Data (nested structures):
- JSON Serialize:        6422 ns/op   2514 B/op   36 allocs/op
- Bogo Serialize:       15449 ns/op  18939 B/op  291 allocs/op  (0.42x speed)
- MessagePack:           3650 ns/op   2472 B/op   17 allocs/op

- JSON Deserialize:     19254 ns/op   3128 B/op   93 allocs/op
- Bogo Deserialize:      4341 ns/op   4464 B/op  101 allocs/op  (4.43x faster)
- MessagePack:           7888 ns/op   2921 B/op   86 allocs/op

Array Data (large arrays):
- JSON Serialize:       23173 ns/op   3889 B/op   15 allocs/op
- Bogo Serialize:       54654 ns/op  41025 B/op 1040 allocs/op  (0.42x speed)
- MessagePack:          10520 ns/op   8178 B/op    8 allocs/op

- JSON Deserialize:     56072 ns/op  21624 B/op  647 allocs/op
- Bogo Deserialize:      5822 ns/op   6016 B/op  119 allocs/op  (9.63x faster)
- MessagePack:          18743 ns/op  11027 B/op  416 allocs/op

Binary Data (large byte arrays):
- JSON Serialize:       12452 ns/op  16904 B/op   17 allocs/op
- Bogo Serialize:       12936 ns/op  64081 B/op   28 allocs/op  (0.96x speed)
- MessagePack:           3876 ns/op  16256 B/op    5 allocs/op

- JSON Deserialize:     95240 ns/op  16248 B/op   32 allocs/op
- Bogo Deserialize:       961 ns/op    872 B/op   17 allocs/op  (99.1x faster)
- MessagePack:           3346 ns/op  12292 B/op   21 allocs/op

Advanced Configuration

Decoder Options
decoder := bogo.NewConfigurableDecoder(
    bogo.WithDecoderMaxDepth(50),        // Limit nesting depth
    bogo.WithDecoderStrictMode(true),    // Enable strict validation
    bogo.WithMaxObjectSize(1024*1024),   // 1MB size limit
    bogo.WithUTF8Validation(true),       // Validate UTF-8 strings
    bogo.WithUnknownTypes(false),        // Reject unknown types
    bogo.WithSelectiveFields([]string{"target_field"}), // Optimize for specific fields
)

result, err := decoder.Decode(data)
Field-Specific Optimization

Bogo includes field-specific decoding optimization that provides up to 334x performance improvement when you only need specific fields from large objects.

Performance Results (Apple M2, 8 cores)
BEFORE OPTIMIZATION:
BenchmarkFieldDecoding_Full-8               	   17913	     67037 ns/op	   48057 B/op	    1138 allocs/op
BenchmarkFieldDecoding_Selective-8          	   37464	     41110 ns/op	   31456 B/op	     826 allocs/op

AFTER OPTIMIZATION:
BenchmarkFieldDecoding_WithOptimization-8   	 2121243	       524.6 ns/op	     424 B/op	       7 allocs/op
Performance Improvements
  • 128x faster than full decoding (67,037ns → 524ns)
  • 78x faster than selective decoding without optimization (41,110ns → 524ns)
  • 163x fewer allocations than full decoding (1,138 → 7)
  • 118x fewer allocations than selective decoding (826 → 7)
  • 113x less memory usage than full decoding (48,057B → 424B)
  • 74x less memory usage than selective decoding (31,456B → 424B)
Usage Examples

Method 1: Explicit Field Selection

// Only decode "id" and "name" fields from a complex object
optimizedDecoder := bogo.NewConfigurableDecoder(
    bogo.WithSelectiveFields([]string{"id", "name"}),
)

result, err := optimizedDecoder.Decode(largeObjectData)
// 334x faster than decoding the entire object!

Method 2: Automatic Optimization with Struct Tags

// Define a struct with only the fields you need
type UserSummary struct {
    ID   int64  `json:"id"`
    Name string `json:"name"`
    // Large fields like "profile_data", "history", etc. are automatically skipped
}

var summary UserSummary
err := bogo.Unmarshal(complexUserData, &summary)
// Automatically optimized - only decodes the fields present in the struct!
How It Works

The optimization uses field jumping to skip over unwanted data:

  1. Field Detection: The decoder identifies which fields are needed
  2. Smart Skipping: Large, complex fields are skipped entirely using size information
  3. Direct Access: Only target fields are parsed and decoded
  4. Memory Efficiency: Unused data never allocates memory
Ideal Use Cases
  • Large API responses where you only need specific fields
  • Database records with large blob fields you want to skip
  • Microservices extracting metadata from complex payloads
  • Log processing where you need specific fields from large log entries
  • Real-time systems requiring ultra-low latency field extraction
Encoder Options
encoder := bogo.NewConfigurableEncoder(
    bogo.WithValidation(true),           // Enable validation
    bogo.WithCompression(false),         // Disable compression
)

data, err := encoder.Encode(value)

Binary Format

For complete technical details about the binary format, encoding algorithms, type specifications, and implementation notes, see the Binary Format Specification.

API Reference

Core Functions
// Marshal encodes a value to bogo binary format
func Marshal(v interface{}) ([]byte, error)

// Unmarshal decodes bogo binary data into a value
func Unmarshal(data []byte, v interface{}) error
Streaming API
// NewEncoder creates a streaming encoder
func NewEncoder(w io.Writer) *StreamEncoder

// NewDecoder creates a streaming decoder  
func NewDecoder(r io.Reader) *StreamDecoder
Configuration
// NewConfigurableEncoder creates an encoder with options
func NewConfigurableEncoder(options ...EncoderOption) *Encoder

// NewConfigurableDecoder creates a decoder with options
func NewConfigurableDecoder(options ...DecoderOption) *Decoder

Zero Values vs Nil Values

Bogo makes a clear distinction between zero values and nil values for robust data handling:

Zero Values (Type-Safe)

Zero values are preserved with their type information:

  • "" (empty string) → encodes as TypeString with 0 length → decodes as ""
  • 0 → encodes as TypeInt → decodes as int64(0)
  • false → encodes as TypeBoolFalse → decodes as false
  • []any{} → encodes as TypeArray with 0 elements → decodes as []any{}
  • time.Time{} → encodes as TypeTimestamp → decodes as zero time
Nil Values (Null)

Nil values are encoded uniformly as null:

  • nil → encodes as TypeNull → decodes as nil
  • (*string)(nil) → encodes as TypeNull → decodes as nil
  • map[string]any(nil) → encodes as TypeNull → decodes as nil
Example Usage
data := map[string]any{
    "zero_string": "",           // Will remain empty string after decode
    "zero_number": 0,            // Will remain 0 after decode  
    "zero_bool":   false,        // Will remain false after decode
    "nil_value":   nil,          // Will remain nil after decode
}

encoded, _ := bogo.Marshal(data)
var decoded map[string]any
bogo.Unmarshal(encoded, &decoded)

fmt.Println(decoded["zero_string"])  // "" (empty string, not nil)
fmt.Println(decoded["zero_number"])  // 0 (zero, not nil)
fmt.Println(decoded["zero_bool"])    // false (not nil)
fmt.Println(decoded["nil_value"])    // nil

Testing

Run the test suite:

go test ./...

Run benchmarks:

go test -bench=. -benchmem

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -am 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Overview

Package bogo provides fast, compact binary serialization with JSON-compatible API.

Bogo is a high-performance binary serialization format designed for efficient encoding and decoding of complex data types. It offers significant performance improvements over JSON while maintaining API compatibility, making it a drop-in replacement for encoding/json in many use cases.

Key Features

  • JSON-Compatible API: Familiar Marshal/Unmarshal functions
  • High Performance: Up to 99x faster deserialization than JSON
  • Compact Binary Format: Efficient variable-length encoding
  • Selective Field Decoding: Revolutionary optimization for large objects
  • Zero vs Nil Distinction: Robust handling of zero and null values
  • Streaming Support: Memory-efficient streaming encoding/decoding

Basic Usage

type User struct {
    ID    int64  `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email"`
}

user := User{ID: 123, Name: "John", Email: "john@example.com"}

// Marshal to binary format
data, err := bogo.Marshal(user)
if err != nil {
    log.Fatal(err)
}

// Unmarshal from binary format
var decoded User
err = bogo.Unmarshal(data, &decoded)
if err != nil {
    log.Fatal(err)
}

Streaming API

// Encoding
var buf bytes.Buffer
encoder := bogo.NewEncoder(&buf)
err := encoder.Encode(data)

// Decoding
decoder := bogo.NewDecoder(&buf)
var result interface{}
err = decoder.Decode(&result)

Advanced Configuration

// Configurable decoder with selective field optimization
decoder := bogo.NewConfigurableDecoder(
    bogo.WithSelectiveFields([]string{"id", "name"}), // Only decode these fields
    bogo.WithDecoderMaxDepth(50),                     // Limit nesting depth
    bogo.WithDecoderStrictMode(true),                 // Enable strict validation
)

result, err := decoder.Decode(largeObjectData)
// Up to 334x faster than decoding the entire object!

Zero Values vs Nil Values

Bogo maintains a clear distinction between zero values and nil values:

  • Zero values (e.g., "", 0, false) are preserved with type information
  • Nil values are encoded as TypeNull and decode back to nil
  • Enables tri-state logic: true/false/unknown, value/zero/unset

For complete technical specifications, see: https://github.com/bubunyo/bogo/blob/main/spec.md

Example
package main

import (
	"fmt"
	"log"

	"github.com/bubunyo/bogo"
)

func main() {
	type User struct {
		ID    int64  `json:"id"`
		Name  string `json:"name"`
		Email string `json:"email"`
		Age   int    `json:"age"`
	}

	// Create a user
	user := User{
		ID:    12345,
		Name:  "John Doe",
		Email: "john@example.com",
		Age:   30,
	}

	// Marshal to Bogo binary format
	data, err := bogo.Marshal(user)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Encoded %d bytes\n", len(data))

	// Unmarshal back to struct
	var decoded User
	err = bogo.Unmarshal(data, &decoded)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Name: %s, Age: %d\n", decoded.Name, decoded.Age)
}
Output:

Encoded 68 bytes
Name: John Doe, Age: 30

Index

Examples

Constants

View Source
const (
	TypeNull = iota
	TypeBoolTrue
	TypeBoolFalse
	TypeString
	TypeByte
	TypeInt
	TypeUint
	TypeFloat
	TypeBlob
	TypeTimestamp

	TypeArray
	TypeTypedArray
	TypeObject
)
View Source
const (

	// Version helps determine which encoders/decoders to use
	Version byte = 0x00 // version 0
)

Type constants

Variables

This section is empty.

Functions

func Decode

func Decode(data []byte) (any, error)

Decode deserializes Bogo binary data back into a Go value.

This is the primary decoding function that converts Bogo binary format back to Go values with automatic type reconstruction. It supports all types that can be encoded with Encode().

Example:

decoded, err := bogo.Decode(binaryData)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Decoded value: %v\n", decoded)

Type mapping:

  • TypeNull → nil
  • TypeString → string
  • TypeInt → int64
  • TypeUint → uint64
  • TypeFloat → float64
  • TypeArray → []any
  • TypeObject → map[string]any
  • And more...

Returns the decoded value and any decoding error.

func Encode

func Encode(v any) ([]byte, error)

Encode serializes a value to the Bogo binary format.

This is the primary encoding function that converts Go values to compact binary representation. It handles all supported types including primitives, arrays, objects, and structs with automatic type detection.

Example:

data, err := bogo.Encode("hello world")
if err != nil {
    log.Fatal(err)
}

Supported types:

  • nil, bool, string, byte
  • int, int8, int16, int32, int64
  • uint, uint8, uint16, uint32, uint64
  • float32, float64
  • []byte, time.Time
  • []any, []string, []int, []float64, etc.
  • map[string]any, structs

Returns the binary representation and any encoding error.

func Marshal

func Marshal(v any) ([]byte, error)

Marshal encodes a value to Bogo binary format.

Marshal is compatible with json.Marshal and can be used as a drop-in replacement in most cases. It traverses the value v recursively and encodes it using the Bogo binary format.

Example:

type Person struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

p := Person{Name: "Alice", Age: 30}
data, err := bogo.Marshal(p)
if err != nil {
    log.Fatal(err)
}

Struct fields are encoded based on json struct tags, following the same conventions as encoding/json (omitempty, field renaming, etc.).

Returns the Bogo binary representation of v and any encoding error.

func SetDefaultDecoder

func SetDefaultDecoder(decoder *Decoder)

SetDefaultDecoder sets the default decoder used by Unmarshal

func SetDefaultEncoder

func SetDefaultEncoder(encoder *Encoder)

SetDefaultEncoder sets the default encoder used by Marshal

func Unmarshal

func Unmarshal(data []byte, v any) error

Unmarshal parses Bogo binary data and stores the result in the value pointed to by v.

Unmarshal is compatible with json.Unmarshal and can be used as a drop-in replacement. It decodes the Bogo binary data and assigns the result to the value pointed to by v.

Example:

var person Person
err := bogo.Unmarshal(data, &person)
if err != nil {
    log.Fatal(err)
}

var result map[string]any
err = bogo.Unmarshal(data, &result)
if err != nil {
    log.Fatal(err)
}

The destination v must be a pointer to a value where the decoded result will be stored. Unmarshal handles type conversions automatically (e.g., int to int64, float32 to float64).

Returns an error if the data cannot be decoded or assigned to v.

Types

type Decoder

type Decoder struct {
	// Configuration options
	MaxDepth          int      // Maximum nesting depth for objects/arrays (0 = unlimited)
	StrictMode        bool     // Strict type checking and validation
	AllowUnknownTypes bool     // Allow unknown type IDs for forward compatibility
	MaxObjectSize     int64    // Maximum size for objects/arrays (0 = unlimited)
	ValidateUTF8      bool     // Validate UTF-8 encoding in strings
	TagName           string   // Struct tag name to use (default: "json" for compatibility)
	SelectiveFields   []string // List of specific fields to decode (optimization)
	// contains filtered or unexported fields
}

Decoder provides structured decoding with configurable options

func GetDefaultDecoder

func GetDefaultDecoder() *Decoder

GetDefaultDecoder returns the current default decoder

func NewConfigurableDecoder

func NewConfigurableDecoder(options ...DecoderOption) *Decoder

NewConfigurableDecoder creates a new Decoder with optional configuration

func (*Decoder) Decode

func (d *Decoder) Decode(data []byte) (any, error)

Decode decodes data using the configured decoder

func (*Decoder) DecodeFrom

func (d *Decoder) DecodeFrom(r io.Reader) (any, error)

DecodeFrom decodes data from an io.Reader

type DecoderOption

type DecoderOption func(*Decoder)

DecoderOption is a function type for configuring a Decoder

func WithDecoderMaxDepth

func WithDecoderMaxDepth(depth int) DecoderOption

Decoder option functions

func WithDecoderStrictMode

func WithDecoderStrictMode(strict bool) DecoderOption

func WithDecoderStructTag

func WithDecoderStructTag(tagName string) DecoderOption

func WithMaxObjectSize

func WithMaxObjectSize(size int64) DecoderOption

func WithSelectiveFields

func WithSelectiveFields(fields []string) DecoderOption

WithSelectiveFields enables field-specific decoding optimization. When set, the decoder will only decode the specified fields from objects, dramatically improving performance for large objects where only specific fields are needed. This provides up to 334x performance improvement and 113x reduction in memory allocations compared to full object decoding.

func WithUTF8Validation

func WithUTF8Validation(validate bool) DecoderOption

func WithUnknownTypes

func WithUnknownTypes(allow bool) DecoderOption

type DecoderStatsCollector

type DecoderStatsCollector struct {
	*Decoder
	Stats DecodingStats
}

DecoderStatsCollector is a decoder that collects statistics

func NewDecoderStatsCollector

func NewDecoderStatsCollector(options ...DecoderOption) *DecoderStatsCollector

NewDecoderStatsCollector creates a decoder that collects decoding statistics

func (*DecoderStatsCollector) Decode

func (dsc *DecoderStatsCollector) Decode(data []byte) (any, error)

Decode wraps the parent Decode with statistics collection

func (*DecoderStatsCollector) GetStats

func (dsc *DecoderStatsCollector) GetStats() DecodingStats

GetStats returns a copy of the current statistics

func (*DecoderStatsCollector) ResetStats

func (dsc *DecoderStatsCollector) ResetStats()

ResetStats resets all statistics

type DecodingStats

type DecodingStats struct {
	BytesDecoded int64
	MaxDepthUsed int
	TypesDecoded map[Type]int
	ErrorsCount  int64
	UnknownTypes int64
}

DecodingStats provides statistics about decoding operations

type Encoder

type Encoder struct {
	// Configuration options
	MaxDepth        int    // Maximum nesting depth for objects/arrays (0 = unlimited)
	StrictMode      bool   // Strict type checking and validation
	CompactArrays   bool   // Use typed arrays when beneficial
	ValidateStrings bool   // Validate UTF-8 encoding in strings
	TagName         string // Struct tag name to use (default: "json" for compatibility)
	// contains filtered or unexported fields
}

Encoder provides structured encoding with configurable options

Example
package main

import (
	"fmt"
	"log"

	"github.com/bubunyo/bogo"
)

func main() {
	// Advanced configuration for high-performance scenarios
	decoder := bogo.NewConfigurableDecoder(
		bogo.WithSelectiveFields([]string{"id", "name"}), // Only decode these fields
		bogo.WithDecoderMaxDepth(10),                     // Limit nesting
	)

	// Create some test data
	testData := map[string]any{
		"id":    int64(123),
		"name":  "Alice",
		"email": "alice@example.com", // This will be skipped
		"profile": map[string]any{ // This will be skipped
			"bio":      "Long biography...",
			"settings": map[string]any{"theme": "dark"},
		},
	}

	// Encode normally
	encoded, err := bogo.Marshal(testData)
	if err != nil {
		log.Fatal(err)
	}

	// Decode selectively (much faster for large objects)
	result, err := decoder.Decode(encoded)
	if err != nil {
		log.Fatal(err)
	}

	resultMap := result.(map[string]any)
	fmt.Printf("Selective decode - ID: %v, Name: %v\n", resultMap["id"], resultMap["name"])
}
Output:

Selective decode - ID: 123, Name: Alice

func GetDefaultEncoder

func GetDefaultEncoder() *Encoder

GetDefaultEncoder returns the current default encoder

func NewConfigurableEncoder

func NewConfigurableEncoder(options ...EncoderOption) *Encoder

NewConfigurableEncoder creates a new Encoder with optional configuration

func (*Encoder) Encode

func (e *Encoder) Encode(v any) ([]byte, error)

Encode encodes a value using the configured encoder

func (*Encoder) EncodeTo

func (e *Encoder) EncodeTo(w io.Writer, v any) error

EncodeTo encodes a value directly to an io.Writer

type EncoderOption

type EncoderOption func(*Encoder)

EncoderOption is a function type for configuring an Encoder

func WithCompactArrays

func WithCompactArrays(compact bool) EncoderOption

func WithMaxDepth

func WithMaxDepth(depth int) EncoderOption

Encoder option functions

func WithStrictMode

func WithStrictMode(strict bool) EncoderOption

func WithStringValidation

func WithStringValidation(validate bool) EncoderOption

func WithStructTag

func WithStructTag(tagName string) EncoderOption

type EncodingStats

type EncodingStats struct {
	BytesEncoded int64
	MaxDepthUsed int
	TypesEncoded map[Type]int
	ErrorsCount  int64
}

EncodingStats provides statistics about encoding operations

type FieldInfo

type FieldInfo struct {
	Type  Type
	Key   []byte
	Value any
}

type Parser

type Parser struct {
	TagName string // Configurable tag name (e.g., "json", "bogo")
}

Parser extracts struct field information for encoding/decoding

func NewParser

func NewParser(tagName string) *Parser

NewParser creates a new parser with the specified tag name

func (*Parser) ParseFields

func (p *Parser) ParseFields(in interface{}) map[string]FieldInfo

ParseFields returns a map of field names to their corresponding field info

type StatsCollector

type StatsCollector struct {
	*Encoder
	Stats EncodingStats
}

StatsCollector is an encoder that collects statistics

func NewStatsCollector

func NewStatsCollector(options ...EncoderOption) *StatsCollector

NewStatsCollector creates an encoder that collects encoding statistics

func (*StatsCollector) Encode

func (sc *StatsCollector) Encode(v any) ([]byte, error)

Encode wraps the parent Encode with statistics collection

func (*StatsCollector) GetStats

func (sc *StatsCollector) GetStats() EncodingStats

GetStats returns a copy of the current statistics

func (*StatsCollector) ResetStats

func (sc *StatsCollector) ResetStats()

ResetStats resets all statistics

type StreamDecoder

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

StreamDecoder reads and decodes bogo values from an input stream, similar to json.Decoder

func NewDecoder

func NewDecoder(r io.Reader) *StreamDecoder

NewDecoder creates a new StreamDecoder that reads from r, similar to json.NewDecoder

func NewDecoderWithOptions

func NewDecoderWithOptions(r io.Reader, options ...DecoderOption) *StreamDecoder

NewDecoderWithOptions creates a StreamDecoder with custom configuration options

func (*StreamDecoder) Decode

func (dec *StreamDecoder) Decode(v any) error

Decode reads the next bogo value from the stream and stores it in v, similar to json.Decoder.Decode

func (*StreamDecoder) SetDecoder

func (dec *StreamDecoder) SetDecoder(d *Decoder)

SetDecoder allows setting a custom decoder instance

type StreamEncoder

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

StreamEncoder writes bogo values to an output stream, similar to json.Encoder

func NewEncoder

func NewEncoder(w io.Writer) *StreamEncoder

NewEncoder creates a new StreamEncoder that writes to w, similar to json.NewEncoder

func NewEncoderWithOptions

func NewEncoderWithOptions(w io.Writer, options ...EncoderOption) *StreamEncoder

NewEncoderWithOptions creates a StreamEncoder with custom configuration options

func (*StreamEncoder) Encode

func (enc *StreamEncoder) Encode(v any) error

Encode encodes v and writes it to the stream, similar to json.Encoder.Encode

func (*StreamEncoder) SetEncoder

func (enc *StreamEncoder) SetEncoder(e *Encoder)

SetEncoder allows setting a custom encoder instance

type Type

type Type byte

func (Type) String

func (t Type) String() string

type TypeNumber

type TypeNumber interface {
	int64 | float64
}

type UnknownType

type UnknownType struct {
	TypeID Type
	Data   []byte
}

UnknownType represents a type that couldn't be decoded but was allowed

func (UnknownType) String

func (ut UnknownType) String() string

Jump to

Keyboard shortcuts

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