Help us shape the future of Go! Take the 2026 Go Developer Survey

bencode

package module
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2026 License: BSD-3-Clause Imports: 11 Imported by: 274

README

bencode-go

A Go language binding for encoding and decoding data in the bencode format that is used by the BitTorrent peer-to-peer file sharing protocol.

Maintenance status: ✅ Maintained (stable). This library is feature-complete — I accept bug fixes and security patches, but am not adding new features. See SECURITY.md for how to report vulnerabilities.

Quick Start

Get the package
go get -u github.com/jackpal/bencode-go
Import the package
import bencode "github.com/jackpal/bencode-go"
Unmarshal a bencode stream into an object
data := myAwesomeObject{}
err := bencode.Unmarshal(reader, &data)
Decode a bencode stream
data, err := bencode.Decode(reader)
Decode with configurable limits or strict validation
dec := bencode.NewDecoder(reader).
	SetMaxStringLength(10 * 1024 * 1024). // 10 MiB
	SetMaxDepth(50).
	SetStrict(true) // Enforces BEP 3 rules (no leading zeros, sorted keys, etc.)

data, err := dec.Decode()
// or: err := dec.Unmarshal(&myObject)

// If the stream contains trailing non-bencode data, access unread buffered bytes:
leftover := dec.Buffered()
Access raw bencoded bytes (e.g. for BitTorrent info_hash)
type Torrent struct {
	Announce string             `bencode:"announce"`
	Info     bencode.RawMessage `bencode:"info"`
}

var t Torrent
err := bencode.Unmarshal(reader, &t)
// Compute the SHA-1 info_hash directly from the raw bencoded info dictionary:
infoHash := sha1.Sum(t.Info)
Encode an object into a bencode stream
err := bencode.Marshal(writer, data)

Complete documentation

http://godoc.org/github.com/jackpal/bencode-go

License

This project is licensed under the Go Authors standard license. (See the LICENSE file for details.)

Version History

tag Notes
v1.2.1 Fix reflection panics when unmarshaling into maps with concrete element types.
v1.2.0 Added RawMessage support, Decoder.Buffered(), and skip unexported fields.
v1.1.0 Added Decoder with configurable resource limits, strict BEP 3 validation, and any types.
v1.0.2 Added go module.
v1.0.1 Removed architecture specific test that was failing on ARM.
v1.0.0 First version.

Documentation

Index

Constants

View Source
const (
	// DefaultMaxStringLength is the default maximum string length (64 MiB).
	DefaultMaxStringLength int64 = 64 * 1024 * 1024

	// DefaultMaxDepth is the default maximum nesting depth for lists and dictionaries.
	DefaultMaxDepth int = 100

	// DefaultMaxElements is the default maximum number of bencode values parsed.
	DefaultMaxElements int64 = 3_000_000
)

Default limits for decoding bencode data.

Variables

This section is empty.

Functions

func Decode

func Decode(reader io.Reader) (data any, err error)

Decode parses the stream r and returns the generic bencode object representation. The object representation is a tree of Go data types: string, int64, uint64, []any, or map[string]any.

func DecodeWithOptions added in v1.1.0

func DecodeWithOptions(reader io.Reader, opts Options) (data any, err error)

DecodeWithOptions parses the stream r with custom Options and returns the generic bencode representation.

func Marshal

func Marshal(w io.Writer, val any) error

Marshal writes the bencode encoding of val to w.

Marshal traverses the value v recursively.

Marshal uses the following type-dependent encodings:

Floating point, integer, and Number values encode as bencode numbers.

String values encode as bencode strings.

Array and slice values encode as bencode arrays.

Struct values encode as bencode maps. Each exported struct field becomes a member of the object. The object's default key string is the struct field name but can be specified in the struct field's tag value. The text of the struct field's tag value is the key name. Examples:

// Field appears in bencode as key "Field".
Field int

// Field appears in bencode as key "myName".
Field int "myName"

Anonymous struct fields are ignored.

Map values encode as bencode objects. The map's key type must be string; the object keys are used directly as map keys.

Boolean, Pointer, Interface, Channel, complex, and function values cannot be encoded in bencode. Attempting to encode such a value causes Marshal to return a MarshalError.

Bencode cannot represent cyclic data structures and Marshal does not handle them. Passing cyclic structures to Marshal will result in an infinite recursion.

func Unmarshal

func Unmarshal(r io.Reader, val any) (err error)

Unmarshal reads and parses the bencode syntax data from r into val using DefaultOptions.

func UnmarshalWithOptions added in v1.1.0

func UnmarshalWithOptions(r io.Reader, val any, opts Options) error

UnmarshalWithOptions reads and parses bencode syntax data from r into val with custom Options.

Types

type Decoder added in v1.1.0

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

Decoder reads and decodes bencode values from an input stream.

func NewDecoder added in v1.1.0

func NewDecoder(r io.Reader) *Decoder

NewDecoder returns a new Decoder reading from r with DefaultOptions.

func NewDecoderWithOptions added in v1.1.0

func NewDecoderWithOptions(r io.Reader, opts Options) *Decoder

NewDecoderWithOptions returns a new Decoder reading from r with the given Options.

func (*Decoder) Buffered added in v1.2.0

func (d *Decoder) Buffered() io.Reader

Buffered returns a reader of the data remaining in the Decoder's buffer. The reader is valid until the next call to Decode or Unmarshal.

func (*Decoder) Decode added in v1.1.0

func (d *Decoder) Decode() (data any, err error)

Decode reads the next bencode value from the stream and returns its generic Go representation.

func (*Decoder) SetMaxDepth added in v1.1.0

func (d *Decoder) SetMaxDepth(depth int) *Decoder

SetMaxDepth sets the maximum nesting depth and returns the Decoder.

func (*Decoder) SetMaxElements added in v1.1.0

func (d *Decoder) SetMaxElements(elements int64) *Decoder

SetMaxElements sets the maximum total elements limit and returns the Decoder.

func (*Decoder) SetMaxStringLength added in v1.1.0

func (d *Decoder) SetMaxStringLength(limit int64) *Decoder

SetMaxStringLength sets the maximum string length in bytes and returns the Decoder.

func (*Decoder) SetStrict added in v1.1.0

func (d *Decoder) SetStrict(strict bool) *Decoder

SetStrict sets whether strict BEP 3 validation is enabled and returns the Decoder.

func (*Decoder) Unmarshal added in v1.1.0

func (d *Decoder) Unmarshal(val any) error

Unmarshal reads the next bencode value and parses it into val (which must be a pointer).

type MarshalError

type MarshalError struct {
	T reflect.Type
}

func (*MarshalError) Error

func (e *MarshalError) Error() string

type Options added in v1.1.0

type Options struct {
	// MaxStringLength limits the maximum length in bytes of any bencode string.
	// Default is DefaultMaxStringLength (64 MiB). Set to -1 for unlimited.
	MaxStringLength int64

	// MaxDepth limits the maximum nesting depth for nested lists and dictionaries.
	// Default is DefaultMaxDepth (100). Set to -1 for unlimited.
	MaxDepth int

	// MaxElements limits the total number of bencode values (integers, strings, lists, dicts) parsed.
	// Default is DefaultMaxElements (3,000,000). Set to -1 for unlimited.
	MaxElements int64

	// Strict enables strict adherence to the BitTorrent BEP 3 bencode specification:
	// - Rejects integer representations with leading zeros (e.g. "i03e" is rejected; "i0e" is allowed).
	// - Rejects negative zero ("i-0e").
	// - Rejects explicit positive sign ("i+5e").
	// - Rejects non-integer numbers (such as floats or exponential notation).
	// - Enforces lexicographically sorted dictionary keys without duplicates.
	// - Rejects string lengths with leading zeros (e.g. "03:abc").
	Strict bool
}

Options specifies configuration and resource limits for decoding bencode data.

func DefaultOptions added in v1.1.0

func DefaultOptions() Options

DefaultOptions returns a new Options struct initialized with standard limits.

type RawMessage added in v1.2.0

type RawMessage []byte

RawMessage is a raw encoded bencode value. It can be used to delay bencode decoding or to access the original bytes of a bencoded value (such as the "info" dictionary in a BitTorrent metainfo file).

type Reader deprecated

type Reader interface {
	io.Reader
	io.ByteScanner
}

Deprecated: This type is currently unused. It is exposed for backwards compatability. The public API that previously used this type,

Unmarshal(r Reader, val any) (err error)

is now

Unmarshal(r io.Reader, val any) (err error)

Which is compatible, since any Reader is also an io.Reader. Clients should drop their use of this type. It may be removed in the future.

Jump to

Keyboard shortcuts

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