0
# Buffer Operations
1
2
Buffer is a mutable collection of bytes that implements both BufferedSource and BufferedSink interfaces. It provides efficient operations for building and manipulating byte sequences with segment-based storage for optimal memory usage.
3
4
## Capabilities
5
6
### Creating and Managing Buffers
7
8
Create Buffer instances and manage their content.
9
10
```kotlin { .api }
11
/**
12
* Creates a new empty Buffer
13
*/
14
class Buffer() : BufferedSource, BufferedSink
15
16
/**
17
* Number of bytes currently in the buffer
18
*/
19
val size: Long
20
21
/**
22
* Removes all bytes from the buffer
23
*/
24
fun clear()
25
26
/**
27
* Creates a deep copy of this buffer
28
* @return New Buffer with identical content
29
*/
30
fun copy(): Buffer
31
32
/**
33
* Creates an immutable snapshot of the current buffer content
34
* @return ByteString containing current buffer bytes
35
*/
36
fun snapshot(): ByteString
37
38
/**
39
* Returns the number of bytes in completed segments
40
* Used for efficient bulk operations
41
* @return Number of bytes in full segments
42
*/
43
fun completeSegmentByteCount(): Long
44
```
45
46
**Usage Examples:**
47
48
```kotlin
49
val buffer = Buffer()
50
buffer.writeUtf8("Hello")
51
println(buffer.size) // 5
52
53
val copy = buffer.copy()
54
val snapshot = buffer.snapshot()
55
println(snapshot.utf8()) // "Hello"
56
57
buffer.clear()
58
println(buffer.size) // 0
59
```
60
61
### Reading from Buffer
62
63
Read various data types from the buffer as a BufferedSource.
64
65
```kotlin { .api }
66
/**
67
* Checks if the buffer is exhausted (empty)
68
* @return true if no more bytes are available
69
*/
70
fun exhausted(): Boolean
71
72
/**
73
* Ensures at least byteCount bytes are available for reading
74
* @param byteCount Minimum number of bytes required
75
* @throws EOFException if insufficient bytes available
76
*/
77
fun require(byteCount: Long)
78
79
/**
80
* Requests that at least byteCount bytes are available
81
* @param byteCount Number of bytes requested
82
* @return true if the requested bytes are available
83
*/
84
fun request(byteCount: Long): Boolean
85
86
/**
87
* Reads and removes a single byte
88
* @return The byte value (0-255)
89
* @throws EOFException if buffer is empty
90
*/
91
fun readByte(): Byte
92
93
/**
94
* Reads and removes a 16-bit integer in big-endian format
95
* @return Short value
96
* @throws EOFException if insufficient bytes
97
*/
98
fun readShort(): Short
99
100
/**
101
* Reads and removes a 16-bit integer in little-endian format
102
* @return Short value
103
* @throws EOFException if insufficient bytes
104
*/
105
fun readShortLe(): Short
106
107
/**
108
* Reads and removes a 32-bit integer in big-endian format
109
* @return Int value
110
* @throws EOFException if insufficient bytes
111
*/
112
fun readInt(): Int
113
114
/**
115
* Reads and removes a 32-bit integer in little-endian format
116
* @return Int value
117
* @throws EOFException if insufficient bytes
118
*/
119
fun readIntLe(): Int
120
121
/**
122
* Reads and removes a 64-bit integer in big-endian format
123
* @return Long value
124
* @throws EOFException if insufficient bytes
125
*/
126
fun readLong(): Long
127
128
/**
129
* Reads and removes a 64-bit integer in little-endian format
130
* @return Long value
131
* @throws EOFException if insufficient bytes
132
*/
133
fun readLongLe(): Long
134
135
/**
136
* Reads all remaining bytes as UTF-8 string
137
* @return String representation of all bytes
138
*/
139
fun readUtf8(): String
140
141
/**
142
* Reads the specified number of bytes as UTF-8 string
143
* @param byteCount Number of bytes to read
144
* @return String representation of the bytes
145
* @throws EOFException if insufficient bytes
146
*/
147
fun readUtf8(byteCount: Long): String
148
149
/**
150
* Reads all remaining bytes as ByteString
151
* @return ByteString containing all bytes
152
*/
153
fun readByteString(): ByteString
154
155
/**
156
* Reads the specified number of bytes as ByteString
157
* @param byteCount Number of bytes to read
158
* @return ByteString containing the bytes
159
* @throws EOFException if insufficient bytes
160
*/
161
fun readByteString(byteCount: Long): ByteString
162
```
163
164
**Usage Examples:**
165
166
```kotlin
167
val buffer = Buffer()
168
buffer.writeUtf8("Hello")
169
buffer.writeInt(42)
170
171
println(buffer.readUtf8(5)) // "Hello"
172
println(buffer.readInt()) // 42
173
println(buffer.exhausted()) // true
174
```
175
176
### Writing to Buffer
177
178
Write various data types to the buffer as a BufferedSink.
179
180
```kotlin { .api }
181
/**
182
* Writes a single byte to the buffer
183
* @param b Byte value to write
184
* @return This buffer for chaining
185
*/
186
fun writeByte(b: Int): Buffer
187
188
/**
189
* Writes a 16-bit integer in big-endian format
190
* @param s Short value to write
191
* @return This buffer for chaining
192
*/
193
fun writeShort(s: Int): Buffer
194
195
/**
196
* Writes a 16-bit integer in little-endian format
197
* @param s Short value to write
198
* @return This buffer for chaining
199
*/
200
fun writeShortLe(s: Int): Buffer
201
202
/**
203
* Writes a 32-bit integer in big-endian format
204
* @param i Int value to write
205
* @return This buffer for chaining
206
*/
207
fun writeInt(i: Int): Buffer
208
209
/**
210
* Writes a 32-bit integer in little-endian format
211
* @param i Int value to write
212
* @return This buffer for chaining
213
*/
214
fun writeIntLe(i: Int): Buffer
215
216
/**
217
* Writes a 64-bit integer in big-endian format
218
* @param v Long value to write
219
* @return This buffer for chaining
220
*/
221
fun writeLong(v: Long): Buffer
222
223
/**
224
* Writes a 64-bit integer in little-endian format
225
* @param v Long value to write
226
* @return This buffer for chaining
227
*/
228
fun writeLongLe(v: Long): Buffer
229
230
/**
231
* Writes a string as UTF-8 bytes
232
* @param string String to write
233
* @return This buffer for chaining
234
*/
235
fun writeUtf8(string: String): Buffer
236
237
/**
238
* Writes a portion of a string as UTF-8 bytes
239
* @param string String to write
240
* @param beginIndex Starting character index
241
* @param endIndex Ending character index
242
* @return This buffer for chaining
243
*/
244
fun writeUtf8(string: String, beginIndex: Int, endIndex: Int): Buffer
245
246
/**
247
* Writes all bytes from a ByteString
248
* @param byteString ByteString to write
249
* @return This buffer for chaining
250
*/
251
fun write(byteString: ByteString): Buffer
252
253
/**
254
* Writes all bytes from a byte array
255
* @param source Byte array to write
256
* @return This buffer for chaining
257
*/
258
fun write(source: ByteArray): Buffer
259
260
/**
261
* Writes bytes from a byte array
262
* @param source Byte array to write from
263
* @param offset Starting position in source array
264
* @param byteCount Number of bytes to write
265
* @return This buffer for chaining
266
*/
267
fun write(source: ByteArray, offset: Int, byteCount: Int): Buffer
268
```
269
270
**Usage Examples:**
271
272
```kotlin
273
val buffer = Buffer()
274
.writeUtf8("Hello")
275
.writeByte(32) // space
276
.writeUtf8("World")
277
.writeByte(33) // exclamation
278
279
println(buffer.readUtf8()) // "Hello World!"
280
281
// Write binary data
282
val data = Buffer()
283
.writeInt(42)
284
.writeLong(123456789L)
285
.writeShortLe(0x1234)
286
```
287
288
### Direct Access Operations
289
290
Directly access and manipulate buffer content.
291
292
```kotlin { .api }
293
/**
294
* Returns the byte at the specified position without removing it
295
* @param pos Position of the byte (0-based)
296
* @return Byte at the specified position
297
* @throws IndexOutOfBoundsException if pos is out of range
298
*/
299
operator fun get(pos: Long): Byte
300
301
/**
302
* Copies data to another buffer
303
* @param out Destination buffer
304
* @param offset Starting position in this buffer
305
* @param byteCount Number of bytes to copy
306
* @return This buffer for chaining
307
*/
308
fun copyTo(out: Buffer, offset: Long = 0, byteCount: Long = size - offset): Buffer
309
310
/**
311
* Provides unsafe cursor access to internal segments
312
* @return UnsafeCursor for direct segment access
313
*/
314
fun readUnsafe(): Buffer.UnsafeCursor
315
316
/**
317
* Provides unsafe cursor access for both reading and writing
318
* @return UnsafeCursor for direct segment access
319
*/
320
fun readAndWriteUnsafe(): Buffer.UnsafeCursor
321
```
322
323
**Usage Examples:**
324
325
```kotlin
326
val buffer = Buffer()
327
buffer.writeUtf8("Hello World")
328
329
// Direct access
330
println(buffer[0]) // 72 (ASCII 'H')
331
println(buffer[6]) // 87 (ASCII 'W')
332
333
// Copy to another buffer
334
val copy = Buffer()
335
buffer.copyTo(copy, 0, 5) // Copy "Hello"
336
println(copy.readUtf8()) // "Hello"
337
```
338
339
### Hash Functions
340
341
Compute hashes of the buffer content.
342
343
```kotlin { .api }
344
/**
345
* Computes MD5 hash of buffer content (deprecated)
346
* @return ByteString containing MD5 hash
347
*/
348
fun md5(): ByteString
349
350
/**
351
* Computes SHA-1 hash of buffer content
352
* @return ByteString containing SHA-1 hash
353
*/
354
fun sha1(): ByteString
355
356
/**
357
* Computes SHA-256 hash of buffer content
358
* @return ByteString containing SHA-256 hash
359
*/
360
fun sha256(): ByteString
361
362
/**
363
* Computes SHA-512 hash of buffer content
364
* @return ByteString containing SHA-512 hash
365
*/
366
fun sha512(): ByteString
367
368
/**
369
* Computes HMAC-SHA1 of buffer content
370
* @param key Secret key for HMAC computation
371
* @return ByteString containing HMAC-SHA1
372
*/
373
fun hmacSha1(key: ByteString): ByteString
374
375
/**
376
* Computes HMAC-SHA256 of buffer content
377
* @param key Secret key for HMAC computation
378
* @return ByteString containing HMAC-SHA256
379
*/
380
fun hmacSha256(key: ByteString): ByteString
381
382
/**
383
* Computes HMAC-SHA512 of buffer content
384
* @param key Secret key for HMAC computation
385
* @return ByteString containing HMAC-SHA512
386
*/
387
fun hmacSha512(key: ByteString): ByteString
388
```
389
390
**Usage Examples:**
391
392
```kotlin
393
val buffer = Buffer()
394
buffer.writeUtf8("Hello, World!")
395
396
val sha256 = buffer.sha256()
397
println(sha256.hex())
398
399
val key = "secret".encodeUtf8()
400
val hmac = buffer.hmacSha256(key)
401
println(hmac.hex())
402
```
403
404
### Unsafe Cursor Operations
405
406
Direct access to internal buffer segments for high-performance operations.
407
408
```kotlin { .api }
409
/**
410
* Cursor for direct access to buffer segments
411
* Provides unsafe but efficient access to internal byte arrays
412
*/
413
class UnsafeCursor {
414
/**
415
* Current segment's byte array, or null if at end
416
*/
417
var data: ByteArray?
418
419
/**
420
* Starting index in current segment's byte array
421
*/
422
var start: Int
423
424
/**
425
* Ending index in current segment's byte array
426
*/
427
var end: Int
428
429
/**
430
* Current position in the buffer
431
*/
432
var offset: Long
433
434
/**
435
* Moves cursor to the specified position
436
* @param offset Target position in buffer
437
* @return Number of bytes available from this position
438
*/
439
fun seek(offset: Long): Long
440
441
/**
442
* Moves cursor to next segment
443
* @return Number of bytes in next segment, or -1 if at end
444
*/
445
fun next(): Long
446
447
/**
448
* Closes the cursor and releases resources
449
*/
450
fun close()
451
}
452
```
453
454
**Usage Examples:**
455
456
```kotlin
457
val buffer = Buffer()
458
buffer.writeUtf8("Hello World")
459
460
// Read using unsafe cursor
461
val cursor = buffer.readUnsafe()
462
cursor.seek(0)
463
while (cursor.data != null) {
464
for (i in cursor.start until cursor.end) {
465
print("${cursor.data!![i].toChar()}")
466
}
467
cursor.next()
468
}
469
cursor.close()
470
```