Last active
July 20, 2020 18:33
-
-
Save tobiberger/178f436d23fa40f388f4c891921cf0f7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.time.ZonedDateTime | |
data class MessageWithExpiry( | |
val messageSerialized: ByteArray, | |
val expiryDate: ZonedDateTime | |
) | |
data class Batch( | |
val messages: Array<ByteArray>, | |
val latestMessageExpiryDate: ZonedDateTime | |
) | |
private val MAX_BATCH_SIZE = 8 * 1024 * 1024 | |
fun Sequence<MessageWithExpiry>.batchMessages() = sequence { | |
val batchMessages = mutableListOf<MessageWithExpiry>() | |
var batchSize = 0 | |
this@batchMessages.forEach { message -> | |
val messageSize = message.messageSerialized.size | |
if (batchSize + messageSize > MAX_BATCH_SIZE && batchMessages.isNotEmpty()) { | |
yield(batchMessages.toBatch()) | |
batchMessages.clear() | |
batchSize = 0 | |
} | |
batchMessages += message | |
batchSize += messageSize | |
} | |
if (batchMessages.isNotEmpty()) { | |
yield(batchMessages.toBatch()) | |
} | |
} | |
fun MutableList<MessageWithExpiry>.toBatch(): Batch { | |
return Batch( | |
map { it.messageSerialized }.toTypedArray(), | |
maxBy { it.expiryDate }!!.expiryDate | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment