Skip to content

Commit 4e9810a

Browse files
authored
Inline ndata() in concatkdf New (#1567)
Write length-prefixed fields directly into a single buffer, eliminating intermediate allocations from ndata(). No measurable perf change (compiler already optimized via inlining + escape analysis): 54.6 ns/op, 128 B/op, 2 allocs.
1 parent 690cac8 commit 4e9810a

File tree

1 file changed

+17
-14
lines changed

1 file changed

+17
-14
lines changed

jwe/internal/concatkdf/concatkdf.go

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -13,22 +13,25 @@ type KDF struct {
1313
hash crypto.Hash
1414
}
1515

16-
func ndata(src []byte) []byte {
17-
buf := make([]byte, 4+len(src))
18-
binary.BigEndian.PutUint32(buf, uint32(len(src)))
19-
copy(buf[4:], src)
20-
return buf
21-
}
22-
2316
func New(hash crypto.Hash, alg, Z, apu, apv, pubinfo, privinfo []byte) *KDF {
24-
algbuf := ndata(alg)
25-
apubuf := ndata(apu)
26-
apvbuf := ndata(apv)
17+
// Write length-prefixed fields directly into a single buffer,
18+
// avoiding intermediate allocations from ndata().
19+
totalSize := (4 + len(alg)) + (4 + len(apu)) + (4 + len(apv)) + len(pubinfo) + len(privinfo)
20+
concat := make([]byte, totalSize)
21+
22+
n := 0
23+
binary.BigEndian.PutUint32(concat[n:], uint32(len(alg)))
24+
n += 4
25+
n += copy(concat[n:], alg)
26+
27+
binary.BigEndian.PutUint32(concat[n:], uint32(len(apu)))
28+
n += 4
29+
n += copy(concat[n:], apu)
30+
31+
binary.BigEndian.PutUint32(concat[n:], uint32(len(apv)))
32+
n += 4
33+
n += copy(concat[n:], apv)
2734

28-
concat := make([]byte, len(algbuf)+len(apubuf)+len(apvbuf)+len(pubinfo)+len(privinfo))
29-
n := copy(concat, algbuf)
30-
n += copy(concat[n:], apubuf)
31-
n += copy(concat[n:], apvbuf)
3235
n += copy(concat[n:], pubinfo)
3336
copy(concat[n:], privinfo)
3437

0 commit comments

Comments
 (0)