簡體   English   中英

如何將 UUID 的 ArrayList 轉換為 ByteArray?

[英]How Do I Convert An ArrayList of UUID To A ByteArray?

object UUIDConversion {
    fun UUID.toByteArray() : ByteArray {
        val byteBuffer = ByteBuffer.wrap(ByteArray(16))
        byteBuffer.putLong(this.mostSignificantBits)
        byteBuffer.putLong(this.leastSignificantBits)
        return byteBuffer.array()
    }
    fun ByteArray.toUUID() : UUID {
        val byteBuffer = ByteBuffer.wrap(this)
        val mostSignificantBits = byteBuffer.long
        val leastSignificantBits = byteBuffer.long
        return UUID(mostSignificantBits, leastSignificantBits)
    }
}

我有上面的代碼將 UUID 轉換為 ByteArray 並將其轉換回來,但我還需要能夠將 ArrayList 轉換為 ByteArray 並將其轉換回來。 我該怎么做呢? 如果您想知道為什么我需要這樣做,那是因為我需要將 HashMap<UUID, ArrayList 存儲在鍵值數據庫中,並且我需要將其轉換為 ByteArray 並返回使用它。

Java 或 Kotlin 答案都很好。

您可以使用+運算符連接獨立的 UUID 字節 arrays,如下所示:

val allUUIDs : ByteArray = listOfUUID.fold(ByteArray(0)) { buffer, uuid -> buffer + uuid.toByteArray() }

但是,如果您要轉換的鏈很長,則性能可能會顯着下降。 相反,您可以使用專用方法來讀取/寫入字節緩沖區:

import java.nio.ByteBuffer
import java.util.*
import kotlin.RuntimeException

fun ByteBuffer.readUUIDs(nbUUIDs : Int = remaining()/16) : Sequence<UUID> {
    if (nbUUIDs <= 0) return emptySequence()
    val nbBytes = nbUUIDs * 16
    // Defensive copy -> resulting sequence becomes independant from receiver buffer
    val defCpy = ByteArray(nbBytes)
    // slice is required to left source buffer untouched
    slice().get(defCpy)
    val view = ByteBuffer.wrap(defCpy)
    return (1..nbUUIDs).asSequence()
        .map { UUID(view.long, view.long) }
}

fun List<UUID>?.write() : ByteBuffer? {
    if (this == null || isEmpty()) return null;
    val buffer = ByteBuffer.allocate(Math.multiplyExact(size, 16))
    forEach { uuid ->
        buffer.putLong(uuid.mostSignificantBits)
        buffer.putLong(uuid.leastSignificantBits)
    }
    buffer.rewind()
    return buffer
}

fun main() {
    val uuids = (0..3).asSequence().map { UUID.randomUUID() }.toList()
    val writtenUUIDs = uuids.write()
    val uuidSequence = writtenUUIDs ?.readUUIDs() ?: throw RuntimeException("Bug")

    // Note that now, we can do whatever we want with the buffer. The sequence is not impacted
    writtenUUIDs.getLong()
    writtenUUIDs.putLong(-1)

    val readBack = uuidSequence?.toList()
    assert(uuids == readBack) { throw RuntimeException("Bug") }
    println(uuids)
    println(readBack)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM