| 392 | * @since 4.0.6 |
| 393 | */ |
| 394 | export const decode = <IE = never, Done = unknown>(): Channel.Channel< |
| 395 | Arr.NonEmptyReadonlyArray<Entry<ZipError | IE>>, |
| 396 | ZipError | IE, |
| 397 | Done, |
| 398 | Arr.NonEmptyReadonlyArray<Uint8Array>, |
| 399 | IE, |
| 400 | Done |
| 401 | > => |
| 402 | Channel.fromTransform((upstream, scope) => |
| 403 | Effect.suspend(() => { |
| 404 | const decoder = new Decoder() |
| 405 | let done: { readonly value: Done } | undefined |
| 406 | let pulls = 0 |
| 407 | |
| 408 | const pullUpstream = upstream.pipe( |
| 409 | Effect.map((chunks) => { |
| 410 | pulls++ |
| 411 | for (const chunk of chunks) decoder.push(chunk) |
| 412 | }), |
| 413 | Pull.catchDone((value) => { |
| 414 | pulls++ |
| 415 | done = { value: value as Done } |
| 416 | decoder.end() |
| 417 | return Effect.void |
| 418 | }) |
| 419 | ) |
| 420 | |
| 421 | // Serialize entry and body pulls; reuse input pulled while waiting for the lock. |
| 422 | const lock = Semaphore.makeUnsafe(1) |
| 423 | const pullInput = (seen: number) => |
| 424 | lock.withPermit(Effect.suspend(() => pulls === seen ? pullUpstream : Effect.void)) |
| 425 | |
| 426 | const run = <A, D>(f: () => A | undefined | typeof NeedInput, end: () => D): Pull.Pull<A, ZipError | IE, D> => |
| 427 | Effect.suspend(function loop(): Pull.Pull<A, ZipError | IE, D> { |
| 428 | const seen = pulls |
| 429 | let result: A | undefined | typeof NeedInput |
| 430 | try { |
| 431 | result = f() |
| 432 | } catch (error) { |
| 433 | return isZipError(error) ? Effect.fail(error) : Effect.die(error) |
| 434 | } |
| 435 | if (result === NeedInput) return Effect.flatMap(pullInput(seen), loop) |
| 436 | return result === undefined ? Cause.done(end()) : Effect.succeed(result) |
| 437 | }) |
| 438 | |
| 439 | const body = (id: number): Stream.Stream<Uint8Array, ZipError | IE> => |
| 440 | Stream.fromPull(Effect.succeed(run(() => decoder.read(id), () => undefined))) |
| 441 | |
| 442 | const next = run(() => { |
| 443 | const header = decoder.next() |
| 444 | return header === NeedInput || header === undefined |
| 445 | ? header |
| 446 | : Arr.of({ header, body: body(decoder.generation) }) |
| 447 | }, () => done!.value) |
| 448 | |
| 449 | return Effect.as(Scope.addFinalizer(scope, Effect.sync(() => decoder.close())), next) |
| 450 | }) |
| 451 | ) |