Skip to content
This repository was archived by the owner on Apr 25, 2025. It is now read-only.

Add structProvable #276

Open
wants to merge 2 commits into
base: v1
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 81 additions & 0 deletions lib/generic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ export {
EmptyNull,
EmptyUndefined,
EmptyVoid,
StructProvable,
structProvable,
};

type GenericProvable<T, TValue, Field> = {
Expand All @@ -28,6 +30,85 @@ type GenericProvable<T, TValue, Field> = {
toValue: (x: T) => TValue;
fromValue: (x: T | TValue) => T;
};

type StructProvable<T extends {}, TValue extends {[K in keyof T]: any}, Field> = {
[K in keyof T]: GenericProvable<T[K], TValue[K], Field>;
}

function structProvable<T extends {}, TValue extends {[K in keyof T]: any}, Field>
(typ: StructProvable<T, TValue, Field>):
GenericProvable<
{[K in keyof T]: T[K]},
{[K in keyof T]: TValue[K]},
Field>
{
return {
toFields: (x) => {
var fields: Field[] = [];
var field: keyof T;
for (field in typ) {
fields.concat(typ[field].toFields(x[field]));
}
return fields;
},
toAuxiliary: (x? /* Why is this nullable?! */) => {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it's supposed to be called without argument, and return a default value, when we're in compilation mode

if (x == undefined) {
return [];
}
var auxes: any[] = [];
var field: keyof T;
for (field in typ) {
auxes.concat(typ[field].toAuxiliary(x[field]));
}
return auxes;
},
fromFields: (x: Field[], aux: any[]) => {
var res: {[K in keyof T]?: T[K]} = {};
var offset = 0;
var idx = 0;
var field: keyof T;
for (field in typ) {
let end = offset + typ[field].sizeInFields();
let field_aux = aux[idx];
res[field] = typ[field].fromFields(x.slice(offset, end), field_aux);
offset = end;
idx += 1;
}
return (res as {[K in keyof T]: T[K]});
},
sizeInFields: () => {
var sum = 0;
var field: keyof T;
for (field in typ) {
sum += typ[field].sizeInFields();
}
return sum;
},
check: (x) => {
var field: keyof T;
for (field in typ) {
typ[field].check(x[field]);
}
},
toValue: (x) => {
var res: {[K in keyof T]?: TValue[K]} = {};
var field: keyof T;
for (field in typ) {
res[field] = typ[field].toValue(x[field]);
}
return (res as {[K in keyof T]: TValue[K]});
},
fromValue: (x) => {
var res: {[K in keyof T]?: T[K]} = {};
var field: keyof T;
for (field in typ) {
res[field] = typ[field].fromValue(x[field]);
}
return (res as {[K in keyof T]: T[K]});
},
}
}

type GenericProvablePure<T, TValue, Field> = Omit<
GenericProvable<T, TValue, Field>,
'fromFields'
Expand Down
Loading