-
Notifications
You must be signed in to change notification settings - Fork 4
/
iterable.ts
63 lines (61 loc) · 1.85 KB
/
iterable.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import {
AssertState,
Codec,
createCodec,
metadata,
ScaleAssertError,
ScaleDecodeError,
ScaleEncodeError,
} from "../common/mod.ts"
import { compact } from "./compact.ts"
import { u32 } from "./int.ts"
const compactU32 = compact(u32)
export function iterable<TI, I extends Iterable<TI>, TO = TI, O = I>(
props: {
$el: Codec<TI, TO>
calcLength: (iterable: I) => number
rehydrate: (iterable: Iterable<TO>) => O
assert: (this: Codec<I, O>, assert: AssertState) => void
},
): Codec<I, O> {
return createCodec({
_metadata: metadata("$.iterable", iterable, props),
_staticSize: compactU32._staticSize,
_encode(buffer, value) {
const length = props.calcLength(value)
compactU32._encode(buffer, length)
buffer.pushAlloc(length * props.$el._staticSize)
let i = 0
for (const el of value) {
props.$el._encode(buffer, el)
i++
}
if (i !== length) throw new ScaleEncodeError(this, value, "Incorrect length returned by calcLength")
buffer.popAlloc()
},
_decode(buffer) {
const length = compactU32._decode(buffer)
let done = false
const value = props.rehydrate(function*() {
for (let i = 0; i < length; i++) {
yield props.$el._decode(buffer)
}
done = true
}())
if (!done) throw new ScaleDecodeError(this, buffer, "Iterable passed to rehydrate must be immediately exhausted")
return value
},
_assert(assert) {
props.assert.call(this, assert)
const length = props.calcLength(assert.value as I)
let i = 0
for (const el of assert.value as I) {
props.$el._assert(new AssertState(el, `#iterator[${i}]`))
i++
}
if (i !== length) {
throw new ScaleAssertError(this, assert.value, `${assert.path}: Incorrect length returned by calcLength`)
}
},
})
}