readFromBufferAsUnsigned function
Read a specified piece of the buffer and convert it to an integer number (unsigned).
If offset
is aligned, tat is if (offset
mod byteCnt
) = 0,
the function chooses more efficient implementation.
On unaligned data, byte-by-byte copying takes place.
The only valid values for byteCnt
are 1, 2, 4 and 8 (any other
will cause a MemException).
Implementation
int readFromBufferAsUnsigned(Pointer<Uint8> buffer, int offset, int byteCnt) {
if (offset % byteCnt == 0) {
// the offset is aligned
switch (byteCnt) {
case 1:
return buffer[offset];
case 2:
return Pointer<Uint16>.fromAddress(buffer.address + offset)
.asTypedList(1)[0];
case 4:
return Pointer<Uint32>.fromAddress(buffer.address + offset)
.asTypedList(1)[0];
case 8:
return Pointer<Uint64>.fromAddress(buffer.address + offset)
.asTypedList(1)[0];
default:
throw MemException(
"Invalid byte count for reading int from buffer: $byteCnt");
}
} else {
// the offset not aligned - copying byte by byte
final bytes = Uint8List(byteCnt);
for (var i = 0; i < byteCnt; i++) {
bytes[i] = buffer[offset + i];
}
return fromBytesAsUnsigned(bytes);
}
}