blob: 674a55059a55f65701778e874b6929650a6e0cfe [file] [log] [blame]
Abhay Kumara2ae5992025-11-10 14:02:24 +00001package sarama
2
3import (
4 "time"
5
6 "github.com/rcrowley/go-metrics"
7)
8
9// PacketEncoder is the interface providing helpers for writing with Kafka's encoding rules.
10// Types implementing Encoder only need to worry about calling methods like PutString,
11// not about how a string is represented in Kafka.
12type packetEncoder interface {
13 // Primitives
14 putInt8(in int8)
15 putInt16(in int16)
16 putInt32(in int32)
17 putInt64(in int64)
18 putVarint(in int64)
19 putUVarint(in uint64)
20 putFloat64(in float64)
21 putArrayLength(in int) error
22 putBool(in bool)
23 putKError(in KError)
24 putDurationMs(in time.Duration)
25
26 // Collections
27 putBytes(in []byte) error
28 putVarintBytes(in []byte) error
29 putRawBytes(in []byte) error
30 putString(in string) error
31 putNullableString(in *string) error
32 putStringArray(in []string) error
33 putInt32Array(in []int32) error
34 putInt64Array(in []int64) error
35 putNullableInt32Array(in []int32) error
36 putEmptyTaggedFieldArray()
37
38 // Provide the current offset to record the batch size metric
39 offset() int
40
41 // Stacks, see PushEncoder
42 push(in pushEncoder)
43 pop() error
44
45 // To record metrics when provided
46 metricRegistry() metrics.Registry
47}
48
49// PushEncoder is the interface for encoding fields like CRCs and lengths where the value
50// of the field depends on what is encoded after it in the packet. Start them with PacketEncoder.Push() where
51// the actual value is located in the packet, then PacketEncoder.Pop() them when all the bytes they
52// depend upon have been written.
53type pushEncoder interface {
54 // Saves the offset into the input buffer as the location to actually write the calculated value when able.
55 saveOffset(in int)
56
57 // Returns the length of data to reserve for the output of this encoder (eg 4 bytes for a CRC32).
58 reserveLength() int
59
60 // Indicates that all required data is now available to calculate and write the field.
61 // SaveOffset is guaranteed to have been called first. The implementation should write ReserveLength() bytes
62 // of data to the saved offset, based on the data between the saved offset and curOffset.
63 run(curOffset int, buf []byte) error
64}
65
66// dynamicPushEncoder extends the interface of pushEncoder for uses cases where the length of the
67// fields itself is unknown until its value was computed (for instance varint encoded length
68// fields).
69type dynamicPushEncoder interface {
70 pushEncoder
71
72 // Called during pop() to adjust the length of the field.
73 // It should return the difference in bytes between the last computed length and current length.
74 adjustLength(currOffset int) int
75}