diff --git a/gradle.properties b/gradle.properties index 24212a0..8e48d10 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,7 +4,7 @@ kotlin.code.style=official specifyKotlinAsDependency=false projectGroup=ru.dbotthepony.kommons -projectVersion=2.9.23 +projectVersion=2.9.24 guavaDepVersion=33.0.0 gsonDepVersion=2.8.9 diff --git a/src/main/kotlin/ru/dbotthepony/kommons/io/StreamCodec.kt b/src/main/kotlin/ru/dbotthepony/kommons/io/StreamCodec.kt index 1dd6558..609851d 100644 --- a/src/main/kotlin/ru/dbotthepony/kommons/io/StreamCodec.kt +++ b/src/main/kotlin/ru/dbotthepony/kommons/io/StreamCodec.kt @@ -179,8 +179,33 @@ interface StreamCodec { return value.map(codec::copy) } } + + class Mapping(private val codec: StreamCodec, private val from: T.() -> R, private val to: R.() -> T, private val copy: R.() -> R = { this }) : StreamCodec { + override fun read(stream: DataInputStream): R { + return from(codec.read(stream)) + } + + override fun write(stream: DataOutputStream, value: R) { + codec.write(stream, to(value)) + } + + override fun copy(value: R): R { + return copy(value) + } + } } +fun StreamCodec.map(from: T.() -> R, to: R.() -> T): StreamCodec { + return StreamCodec.Mapping(this, from, to) +} + +fun StreamCodec.map(from: T.() -> R, to: R.() -> T, copy: R.() -> R): StreamCodec { + return StreamCodec.Mapping(this, from, to, copy) +} + +fun StreamCodec.optional() = StreamCodec.Optional(this) +fun StreamCodec.koptional() = StreamCodec.KOptional(this) + val NullValueCodec = StreamCodec.Impl({ _ -> null }, { _, _ -> }) val BooleanValueCodec = StreamCodec.Impl(DataInputStream::readBoolean, 1L, DataOutputStream::writeBoolean) val ByteValueCodec = StreamCodec.Impl(DataInputStream::readByte, 1L, { s, v -> s.writeByte(v.toInt()) }) @@ -196,6 +221,11 @@ val VarIntValueCodec = StreamCodec.Impl(DataInputStream::readSignedVarInt, DataO val VarLongValueCodec = StreamCodec.Impl(DataInputStream::readSignedVarLong, DataOutputStream::writeSignedVarLong) val BinaryStringCodec = StreamCodec.Impl(DataInputStream::readBinaryString, DataOutputStream::writeBinaryString) +val UnsignedVarLongCodec = StreamCodec.Impl(DataInputStream::readVarLong, DataOutputStream::writeVarLong) +val UnsignedVarIntCodec = StreamCodec.Impl(DataInputStream::readVarInt, DataOutputStream::writeVarInt) + +val ByteArrayCodec = StreamCodec.Impl(DataInputStream::readByteArray, DataOutputStream::writeByteArray) + val RGBCodec = StreamCodec.Impl( { s -> RGBAColor(s.readFloat(), s.readFloat(), s.readFloat()) }, { s, v -> s.writeFloat(v.red); s.writeFloat(v.green); s.writeFloat(v.blue) })