* Composes a new array with elements having the given number of bits and * translates the content of the source array to it. * @param {number[]} src Source array * @param {number} srcSize Bit size of source array elements * @param {number} dstSize Bit size of destination array elements
(src, srcSize, dstSize, trimEnd = false)
| 205 | * Uint8Array, if dstSize is set to 8. |
| 206 | */ |
| 207 | static resizeBitSizedArray (src, srcSize, dstSize, trimEnd = false) { |
| 208 | const size = Math.ceil(src.length * srcSize / dstSize) |
| 209 | const dst = dstSize === 8 ? new Uint8Array(size) : new Array(size).fill(0) |
| 210 | |
| 211 | // Destination element mask (e.g. 11111111b for dstSize = 8) |
| 212 | const dstElementMask = (1 << dstSize) - 1 |
| 213 | |
| 214 | let element, startBitIndex, endBitIndex, dstStartIndex, dstEndIndex |
| 215 | let rightBitOffset, remainder, j |
| 216 | |
| 217 | for (let i = 0; i < src.length; i++) { |
| 218 | element = src[i] |
| 219 | |
| 220 | // Start and end bit index of the current element |
| 221 | startBitIndex = i * srcSize |
| 222 | endBitIndex = (i + 1) * srcSize |
| 223 | |
| 224 | // Start and end index in the destination array |
| 225 | dstStartIndex = Math.floor(startBitIndex / dstSize) |
| 226 | dstEndIndex = Math.floor(endBitIndex / dstSize) |
| 227 | |
| 228 | // Calculate right bit offset in the last destination element |
| 229 | rightBitOffset = dstSize - endBitIndex % dstSize |
| 230 | |
| 231 | // Begin at the end |
| 232 | dst[dstEndIndex] |= (element << rightBitOffset) & dstElementMask |
| 233 | remainder = element >> (dstSize - rightBitOffset) |
| 234 | |
| 235 | // Inject each dst element until no remainder is left |
| 236 | j = dstEndIndex |
| 237 | while (--j >= dstStartIndex && remainder > 0) { |
| 238 | dst[j] |= remainder & dstElementMask |
| 239 | remainder = remainder >> dstSize |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | if (trimEnd) { |
| 244 | // Trim trailing elements at the end |
| 245 | let k = dst.length - 1 |
| 246 | while (dst[k] === 0) { |
| 247 | k-- |
| 248 | } |
| 249 | return dst.slice(0, k + 1) |
| 250 | } |
| 251 | |
| 252 | return dst |
| 253 | } |
| 254 | } |
no outgoing calls
no test coverage detected