// 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())
	}
}