compact

package
v0.4.3 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2025 License: MIT Imports: 6 Imported by: 0

README

Compact Codec for JSON Patch

The compact codec provides a space-efficient array-based encoding format for JSON Patch operations. It uses arrays instead of objects to represent operations, significantly reducing the physical space required while maintaining readability.

Format Comparison

Standard JSON format:
{"op": "add", "path": "/foo/bar", "value": 123}
Compact format:
[0, "/foo/bar", 123]

Or with string opcodes:

["add", "/foo/bar", 123]

Usage

Basic Operations
package main

import (
    "fmt"
    "github.com/kaptinlin/jsonpatch/codec/compact"
    "github.com/kaptinlin/jsonpatch/op"
)

func main() {
    // Create operations
    ops := []internal.Op{
        op.NewAdd([]string{"foo"}, "bar"),
        op.NewReplace([]string{"baz"}, 42),
    }
    
    // Encode to compact format
    encoded, err := compact.Encode(ops)
    if err != nil {
        panic(err)
    }
    
    fmt.Printf("Encoded: %v\n", encoded)
    // Output: [[0 "/foo" "bar"] [2 "/baz" 42]]
    
    // Decode back to operations
    decoded, err := compact.Decode(encoded)
    if err != nil {
        panic(err)
    }
    
    fmt.Printf("Decoded: %d operations\n", len(decoded))
}
String Opcodes
// Use string opcodes instead of numeric ones
encoder := compact.NewEncoder(compact.WithStringOpcode(true))
encoded, err := encoder.Encode(ops)
// Result: [["add" "/foo" "bar"] ["replace" "/baz" 42]]
JSON Marshaling
// Encode to JSON bytes
jsonData, err := compact.EncodeJSON(ops)
if err != nil {
    panic(err)
}

// Decode from JSON bytes
decoded, err := compact.DecodeJSON(jsonData)
if err != nil {
    panic(err)
}

Operation Mapping

Standard JSON Patch Operations
Operation Numeric Code String Code Compact Format
add 0 "add" [0, path, value]
remove 1 "remove" [1, path]
replace 2 "replace" [2, path, value]
move 3 "move" [3, path, from]
copy 4 "copy" [4, path, from]
test 5 "test" [5, path, value]
Extended Operations
Operation Numeric Code String Code Compact Format
flip 10 "flip" [10, path]
inc 11 "inc" [11, path, delta]
merge 12 "merge" [12, path, value]
extend 13 "extend" [13, path, value]
Predicate Operations
Operation Numeric Code String Code Compact Format
defined 20 "defined" [20, path]
undefined 21 "undefined" [21, path]
contains 22 "contains" [22, path, value, ignoreCase?]
starts 23 "starts" [23, path, value, ignoreCase?]
ends 24 "ends" [24, path, value, ignoreCase?]

API Reference

Encoder
type Encoder struct { ... }

// Create a new encoder
func NewEncoder(opts ...EncoderOption) *Encoder

// Encode a single operation
func (e *Encoder) Encode(op internal.Op) (CompactOp, error)

// Encode multiple operations
func (e *Encoder) EncodeSlice(ops []internal.Op) ([]CompactOp, error)
Decoder
type Decoder struct { ... }

// Create a new decoder
func NewDecoder(opts ...DecoderOption) *Decoder

// Decode a single compact operation
func (d *Decoder) Decode(compactOp CompactOp) (internal.Op, error)

// Decode multiple compact operations
func (d *Decoder) DecodeSlice(compactOps []CompactOp) ([]internal.Op, error)
Standalone Functions
// Encode operations using default options
func Encode(ops []internal.Op, opts ...EncoderOption) ([]CompactOp, error)

// Encode operations to JSON bytes
func EncodeJSON(ops []internal.Op, opts ...EncoderOption) ([]byte, error)

// Decode compact operations using default options
func Decode(compactOps []CompactOp, opts ...DecoderOption) ([]internal.Op, error)

// Decode compact operations from JSON bytes
func DecodeJSON(data []byte, opts ...DecoderOption) ([]internal.Op, error)
Options
// Use string opcodes instead of numeric codes
func WithStringOpcode(useString bool) EncoderOption

Features

  • Space Efficient: Significantly smaller than standard JSON format
  • Fast: Optimized encoding and decoding performance
  • Flexible: Supports both numeric and string opcodes
  • Compatible: Works with all existing operation types
  • Type Safe: Full Go type safety and error handling

Supported Operations

Currently supports all standard JSON Patch operations and basic extended/predicate operations:

Standard: add, remove, replace, move, copy, test
Extended: flip, inc
Predicates: defined, undefined, contains, starts, ends
Coming Soon: merge, extend, string operations, composite predicates

Documentation

Overview

Package compact implements a compact array-based codec for JSON Patch operations. This codec provides significant space savings compared to standard JSON format while maintaining full compatibility with all operation types.

Package compact implements a compact array-based codec for JSON Patch operations. This codec uses arrays instead of objects to represent operations, significantly reducing the physical space required for encoding while maintaining readability.

Index

Constants

This section is empty.

Variables

View Source
var (
	// Base operation errors
	ErrCompactOperationMinLength     = errors.New("compact operation must have at least opcode and path")
	ErrCompactOperationPathNotString = errors.New("compact operation path must be a string")

	// Operation-specific errors
	ErrAddOperationRequiresValue       = errors.New("add operation requires value")
	ErrReplaceOperationRequiresValue   = errors.New("replace operation requires value")
	ErrMoveOperationRequiresFrom       = errors.New("move operation requires from path")
	ErrMoveOperationFromNotString      = errors.New("move operation from must be a string")
	ErrCopyOperationRequiresFrom       = errors.New("copy operation requires from path")
	ErrCopyOperationFromNotString      = errors.New("copy operation from must be a string")
	ErrTestOperationRequiresValue      = errors.New("test operation requires value")
	ErrIncOperationRequiresDelta       = errors.New("inc operation requires delta")
	ErrIncOperationDeltaNotNumber      = errors.New("inc operation delta must be a number")
	ErrContainsOperationRequiresValue  = errors.New("contains operation requires value")
	ErrContainsOperationValueNotString = errors.New("contains operation value must be a string")
	ErrStartsOperationRequiresValue    = errors.New("starts operation requires value")
	ErrStartsOperationValueNotString   = errors.New("starts operation value must be a string")
	ErrEndsOperationRequiresValue      = errors.New("ends operation requires value")
	ErrEndsOperationValueNotString     = errors.New("ends operation value must be a string")
)

Predefined errors for compact codec operations

View Source
var (
	ErrUnsupportedOperationType = errors.New("unsupported operation type")
	ErrUnknownStringOpcode      = errors.New("unknown string opcode")
	ErrInvalidOpcodeType        = errors.New("invalid opcode type")
	ErrUnknownNumericOpcode     = errors.New("unknown numeric opcode")
)

Base errors for dynamic data

View Source
var (
	// NewEncoder creates a new compact encoder with the given options
	NewCompactEncoder = NewEncoder

	// NewDecoder creates a new compact decoder with the given options
	NewCompactDecoder = NewDecoder

	// EncodeCompact encodes operations into compact format using default options
	EncodeCompact = Encode

	// DecodeCompact decodes compact format operations using default options
	DecodeCompact = Decode

	// EncodeCompactJSON encodes operations into compact format JSON bytes
	EncodeCompactJSON = EncodeJSON

	// DecodeCompactJSON decodes compact format JSON bytes into operations
	DecodeCompactJSON = DecodeJSON
)

Re-export main functions for convenience

View Source
var (
	DefaultEncoderOptions = EncoderOptions{
		StringOpcode: false,
	}
	DefaultDecoderOptions = DecoderOptions{}
)

Default options

Functions

func Decode

func Decode(compactOps []Op, opts ...DecoderOption) ([]internal.Op, error)

Decode decodes compact format operations using default options

func DecodeJSON

func DecodeJSON(data []byte, opts ...DecoderOption) ([]internal.Op, error)

DecodeJSON decodes compact format JSON bytes into operations

func EncodeJSON

func EncodeJSON(ops []internal.Op, opts ...EncoderOption) ([]byte, error)

EncodeJSON encodes operations into compact format JSON bytes

Types

type Decoder

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

Decoder decodes compact format operations into operation instances

func NewDecoder

func NewDecoder(opts ...DecoderOption) *Decoder

NewDecoder creates a new compact decoder with the given options

func (*Decoder) Decode

func (d *Decoder) Decode(compactOp Op) (internal.Op, error)

Decode decodes a single compact operation into an operation instance

func (*Decoder) DecodeSlice

func (d *Decoder) DecodeSlice(compactOps []Op) ([]internal.Op, error)

DecodeSlice decodes multiple compact operations into operation instances

type DecoderOption

type DecoderOption func(*DecoderOptions)

DecoderOption is a functional option for configuring the decoder

type DecoderOptions

type DecoderOptions struct {
}

DecoderOptions configures the compact decoder behavior

type Encoder

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

Encoder encodes operations into compact format

func NewEncoder

func NewEncoder(opts ...EncoderOption) *Encoder

NewEncoder creates a new compact encoder with the given options

func (*Encoder) Encode

func (e *Encoder) Encode(op internal.Op) (Op, error)

Encode encodes a single operation into compact format

func (*Encoder) EncodeSlice

func (e *Encoder) EncodeSlice(ops []internal.Op) ([]Op, error)

EncodeSlice encodes multiple operations into compact format

type EncoderOption

type EncoderOption func(*EncoderOptions)

EncoderOption is a functional option for configuring the encoder

func WithStringOpcode

func WithStringOpcode(useString bool) EncoderOption

WithStringOpcode configures the encoder to use string opcodes

type EncoderOptions

type EncoderOptions struct {
	// StringOpcode determines whether to use string opcodes instead of numeric ones
	StringOpcode bool
}

EncoderOptions configures the compact encoder behavior

type JSONPatchOptions added in v0.4.3

type JSONPatchOptions = internal.Options

JSONPatchOptions contains options for JSON Patch operations.

type Op added in v0.4.3

type Op []interface{}

Op represents a compact format operation as an array

func Encode

func Encode(ops []internal.Op, opts ...EncoderOption) ([]Op, error)

Encode encodes operations into compact format using default options

type OpCode

type OpCode int

OpCode represents operation codes for compact format

const (
	// JSON Patch (RFC 6902) operations - match internal/constants.go
	OpCodeAdd     OpCode = 0
	OpCodeRemove  OpCode = 1
	OpCodeReplace OpCode = 2
	OpCodeCopy    OpCode = 3
	OpCodeMove    OpCode = 4
	OpCodeTest    OpCode = 5

	// String editing
	OpCodeStrIns OpCode = 6
	OpCodeStrDel OpCode = 7

	// Extra
	OpCodeFlip OpCode = 8
	OpCodeInc  OpCode = 9

	// Slate.js
	OpCodeSplit  OpCode = 10
	OpCodeMerge  OpCode = 11
	OpCodeExtend OpCode = 12

	// JSON Predicate operations
	OpCodeContains      OpCode = 30
	OpCodeDefined       OpCode = 31
	OpCodeEnds          OpCode = 32
	OpCodeIn            OpCode = 33
	OpCodeLess          OpCode = 34
	OpCodeMatches       OpCode = 35
	OpCodeMore          OpCode = 36
	OpCodeStarts        OpCode = 37
	OpCodeUndefined     OpCode = 38
	OpCodeTestType      OpCode = 39
	OpCodeTestString    OpCode = 40
	OpCodeTestStringLen OpCode = 41
	OpCodeType          OpCode = 42
	OpCodeAnd           OpCode = 43
	OpCodeNot           OpCode = 44
	OpCodeOr            OpCode = 45
)

Operation codes for compact format

type Operation

type Operation = internal.CompactOperation

Operation represents a compact format operation.

Jump to

Keyboard shortcuts

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