kolo docsbeta

kolo-codec

Codificação binária canônica para o Kolo, em que cada valor tem exatamente uma codificação válida.

Nesta página

Os peers assinam e calculam o hash dos bytes que trocam, então um valor precisa sempre virar os mesmos bytes. A kolo-codec dá a cada valor exatamente uma codificação válida: os inteiros sem sinal são varints LEB128 sem sinal mínimos, como define o padrão DWARF Version 5, os inteiros com sinal são mapeados para inteiros sem sinal alternando o sinal (0, -1, 1, -2 viram 0, 1, 2, 3), e as strings são UTF-8 (RFC 3629). Ela rejeita qualquer outra com um erro e lê entradas não confiáveis sem entrar em pânico. A kolo-log e as bibliotecas acima dela usam a kolo-codec para tudo o que assinam, passam por hash, enviam ou guardam. Ela não tem schema nem forma em JSON.

Instalação

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

Nenhuma dependência fora da biblioteca padrão.

Início rápido

Escreva um número e uma string, leia os dois de volta e veja uma segunda codificação de um valor ser rejeitada.

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))
}

O programa imprime encoded: ac020568656c6c6f, depois 300 hello e non-canonical: true. Leia os campos na ordem em que foram escritos e chame Done no fim, para que bytes sobrando virem um erro.

Referência da API

A referência da API é gerada a partir do código Go e está em inglês.

Pacote 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.

Variáveis

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.

Bom saber

ValorCodificação
inteiro sem sinalvarint LEB128 sem sinal, mínimo
inteiro com sinalzigzag, depois o varint sem sinal
uint32, uint64largura fixa, little-endian
boolum byte, 0 ou 1
bytes, stringtamanho em varint, depois os dados
valor de tamanho fixo (chave, hash)os bytes crus, sem tamanho

Limites

  • Um varint tem no máximo 10 bytes e 64 bits. Uma entrada mais longa retorna ErrTooLarge, e um varint com bytes redundantes retorna ErrNonCanonical.
  • Bytes(max) e String(max) retornam ErrTooLarge para um tamanho acima de max ou para um max negativo, e ErrShortBuffer para um tamanho que passa do fim da entrada. As duas verificações acontecem antes de qualquer alocação.
  • UvarintMax(max) retorna ErrTooLarge para um valor acima de max.
  • Fixed(n) retorna ErrTooLarge para um n negativo.
  • Um byte de bool diferente de 0 ou 1 retorna ErrNonCanonical.

Segurança

  • Decodificar uma entrada não confiável retorna um erro, nunca um pânico.
  • Uma leitura que falha não consome nada.
  • Bytes, Fixed e Encoder.Bytes retornam cópias, então alterar a entrada ou a saída depois não muda o que você tem em mãos.
  • Encoder.Len é o tamanho da saída até agora, sem copiá-la, e Encoder.Reset esvazia o codificador e mantém o buffer, para que um caminho crítico possa reutilizá-lo. Os resultados de Encoder.Bytes obtidos antes não são afetados.
  • As mensagens de erro nunca incluem valores tirados da entrada.

Limites conhecidos

  • Experimental. A API pode mudar antes da v1.0.0.
  • Sem normalização Unicode (sem NFC).
  • PutString grava UTF-8 inválido do jeito que recebe, e String depois o rejeita. Use PutValidString para recusá-lo já na escrita, e Bytes para dados arbitrários.

Erros

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

Teste os erros com errors.Is. ErrTooLarge pode vir envolvido com um motivo curto, como um uvarint que estoura 64 bits; os outros erros são retornados como estão.

Referências

  • DWARF Version 5, o padrão Debugging Information Format.
    • Usa: a codificação LEB128 sem sinal, usada apenas na sua forma mínima.
    • Não implementa: LEB128 com sinal; em vez disso, os inteiros com sinal são mapeados para inteiros sem sinal alternando o sinal.
  • RFC 3629, UTF-8, a transformation format of ISO 10646 (Internet Standard, November 2003).
    • Usa: a definição de UTF-8 válido contra a qual cada string é verificada.
    • Não implementa: nada ficou de fora.