Skip to content

x/crypto/cryptobyte: non allocating AddUint*LengthPrefixed and AddASN1 API #54059

@mateusz834

Description

@mateusz834

The (*Builder).AddUint*LengthPrefixed allocates on every call a new *Builder.
This allocation cause ~17% of all heap allocations of a crypto/tls tls handshake.

Proposal:

Add new non allocating API Uint*LengthPrefixed:

p := NewBuilder(make([]byte,0,512))
p.Uint8LengthPrefixed(func () {
	p.Uint8LengthPrefixed(func () {
		p.AddUint8(42)
	})
	p.AddUint8(11)
})

The new methods will not return a *Builder in the func(), as the original API does.
Instedad it will require the usage of the original *Builder.
All writes to the original *Builder, inside Uint*LengthPrexied methods will
write them accordingly to the LengthPrefixed part in which they were executed.

Implementation example: commit

Benchmarks:

BenchmarkLengthPrefixed-4            15930202                70.18 ns/op            0 B/op          0 allocs/op
BenchmarkAddLengthPrefixedOld-4          2160042               762.2 ns/op           292 B/op          7 allocs/op
b := NewBuilder(buf)
b.Uint8LengthPrefixed(func() {
	b.AddBytes([]byte("123456"))
})
b.Uint8LengthPrefixed(func() {
	b.AddBytes([]byte("abcdef"))
})
b.Uint8LengthPrefixed(func() {
        b.AddBytes([]byte("qwerty"))
})

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    Accepted

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions