Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom Serialize/Deserialize #19

Closed
mehtaphysical opened this issue May 18, 2021 · 0 comments · Fixed by #20
Closed

Custom Serialize/Deserialize #19

mehtaphysical opened this issue May 18, 2021 · 0 comments · Fixed by #20

Comments

@mehtaphysical
Copy link
Contributor

What do you think about allowing classes to provide custom serialize/deserialize methods?

By adding something like this to serializeStruct

function serializeStruct(schema: Schema, obj: any, writer: any) {
  if (typeof obj.borshSerialize === 'function') {
    obj.borshSerialize(writer);
    return;
  }
.....
}
.....

function deserializeStruct(
  schema: Schema,
  classType: any,
  reader: BinaryReader
) {
  if(typeof classType.borshDeserialize) {
    classType.borshDeserialize(reader);
    return;
  }
....
}

we could then do this:

export class PublicKey {
    keyType: KeyType;
    data: Uint8Array;

    static borsheDeserialize(reader: BinaryReader) {
        reader.readU8
    }

    static borshDeserialize(reader: BinaryReader): PublicKey {
        const keyType = reader.readU8();

        let data;
        if(keyType === KeyType.ED25519) {
            data = reader.readFixedArray(32);
        } else if(keyType === KeyType.SECP256k1) {
            data = reader.readFixedArray(64);
        }

        return new PublicKey({ keyType, data });
    }

    borshSerialize(writer: BinaryWriter) {
        writer.writeU8(this.keyType);
        writer.writeFixedArray(this.data);
    }
}

If this looks good I'm happy to implement it and submit a PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant