Bimba.git

ref: da3ea3a5dcbbe400faced1223c2a6512f33056ff

fruchtfleisch/src/main/java/xyz/apiote/fruchtfleisch/Writer.kt


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: GPL-3.0-or-later

package xyz.apiote.fruchtfleisch

import java.io.OutputStream

@Suppress("MemberVisibilityCanBePrivate")
class Writer(private val stream: OutputStream) {
	@OptIn(ExperimentalUnsignedTypes::class)
	fun writeUInt(v: ULong) {
		var value = v
		val bytes = mutableListOf<UByte>()
		while (value >= 0x80u) {
			bytes.add(value.toUByte() or 0x80u)
			value = value.shr(7)
		}
		bytes.add(value.toUByte())
		stream.write(bytes.toUByteArray().toByteArray())
	}

	fun writeFixedData(v: ByteArray) {
		stream.write(v)
	}

	fun writeData(v: ByteArray) {
		writeUInt(v.size.toULong())
		writeFixedData(v)
	}

	fun writeString(v: String) {
		writeData(v.encodeToByteArray())
	}
}