()
| 351 | * @since 4.0.5 |
| 352 | */ |
| 353 | export const decode = <IE = never, Done = unknown>(): Channel.Channel< |
| 354 | Arr.NonEmptyReadonlyArray<Entry<TarError | IE>>, |
| 355 | TarError | IE, |
| 356 | Done, |
| 357 | Arr.NonEmptyReadonlyArray<Uint8Array>, |
| 358 | IE, |
| 359 | Done |
| 360 | > => |
| 361 | Channel.fromTransform((upstream, scope) => |
| 362 | Effect.suspend(() => { |
| 363 | const decoder = new Decoder() |
| 364 | let done: { readonly value: Done } | undefined |
| 365 | let pulls = 0 |
| 366 | |
| 367 | const pullUpstream = upstream.pipe( |
| 368 | Effect.map((chunks) => { |
| 369 | pulls++ |
| 370 | for (const chunk of chunks) decoder.push(chunk) |
| 371 | }), |
| 372 | Pull.catchDone((value) => { |
| 373 | pulls++ |
| 374 | done = { value: value as Done } |
| 375 | decoder.end() |
| 376 | return Effect.void |
| 377 | }) |
| 378 | ) |
| 379 | |
| 380 | // Serialize entry and body pulls; reuse input pulled while waiting for the lock. |
| 381 | const lock = Semaphore.makeUnsafe(1) |
| 382 | const pullInput = (seen: number) => |
| 383 | lock.withPermit(Effect.suspend(() => pulls === seen ? pullUpstream : Effect.void)) |
| 384 | |
| 385 | const run = <A, D>(f: () => A | undefined | typeof NeedInput, end: () => D): Pull.Pull<A, TarError | IE, D> => |
| 386 | Effect.suspend(function loop(): Pull.Pull<A, TarError | IE, D> { |
| 387 | const seen = pulls |
| 388 | let result: A | undefined | typeof NeedInput |
| 389 | try { |
| 390 | result = f() |
| 391 | } catch (error) { |
| 392 | return isTarError(error) ? Effect.fail(error) : Effect.die(error) |
| 393 | } |
| 394 | if (result === NeedInput) return Effect.flatMap(pullInput(seen), loop) |
| 395 | return result === undefined ? Cause.done(end()) : Effect.succeed(result) |
| 396 | }) |
| 397 | |
| 398 | const body = (id: number): Stream.Stream<Uint8Array, TarError | IE> => |
| 399 | Stream.fromPull(Effect.succeed(run(() => decoder.read(id), () => undefined))) |
| 400 | |
| 401 | const next = run(() => { |
| 402 | const header = decoder.next() |
| 403 | return header === NeedInput || header === undefined |
| 404 | ? header |
| 405 | : Arr.of({ header, body: body(decoder.generation) }) |
| 406 | }, () => done!.value) |
| 407 | |
| 408 | return Effect.as(Scope.addFinalizer(scope, Effect.sync(() => decoder.close())), next) |
| 409 | }) |
| 410 | ) |
no test coverage detected