Travis Griggs
02/10/2021, 4:36 PManInt.le.ubytes
.
In Swift, I'd accomplish this with something like:
protocol LittleEndianEncodable {
var byteSize:UInt get()
var le:LittleEndianEncoder get()
}
extension LittleEndianEncodable {
var le:LittleEndianEncoder<Self> {
return LittleEndianEncoder(self)
}
}
struct LittleEndianEncoder {
var value:LittleEndianEncodable
var ubytes:Data { // well, Data in Swift
return 0..<self.value.byteSize.map { index in self.value >> (index * 8 ) & 0xFF }
}
}
Or something close to that. Then I'd just add an extension to the existing int classes and be off to the races. But in Kotlin, I can't create a new interface that I then enforce on existing class types. Is there an alternate approach to do this? Basically I want le
to return a "trampoline" object which can return the ubytes
for the object it's wrapped, and do it generically, so I don't have to make individual transformer types for each uint type. I looked through the docs, hoping to find that there was already something that answers the byte size for int types, but didn't see anything 😞diesieben07
02/10/2021, 5:03 PMbyteSize
and byte-wise access for each type there? I assume it doesn't happen "by magic"?Travis Griggs
02/10/2021, 5:21 PMle
extension, because I already provided a default implementation for that in the LittleEndianEncoding extension.
In Kotlin, you can add (static) extension methods to existing types (I love and use this). But you can't (as far as I understand) extend an existing type to conform to a new protocol.Travis Griggs
02/10/2021, 5:23 PMAnimesh Sahu
02/10/2021, 5:33 PMAnimesh Sahu
02/10/2021, 5:39 PMNir
02/10/2021, 5:40 PMdiesieben07
02/10/2021, 5:40 PMNir
02/10/2021, 5:40 PMNir
02/10/2021, 5:43 PMTravis Griggs
02/10/2021, 5:45 PMdata class UIntLittleEndianEncoding(val value:UInt) {
val ubytes:UByteArray get() {
return UByteArray(4) { index -> ((this.value shr (index * 8)) and 0xFFu).ubyte }
}
}
val UInt.le:UIntLittleEndianEncoding get() = UIntLittleEndianEncoding(this)
Yes, I can do that. But I was hoping to make a more general purpose/parametric transform object that could handle all kinds of Unsigned thingsTravis Griggs
02/10/2021, 5:54 PMNir
02/10/2021, 5:55 PMNir
02/10/2021, 5:55 PMTravis Griggs
02/10/2021, 6:04 PMval UInt.ubytes_le:UByteArray
get() {
return UByteArray(4) { index -> ((this shr (index * 8)) and 0xFFu).ubyte }
}
Travis Griggs
02/10/2021, 6:05 PM