Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,42 +20,23 @@ sealed interface SpellContinuation {
fun pushFrame(frame: ContinuationFrame): SpellContinuation = NotDone(frame, this)

companion object {
// TODO port: maybe serialize to list like before?
// TODO port: maybe unit should be first
@JvmStatic
val CODEC = Codec.recursive<SpellContinuation>(
SpellContinuation::class.java.simpleName
) { recursed: Codec<SpellContinuation> ->
Codec.withAlternative<SpellContinuation>(
Codec.unit(Done),
RecordCodecBuilder.create<NotDone> { inst ->
inst.group(
ContinuationFrame.Type.TYPED_CODEC.fieldOf("frame").forGetter { it.frame },
recursed.fieldOf("next").forGetter { it.next }
).apply(inst, ::NotDone)
}
)
}
val CODEC = ContinuationFrame.Type.TYPED_CODEC.listOf().xmap(::fromList, ::toList)
@JvmStatic
val STREAM_CODEC = StreamCodec.recursive<RegistryFriendlyByteBuf, SpellContinuation> { recursed ->
withAlternative(
StreamCodec.unit(Done),
StreamCodec.composite(
ContinuationFrame.Type.TYPED_STREAM_CODEC, NotDone::frame,
recursed, NotDone::next,
::NotDone
).map(Function.identity()) { it as NotDone }
)
val STREAM_CODEC = ContinuationFrame.Type.TYPED_STREAM_CODEC.apply(ByteBufCodecs.list()).map(::fromList, ::toList)

private fun fromList(list: List<ContinuationFrame>): SpellContinuation {
return list.foldRight(Done, ::NotDone)
}

private fun <B: ByteBuf, T> withAlternative(primary: StreamCodec<B, T>, alternative: StreamCodec<B, T>): StreamCodec<B, T> {
return ByteBufCodecs.either<B, T, T>(
primary,
alternative
).map<T>(
Function { either: Either<T, T> -> Either.unwrap(either) },
Function { value: T -> Either.left(value) }
)
private fun toList(sc: SpellContinuation): List<ContinuationFrame> {
val result = ArrayList<ContinuationFrame>()
var acc = sc
while(acc is NotDone) {
result.add(acc.frame)
acc = acc.next
}
return result
}
}
}
Loading