(writer: Writer, coders: ReadonlyArray<Coder>, values: Array<any> | { [ name: string ]: any })
| 13 | * @_ignore |
| 14 | */ |
| 15 | export function pack(writer: Writer, coders: ReadonlyArray<Coder>, values: Array<any> | { [ name: string ]: any }): number { |
| 16 | let arrayValues: Array<any> = [ ]; |
| 17 | |
| 18 | if (Array.isArray(values)) { |
| 19 | arrayValues = values; |
| 20 | |
| 21 | } else if (values && typeof(values) === "object") { |
| 22 | let unique: { [ name: string ]: boolean } = { }; |
| 23 | |
| 24 | arrayValues = coders.map((coder) => { |
| 25 | const name = coder.localName; |
| 26 | assert(name, "cannot encode object for signature with missing names", |
| 27 | "INVALID_ARGUMENT", { argument: "values", info: { coder }, value: values }); |
| 28 | |
| 29 | assert(!unique[name], "cannot encode object for signature with duplicate names", |
| 30 | "INVALID_ARGUMENT", { argument: "values", info: { coder }, value: values }); |
| 31 | |
| 32 | unique[name] = true; |
| 33 | |
| 34 | return values[name]; |
| 35 | }); |
| 36 | |
| 37 | } else { |
| 38 | assertArgument(false, "invalid tuple value", "tuple", values); |
| 39 | } |
| 40 | |
| 41 | assertArgument(coders.length === arrayValues.length, "types/value length mismatch", "tuple", values); |
| 42 | |
| 43 | let staticWriter = new Writer(); |
| 44 | let dynamicWriter = new Writer(); |
| 45 | |
| 46 | let updateFuncs: Array<(baseOffset: number) => void> = []; |
| 47 | coders.forEach((coder, index) => { |
| 48 | let value = arrayValues[index]; |
| 49 | |
| 50 | if (coder.dynamic) { |
| 51 | // Get current dynamic offset (for the future pointer) |
| 52 | let dynamicOffset = dynamicWriter.length; |
| 53 | |
| 54 | // Encode the dynamic value into the dynamicWriter |
| 55 | coder.encode(dynamicWriter, value); |
| 56 | |
| 57 | // Prepare to populate the correct offset once we are done |
| 58 | let updateFunc = staticWriter.writeUpdatableValue(); |
| 59 | updateFuncs.push((baseOffset: number) => { |
| 60 | updateFunc(baseOffset + dynamicOffset); |
| 61 | }); |
| 62 | |
| 63 | } else { |
| 64 | coder.encode(staticWriter, value); |
| 65 | } |
| 66 | }); |
| 67 | |
| 68 | // Backfill all the dynamic offsets, now that we know the static length |
| 69 | updateFuncs.forEach((func) => { func(staticWriter.length); }); |
| 70 | |
| 71 | let length = writer.appendWriter(staticWriter); |
| 72 | length += writer.appendWriter(dynamicWriter); |
no test coverage detected
searching dependent graphs…