Skip to content

Commit e1cb4f2

Browse files
authored
Fix index count when packing bytes to typed number array (#7)
1 parent 0bb7540 commit e1cb4f2

File tree

1 file changed

+10
-7
lines changed
  • library/endian/src/commonMain/kotlin/org/kotlincrypto/bitops/endian/internal

1 file changed

+10
-7
lines changed

library/endian/src/commonMain/kotlin/org/kotlincrypto/bitops/endian/internal/-EndianUtils.kt

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,7 @@ internal inline fun ByteArray.packNumberAllElsePartial(
167167
ushr: (bits: Int) -> Byte,
168168
): ByteArray {
169169
// Check endIndex first
170-
return if (sourceIndexEnd == numberSizeBytes && sourceIndexStart == 0) packNumber()
170+
return if (sourceIndexEnd == numberSizeBytes && sourceIndexStart == 0) packNumber(this)
171171
else packNumberPartial(destOffset, sourceIndexStart, sourceIndexEnd, ushr)
172172
}
173173

@@ -177,9 +177,9 @@ internal inline fun ByteArray.packNumberPartial(
177177
sourceIndexEnd: Int,
178178
ushr: (bits: Int) -> Byte,
179179
): ByteArray {
180-
var pos = destOffset
180+
var destPos = destOffset
181181
for (i in sourceIndexStart..<sourceIndexEnd) {
182-
this[pos++] = ushr(Byte.SIZE_BITS * i)
182+
this[destPos++] = ushr(Byte.SIZE_BITS * i)
183183
}
184184
return this
185185
}
@@ -191,20 +191,23 @@ internal inline fun ByteArray.packArray(
191191
numberSizeBytes: Int,
192192
packNumber: ByteArray.(sourcePos: Int, destPos: Int) -> ByteArray,
193193
): ByteArray {
194-
for (i in sourceIndexStart..<sourceIndexEnd) {
195-
packNumber(i, (i * numberSizeBytes) + destOffset)
194+
var destPos = destOffset
195+
var sourcePos = sourceIndexStart
196+
while (sourcePos < sourceIndexEnd) {
197+
packNumber(this, sourcePos++, destPos)
198+
destPos += numberSizeBytes
196199
}
197200
return this
198201
}
199202

200-
internal inline fun <Dest: Any> Dest.packArray(
203+
internal inline fun <TypedArray: Any> TypedArray.packArray(
201204
source: ByteArray,
202205
destOffset: Int,
203206
sourceIndexStart: Int,
204207
sourceIndexEnd: Int,
205208
numberSizeBytes: Int,
206209
unpackNumber: ByteArray.(sourcePos: Int, destPos: Int) -> Unit,
207-
): Dest {
210+
): TypedArray {
208211
var destPos = destOffset
209212
var sourcePos = sourceIndexStart
210213
while (sourcePos < sourceIndexEnd) {

0 commit comments

Comments
 (0)