near / borsh-js

TypeScript/JavaScript implementation of Binary Object Representation Serializer for Hashing
Apache License 2.0
112 stars 38 forks source link

use custom Writer/Reader #30

Closed exromany closed 3 years ago

exromany commented 3 years ago

Allow specify custom Writer/Reader, like this:

class ExtendedWriter extends borsh.BinaryWriter {
    writeDate(value) {
        this.writeU64(value.getTime());
    }
}
class ExtendedReader extends borsh.BinaryReader {
    readDate() {
        const value = this.readU64();
        return new Date(value.toNumber());
    }
}

const value = new Test({ x: new Date('Aug 12, 2021 12:00:00 UTC+00:00') });
const schema = new Map([[Test, {kind: 'struct', fields: [['x', 'date']]}]]);

const buf = borsh.serialize(schema, value, ExtendedWriter);
const newValue = borsh.deserialize(schema, Test, buf, ExtendedReader);
newValue instanceof Date // true
exromany commented 3 years ago

@volovyk-s can you see at this PR?

exromany commented 3 years ago

@volovyk-s done