reading the first n bytes of a byte stream (in form of a AsyncIterable) feels cumbersome and error prone.
Is there a better way to implement this?
async function shift(
  length: number,
  stream: AsyncIterable<Uint8Array>
): Promise<[Uint8Array, AsyncIterable<Uint8Array>]> {
  const prefix = new Uint8Array(length);
  let offset = 0;
  const iterator = stream[Symbol.asyncIterator]();
  while (true) {
    const { done, value } = await iterator.next();
    if (done) {
      throw new Error("Buffer underflow");
    } else {
      const chunk = value;
      if (chunk.length < length - offset) {
        prefix.set(chunk, offset);
        offset += chunk.length;
      } else {
        const slice = chunk.slice(0, length - offset);
        prefix.set(slice, offset);
        return [prefix, prepend(chunk.slice(slice.length), stream)];
      }
    }
  }
}
async function* prepend(
  prefix: Uint8Array,
  stream: AsyncIterable<Uint8Array>
) {
  yield prefix;
  yield* stream;
}
 
     
    