kolo docsbeta

kolo-codec

Codificación binaria canónica para Kolo, en la que cada valor tiene exactamente una codificación válida.

En esta página

Los peers firman y calculan el hash de los bytes que intercambian, así que un valor siempre debe codificarse en los mismos bytes. kolo-codec da a cada valor exactamente una codificación válida: los enteros sin signo son varints LEB128 sin signo mínimos, tal como los define el estándar DWARF Version 5, los enteros con signo se asignan a enteros sin signo alternando el signo (0, -1, 1, -2 pasan a ser 0, 1, 2, 3), y las cadenas son UTF-8 (RFC 3629). Rechaza todo lo demás con un error y lee entradas no fiables sin entrar en pánico. kolo-log y las bibliotecas que se apoyan en él lo usan para todo lo que firman, calculan con hash, envían o guardan. No tiene esquema ni forma JSON.

Instalación

go get github.com/ciranda-dev/kolo-codec

No tiene dependencias fuera de la biblioteca estándar.

Inicio rápido

Escribe un número y una cadena, vuelve a leerlos y comprueba cómo se rechaza una segunda codificación de un valor.

main.go
package main

import (
	"errors"
	"fmt"
	"log"

	kolocodec "github.com/ciranda-dev/kolo-codec"
)

func main() {
	var e kolocodec.Encoder
	e.PutUvarint(300)
	e.PutString("hello")
	data := e.Bytes()
	fmt.Printf("encoded: %x\n", data)

	d := kolocodec.NewDecoder(data)
	seq, err := d.Uvarint()
	if err != nil {
		log.Fatal(err)
	}
	body, err := d.String(1024)
	if err != nil {
		log.Fatal(err)
	}
	if err := d.Done(); err != nil {
		log.Fatal(err)
	}
	fmt.Println(seq, body)

	// 80 00 is a second, longer encoding of 0.
	_, err = kolocodec.NewDecoder([]byte{0x80, 0x00}).Uvarint()
	fmt.Println("non-canonical:", errors.Is(err, kolocodec.ErrNonCanonical))
}

Imprime encoded: ac020568656c6c6f, después 300 hello y non-canonical: true. Lee los campos en el orden en que se escribieron y llama a Done al final, para que los bytes sobrantes den error.

Referencia de la API

La referencia de la API se genera a partir del código Go y está en inglés.

Paquete kolocodec · github.com/ciranda-dev/kolo-codec · v0.1.0

Package kolocodec encodes values into canonical bytes for Kolo and decodes them without panicking on hostile input. Canonical is byte-level: strings must be valid UTF-8 but are not normalized (no NFC).

This package is experimental and its API may change before v1.0.0.

Variables

var (
	// ErrShortBuffer is returned when the input ends before a value does.
	ErrShortBuffer = errors.New("kolocodec: short buffer")
	// ErrNonCanonical is returned when the input is not the one valid encoding of its value.
	ErrNonCanonical = errors.New("kolocodec: non-canonical encoding")
	// ErrTooLarge is returned when a length or value is over the caller's max or a uvarint overflows 64 bits.
	ErrTooLarge = errors.New("kolocodec: value too large")
	// ErrInvalidUTF8 is returned by [Decoder.String] and [Encoder.PutValidString] for invalid UTF-8.
	ErrInvalidUTF8 = errors.New("kolocodec: invalid UTF-8")
	// ErrTrailingBytes is returned by [Decoder.Done] when input is left.
	ErrTrailingBytes = errors.New("kolocodec: trailing bytes")
)

Tipos

type Decoder

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

Decoder reads canonical encodings from a byte slice; a failed read consumes nothing.

func NewDecoder
func NewDecoder(b []byte) *Decoder

NewDecoder returns a Decoder that reads from b.

func (Decoder) Bool
func (d *Decoder) Bool() (bool, error)

Bool reads one byte and returns ErrNonCanonical if it is not 0 or 1.

func (Decoder) Bytes
func (d *Decoder) Bytes(max int) ([]byte, error)

Bytes reads a length-prefixed byte slice of at most max bytes and returns a copy.

func (Decoder) Done
func (d *Decoder) Done() error

Done returns ErrTrailingBytes if any input is left.

func (Decoder) Fixed
func (d *Decoder) Fixed(n int) ([]byte, error)

Fixed reads exactly n bytes with no length and returns a copy.

func (Decoder) Len
func (d *Decoder) Len() int

Len returns the number of bytes left to read.

func (Decoder) String
func (d *Decoder) String(max int) (string, error)

String reads a length-prefixed UTF-8 string of at most max bytes.

func (Decoder) Uint32
func (d *Decoder) Uint32() (uint32, error)

Uint32 reads 4 bytes, little-endian.

func (Decoder) Uint64
func (d *Decoder) Uint64() (uint64, error)

Uint64 reads 8 bytes, little-endian.

func (Decoder) Uvarint
func (d *Decoder) Uvarint() (uint64, error)

Uvarint reads a minimal unsigned LEB128 varint, rejecting non-minimal encodings.

func (Decoder) UvarintMax
func (d *Decoder) UvarintMax(max uint64) (uint64, error)

UvarintMax reads a uvarint like Decoder.Uvarint and returns ErrTooLarge if it is over max.

func (Decoder) Varint
func (d *Decoder) Varint() (int64, error)

Varint reads a zigzag-encoded minimal varint written by Encoder.PutVarint.

type Encoder

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

Encoder appends canonical encodings to a buffer; the zero value is ready to use.

func (Encoder) Bytes
func (e *Encoder) Bytes() []byte

Bytes returns a copy of the encoded output.

func (Encoder) Len
func (e *Encoder) Len() int

Len returns the number of bytes written, without copying them.

func (Encoder) PutBool
func (e *Encoder) PutBool(v bool)

PutBool writes v as one byte, 0 or 1.

func (Encoder) PutBytes
func (e *Encoder) PutBytes(b []byte)

PutBytes writes the length of b as a uvarint, then b.

func (Encoder) PutFixed
func (e *Encoder) PutFixed(b []byte)

PutFixed writes b with no length, for fixed-size values such as keys and hashes.

func (Encoder) PutString
func (e *Encoder) PutString(s string)

PutString writes s like Encoder.PutBytes; use Encoder.PutValidString to reject invalid UTF-8.

func (Encoder) PutUint32
func (e *Encoder) PutUint32(v uint32)

PutUint32 writes v as 4 bytes, little-endian.

func (Encoder) PutUint64
func (e *Encoder) PutUint64(v uint64)

PutUint64 writes v as 8 bytes, little-endian.

func (Encoder) PutUvarint
func (e *Encoder) PutUvarint(v uint64)

PutUvarint writes v as a minimal unsigned LEB128 varint.

func (Encoder) PutValidString
func (e *Encoder) PutValidString(s string) error

PutValidString writes s like Encoder.PutString, or returns ErrInvalidUTF8 and writes nothing.

func (Encoder) PutVarint
func (e *Encoder) PutVarint(v int64)

PutVarint writes v as a zigzag-encoded minimal varint.

func (Encoder) Reset
func (e *Encoder) Reset()

Reset discards the output and keeps the buffer for reuse; earlier results of Encoder.Bytes are unaffected.

Conviene saber

ValorCodificación
entero sin signovarint LEB128 sin signo mínimo
entero con signozigzag y después el varint sin signo
uint32, uint64ancho fijo, little-endian
boolun byte, 0 o 1
bytes, cadenalongitud en varint y después los datos
valor de tamaño fijo (clave, hash)los bytes tal cual, sin longitud

Límites

  • Un varint ocupa como máximo 10 bytes y 64 bits. Una entrada más larga devuelve ErrTooLarge, y un varint con bytes redundantes devuelve ErrNonCanonical.
  • Bytes(max) y String(max) devuelven ErrTooLarge con una longitud mayor que max o con un max negativo, y ErrShortBuffer con una longitud que pasa del final de la entrada. Ambas cosas se comprueban antes de reservar memoria.
  • UvarintMax(max) devuelve ErrTooLarge con un valor mayor que max.
  • Fixed(n) devuelve ErrTooLarge con un n negativo.
  • Un byte de bool distinto de 0 o 1 devuelve ErrNonCanonical.

Seguridad

  • Decodificar una entrada no fiable devuelve un error, nunca un pánico.
  • Una lectura fallida no consume nada.
  • Bytes, Fixed y Encoder.Bytes devuelven copias, así que cambiar después la entrada o la salida no cambia lo que tienes.
  • Encoder.Len es el tamaño de la salida hasta ahora, sin copiarla, y Encoder.Reset vacía el codificador y conserva su búfer, para que una ruta crítica pueda reutilizarlo. Los resultados de Encoder.Bytes obtenidos antes no se ven afectados.
  • Los mensajes de error nunca incluyen valores tomados de la entrada.

Límites conocidos

  • Experimental. La API puede cambiar antes de v1.0.0.
  • Sin normalización Unicode (sin NFC).
  • PutString escribe el UTF-8 no válido tal cual, y luego String lo rechaza. Usa PutValidString para rechazarlo al escribir, y Bytes para datos arbitrarios.

Errores

ErrorMensaje
ErrInvalidUTF8kolocodec: invalid UTF-8
ErrNonCanonicalkolocodec: non-canonical encoding
ErrShortBufferkolocodec: short buffer
ErrTooLargekolocodec: value too large
ErrTrailingByteskolocodec: trailing bytes

Comprueba los errores con errors.Is. ErrTooLarge puede llegar envuelto con un motivo breve, como un uvarint que desborda los 64 bits; los demás errores se devuelven tal cual.

Referencias

  • DWARF Version 5, el estándar Debugging Information Format.
    • Toma: la codificación LEB128 sin signo, usada solo en su forma mínima.
    • No implementa: LEB128 con signo; en su lugar, los enteros con signo se asignan a enteros sin signo alternando el signo.
  • RFC 3629, UTF-8, a transformation format of ISO 10646 (Internet Standard, November 2003).
    • Toma: la definición de UTF-8 válido con la que se comprueba cada cadena.
    • No implementa: no se deja nada fuera.