scoop:scoop.platform:0.1.0
src/memory/native_byte_buffer.scoop
Selected production source · src/memory/native_byte_buffer.scoop
1
package scoop.platform.memory3
import scoop.bytes.ByteOrder4
import scoop.platform.system.*6
private fun copyPinnedByteRange(7
destination: Ptr<Byte>,8
source: Array<Byte>,9
offset: Long,10
count: Long11
) {12
@Unsafe13
{14
source.withDataPointer {15
pointer,16
_ -> @Unsafe17
{18
nativeMemoryMove(destination, pointer + offset, count)19
}20
}21
}22
}24
/**25
* Owned growable native byte storage with separate read and write positions. Outstanding native26
* borrows restrict mutation and closure; explicitly close the buffer after use.27
*/28
public class NativeByteBuffer private constructor(): Closeable {29
private var memory: Ptr<Byte>? = None30
private var storageCapacity: Long = 0L31
private var reader: Long = 0L32
private var writer: Long = 0L33
private var closed: Boolean = false34
private var borrowed: Boolean = false35
private val stateLock: AtomicBoolean = AtomicBoolean(false)37
/**38
* The allocated byte capacity.39
*/40
public val capacity: Long get() =41
withState {42
requireOpen();43
storageCapacity44
}45
/**46
* The absolute offset of the next readable byte.47
*/48
public val readPosition: Long get() =49
withState {50
requireOpen();51
reader52
}53
/**54
* The absolute offset immediately after initialized written bytes.55
*/56
public val writePosition: Long get() =57
withState {58
requireOpen();59
writer60
}61
/**62
* The byte count between read and write positions.63
*/64
public val readableBytes: Long get() =65
withState {66
requireOpen();67
writer - reader68
}69
/**70
* The remaining capacity after the write position.71
*/72
public val writableBytes: Long get() =73
withState {74
requireOpen();75
storageCapacity - writer76
}77
/**78
* Whether this owned resource has been closed.79
*/80
public val isClosed: Boolean get() = withState { closed }82
/**83
* Allocates owned native storage with initially empty readable content.84
*/85
public companion object {86
/**87
* Allocates the requested nonnegative capacity with both positions initially zero.88
*/89
public fun allocate(capacity: Long = 0L): NativeByteBuffer {90
requireCount(capacity)91
val result = NativeByteBuffer()92
if (capacity > 0L)93
result.ensureWritable(capacity)94
return result95
}96
}98
private fun acquireState() {99
while (!stateLock.compareAndSet(false, true, MemoryOrder.Acquire, MemoryOrder.Relaxed)) {}100
}102
private fun releaseState() {103
stateLock.store(false, MemoryOrder.Release)104
}106
private fun <T> withState(block: () -> T): T {107
acquireState()108
try {109
return block()110
}111
finally {112
releaseState()113
}114
}116
private fun requireOpen() {117
if (closed)118
throw IllegalStateException(Some("buffer is closed"))119
}121
private fun requireMutable() {122
requireOpen()123
if (borrowed)124
throw IllegalStateException(Some("buffer is borrowed"))125
}127
private fun requireReadable(count: Long) {128
requireMutable()129
requireCount(count)130
if (count > writer - reader)131
throw IndexOutOfBoundsException()132
}134
private fun requireWritable(count: Long) {135
requireMutable()136
requireCount(count)137
if (count > storageCapacity - writer)138
throw IndexOutOfBoundsException()139
}141
private fun requireIndex(index: Long) {142
requireOpen()143
if (index < 0L || index >= writer)144
throw IndexOutOfBoundsException()145
}147
private fun resize(capacity: Long) {148
@Unsafe149
{150
val(next, error) = nativeMemoryResize(memory, capacity)151
if (next == None) {152
throw PlatformException(153
"allocate native buffer",154
PlatformErrorKind.NoMemory,155
Some(NativeError(NativeErrorDomain.PosixErrno, error))156
)157
}158
val delta = capacity - storageCapacity159
memory = next160
storageCapacity = capacity161
gcAdjustPressure(delta)162
}163
}165
/**166
* Grows storage when needed to provide at least count additional writable bytes, preserving167
* positions and initialized content.168
*/169
public fun ensureWritable(count: Long) {170
withState {171
requireMutable()172
requireCount(count)173
if (count <= storageCapacity - writer)174
return@withState175
if (count > Long.MAX_VALUE - writer)176
throw ArithmeticException()177
val needed = writer + count178
val grown =179
if (storageCapacity <= Long.MAX_VALUE / 2L)180
storageCapacity * 2L181
else182
Long.MAX_VALUE183
resize(184
if (grown > needed)185
grown186
else187
needed188
)189
}190
}192
/**193
* Resets both positions to zero without promising to erase stored memory.194
*/195
public fun clear() {196
withState {197
requireMutable()198
reader = 0L199
writer = 0L200
}201
}203
/**204
* Moves unread bytes to offset zero and resets positions around that content.205
*/206
public fun compact() {207
withState {208
requireMutable()209
val count = writer - reader210
if (count > 0L && reader > 0L) {211
@Unsafe212
{213
nativeMemoryMove(memory!!, memory!! + reader, count)214
}215
}216
reader = 0L217
writer = count218
}219
}221
/**222
* Advances the read position by count available bytes.223
*/224
public fun skip(count: Long) {225
withState {226
requireReadable(count)227
reader += count228
}229
}231
/**232
* Reads an initialized byte at an absolute index without moving either position.233
*/234
public fun getByte(index: Long): Byte {235
return withState {236
requireIndex(index)237
@Unsafe238
{239
return@withState memory!!.load(index)240
}241
}242
}244
/**245
* Copies an initialized absolute byte range without moving either position.246
*/247
public fun getBytes(index: Long, count: Long): Array<Byte> {248
return withState {249
requireOpen()250
requireCount(count)251
if (index < 0L || index > writer || count > writer - index)252
throw IndexOutOfBoundsException()253
return@withState Array<Byte>(count) {254
offset -> @Unsafe255
{256
return@Array memory!!.load(index + offset)257
}258
}259
}260
}262
/**263
* Replaces an initialized byte at an absolute index without moving either position.264
*/265
public fun setByte(index: Long, value: Byte) {266
withState {267
requireMutable()268
requireIndex(index)269
@Unsafe270
{271
memory!!.store(index, value)272
}273
}274
}276
/**277
* Reads one byte and advances the read position.278
*/279
public fun readByte(): Byte = readInt8()280
/**281
* Appends one byte and advances the write position.282
*/283
public fun writeByte(value: Byte) {284
writeInt8(value)285
}287
/**288
* Copies count readable bytes into an independent array and advances the read position.289
*/290
public fun readBytes(count: Long): Array<Byte> {291
return withState {292
requireReadable(count)293
val start = reader294
val result =295
Array<Byte>(count) {296
index -> @Unsafe297
{298
return@Array memory!!.load(start + index)299
}300
}301
reader += count302
return@withState result303
}304
}306
/**307
* Copies exactly count readable bytes into the selected array region and advances the read308
* position.309
*/310
public fun readInto(311
array: MutableArray<Byte>,312
offset: Long = 0L,313
count: Long = array.size - offset314
) {315
withState {316
requireReadable(count)317
requireArrayRange(array.size, offset, count)318
if (count > 0L) {319
@Unsafe320
{321
array.withDataPointer {322
pointer,323
_ -> @Unsafe324
{325
nativeMemoryMove(pointer + offset, memory!! + reader, count)326
}327
}328
}329
}330
reader += count331
}332
}334
/**335
* Appends the selected array region and advances the write position.336
*/337
public fun writeBytes(array: List<Byte>, offset: Long = 0L, count: Long = array.size - offset) {338
requireArrayRange(array.size, offset, count)339
val(destination, available) = beginScopedBorrow(true)340
try {341
if (count > available)342
throw IndexOutOfBoundsException()343
if (count > 0L) {344
if (array is Array<Byte>) {345
copyPinnedByteRange(destination!!, array as Array<Byte>, offset, count)346
} else {347
val snapshot = Array<Byte>(count) { index -> array[offset + index] }348
copyPinnedByteRange(destination!!, snapshot, 0L, count)349
}350
}351
} catch (error: Throwable) {352
finishBorrow(0L, available, true)353
throw error354
}355
finishBorrow(count, available, true)356
}358
private fun read(width: Long, order: ByteOrder): ULong {359
return withState {360
requireReadable(width)361
var value = 0uL362
var index = 0L363
@Unsafe364
{365
while (index < width) {366
val offset =367
if (order == ByteOrder.BigEndian)368
index369
else370
width - index - 1L371
value = (value shl 8L) or memory!!.load(reader + offset).toUByte().toULong()372
index += 1L373
}374
}375
reader += width376
return@withState value377
}378
}380
private fun write(value: ULong, width: Long, order: ByteOrder) {381
withState {382
requireWritable(width)383
var index = 0L384
@Unsafe385
{386
while (index < width) {387
val shift =388
(389
if (order == ByteOrder.BigEndian)390
width - index - 1L391
else392
index393
) *394
8L395
memory!!.store(writer + index, (value shr shift).toByte())396
index += 1L397
}398
}399
writer += width400
}401
}403
/**404
* Reads 1 bytes as Int8 and advances the read position.405
*/406
public fun readInt8(): Int8 = read(1L, ByteOrder.BigEndian).toByte()407
/**408
* Reads 1 bytes as UInt8 and advances the read position.409
*/410
public fun readUInt8(): UInt8 = read(1L, ByteOrder.BigEndian).toUByte()411
/**412
* Reads 2 bytes as Int16 in the selected byte order and advances the read position.413
*/414
public fun readInt16(order: ByteOrder): Int16 = read(2L, order).toShort()415
/**416
* Reads 2 bytes as UInt16 in the selected byte order and advances the read position.417
*/418
public fun readUInt16(order: ByteOrder): UInt16 = read(2L, order).toUShort()419
/**420
* Reads 4 bytes as Int32 in the selected byte order and advances the read position.421
*/422
public fun readInt32(order: ByteOrder): Int32 = read(4L, order).toInt()423
/**424
* Reads 4 bytes as UInt32 in the selected byte order and advances the read position.425
*/426
public fun readUInt32(order: ByteOrder): UInt32 = read(4L, order).toUInt()427
/**428
* Reads 8 bytes as Int64 in the selected byte order and advances the read position.429
*/430
public fun readInt64(order: ByteOrder): Int64 = read(8L, order).toLong()431
/**432
* Reads 8 bytes as UInt64 in the selected byte order and advances the read position.433
*/434
public fun readUInt64(order: ByteOrder): UInt64 = read(8L, order)435
/**436
* Reads 4 bytes as Float in the selected byte order and advances the read position.437
*/438
public fun readFloat(order: ByteOrder): Float = Float.fromBits(readInt32(order))439
/**440
* Reads 8 bytes as Double in the selected byte order and advances the read position.441
*/442
public fun readDouble(order: ByteOrder): Double = Double.fromBits(readInt64(order))444
/**445
* Appends 1 bytes representing Int8 and advances the write position.446
*/447
public fun writeInt8(value: Int8) {448
write(value.toULong(), 1L, ByteOrder.BigEndian)449
}450
/**451
* Appends 1 bytes representing UInt8 and advances the write position.452
*/453
public fun writeUInt8(value: UInt8) {454
write(value.toULong(), 1L, ByteOrder.BigEndian)455
}456
/**457
* Appends 2 bytes representing Int16 in the selected byte order and advances the write458
* position.459
*/460
public fun writeInt16(value: Int16, order: ByteOrder) {461
write(value.toULong(), 2L, order)462
}463
/**464
* Appends 2 bytes representing UInt16 in the selected byte order and advances the write465
* position.466
*/467
public fun writeUInt16(value: UInt16, order: ByteOrder) {468
write(value.toULong(), 2L, order)469
}470
/**471
* Appends 4 bytes representing Int32 in the selected byte order and advances the write472
* position.473
*/474
public fun writeInt32(value: Int32, order: ByteOrder) {475
write(value.toULong(), 4L, order)476
}477
/**478
* Appends 4 bytes representing UInt32 in the selected byte order and advances the write479
* position.480
*/481
public fun writeUInt32(value: UInt32, order: ByteOrder) {482
write(value.toULong(), 4L, order)483
}484
/**485
* Appends 8 bytes representing Int64 in the selected byte order and advances the write486
* position.487
*/488
public fun writeInt64(value: Int64, order: ByteOrder) {489
write(value.toULong(), 8L, order)490
}491
/**492
* Appends 8 bytes representing UInt64 in the selected byte order and advances the write493
* position.494
*/495
public fun writeUInt64(value: UInt64, order: ByteOrder) {496
write(value, 8L, order)497
}498
/**499
* Appends 4 bytes representing Float in the selected byte order and advances the write500
* position.501
*/502
public fun writeFloat(value: Float, order: ByteOrder) {503
writeInt32(value.toBits(), order)504
}505
/**506
* Appends 8 bytes representing Double in the selected byte order and advances the write507
* position.508
*/509
public fun writeDouble(value: Double, order: ByteOrder) {510
writeInt64(value.toBits(), order)511
}513
/**514
* Borrows the readable pointer and length only for the callback; the pointer must not escape.515
* This operation does not consume bytes.516
*/517
@Unsafe518
public fun <R> withReadableBytes(block: (Ptr<Byte>?, Long) -> R): R {519
val(pointer, length) = beginScopedBorrow(false)520
try {521
return block(pointer, length)522
}523
finally {524
finishBorrow(0L, length, false)525
}526
}528
/**529
* Borrows writable native storage for the callback, then advances the write position by the530
* returned valid count.531
*/532
@Unsafe533
public fun withWritableBytes(block: (Ptr<Byte>?, Long) -> Long): Long {534
val(pointer, length) = beginScopedBorrow(true)535
val count =536
try {537
block(pointer, length)538
}539
catch (error: Throwable) {540
finishBorrow(0L, length, true);541
throw error542
}543
finishBorrow(count, length, true)544
return count545
}547
/**548
* Begins an explicit readable borrow of count bytes. Complete it once with the consumed count549
* after native access ends.550
*/551
@Unsafe552
public fun borrowReadable(count: Long): NativeByteBorrow = beginBorrow(Some(count), false)554
/**555
* Begins an explicit writable borrow of count bytes. Complete it once with the produced count556
* after native access ends.557
*/558
@Unsafe559
public fun borrowWritable(count: Long): NativeByteBorrow = beginBorrow(Some(count), true)561
// The caller holds stateLock; both borrow forms validate the same range.562
private fun borrowRange(count: Long?, writable: Boolean): (Ptr<Byte>?, Long) {563
requireMutable()564
val available =565
if (writable)566
storageCapacity - writer567
else568
writer - reader569
val length = count ?: available570
requireCount(length)571
if (length > available)572
throw IndexOutOfBoundsException()573
val offset =574
if (writable)575
writer576
else577
reader578
@Unsafe579
{580
val pointer: Ptr<Byte>? =581
if (length == 0L)582
None583
else584
Some(memory!! + offset)585
return (pointer, length)586
}587
}589
private fun beginScopedBorrow(writable: Boolean): (Ptr<Byte>?, Long) {590
acquireState()591
try {592
val range = borrowRange(None, writable)593
borrowed = true594
return range595
}596
finally {597
releaseState()598
}599
}601
private fun beginBorrow(count: Long?, writable: Boolean): NativeByteBorrow {602
acquireState()603
try {604
val(pointer, length) = borrowRange(count, writable)605
val borrow = NativeByteBorrow(this, pointer, length, writable)606
borrowed = true607
return borrow608
}609
finally {610
releaseState()611
}612
}614
internal fun finishBorrow(count: Long, length: Long, writable: Boolean) {615
acquireState()616
try {617
borrowed = false618
if (count < 0L || count > length)619
throw IllegalArgumentException(Some("invalid borrowed byte count"))620
if (writable)621
writer += count622
else623
reader += count624
}625
finally {626
releaseState()627
}628
}630
/**631
* Releases native storage; an outstanding borrow prevents closure.632
*/633
public override fun close() {634
withState {635
if (closed)636
return@withState637
requireMutable()638
val owned = memory639
val capacity = storageCapacity640
memory = None641
storageCapacity = 0L642
reader = 0L643
writer = 0L644
closed = true645
when (owned) {646
case Some(val pointer) -> @Unsafe647
{648
nativeMemoryFree(pointer);649
gcAdjustPressure(-capacity)650
}651
case None -> {}652
}653
}654
}656
release {657
when (memory) {658
case Some(val pointer) -> @Unsafe659
{660
nativeMemoryFree(pointer);661
gcAdjustPressure(-storageCapacity)662
}663
case None -> {}664
}665
}666
}668
private fun requireCount(count: Long) {669
if (count < 0L)670
throw IllegalArgumentException(Some("negative byte count"))671
}673
private fun requireArrayRange(size: Long, offset: Long, count: Long) {674
if (offset < 0L || offset > size || count > size - offset)675
throw IndexOutOfBoundsException()676
}