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

needed web-friendly CBOR library #2

Open
4 tasks
coolaj86 opened this issue Aug 27, 2024 · 1 comment
Open
4 tasks

needed web-friendly CBOR library #2

coolaj86 opened this issue Aug 27, 2024 · 1 comment

Comments

@coolaj86
Copy link
Member

coolaj86 commented Aug 27, 2024

  • find some decent JSON to CBOR unit test fixtures (JSON input, expected hex output)
  • find JSON to CBOR unit test fixtures from another lib or language for good measure
  • try the GPT code
  • double check any bitshifting if unit tests fail

It looks like this could be switched to using TypedArrays and DataView fairly easily:

https://github.com/ellipticoin/js-cbor/blob/master/main.js

This is what we're using as a holdover:

@coolaj86
Copy link
Member Author

coolaj86 commented Aug 27, 2024

I let GPT have a whack at it - since there are HUNDREDS of implementations. Doesn't seem bad. It is missing the canonical sorting.

const CBOR = {
  encode(value) {
    const encoder = new CBOR.Encoder();
    return encoder.encode(value);
  },

  bytesToHex(bytes) {
    return Array.from(bytes)
      .map(byte => byte.toString(16).padStart(2, '0'))
      .join('');
  },

  Encoder: class {
    constructor() {
      this.buffer = [];
    }

    encode(value) {
      this._encodeValue(value);
      return new Uint8Array(this.buffer);
    }

    _encodeValue(value) {
      if (value === null) {
        this._encodeNull();
      } else if (typeof value === 'boolean') {
        this._encodeBoolean(value);
      } else if (typeof value === 'number') {
        this._encodeNumber(value);
      } else if (typeof value === 'string') {
        this._encodeString(value);
      } else if (Array.isArray(value)) {
        this._encodeArray(value);
      } else if (typeof value === 'object') {
        this._encodeObject(value);
      } else {
        throw new Error('Unsupported type');
      }
    }

    _encodeNull() {
      this.buffer.push(0xf6);
    }

    _encodeBoolean(value) {
      this.buffer.push(value ? 0xf5 : 0xf4);
    }

    _encodeNumber(value) {
      if (Number.isInteger(value)) {
        if (value >= 0) {
          this._encodePositiveInteger(value);
        } else {
          this._encodeNegativeInteger(value);
        }
      } else {
        this._encodeFloat(value);
      }
    }

    _encodePositiveInteger(value) {
      if (value < 24) {
        this.buffer.push(value);
      } else if (value < 256) {
        this.buffer.push(0x18, value);
      } else if (value < 65536) {
        this.buffer.push(0x19, value >> 8, value & 0xff);
      } else if (value < 4294967296) {
        this.buffer.push(
          0x1a,
          (value >> 24) & 0xff,
          (value >> 16) & 0xff,
          (value >> 8) & 0xff,
          value & 0xff
        );
      } else {
        this.buffer.push(0x1b);
        for (let i = 7; i >= 0; i--) {
          this.buffer.push((value >> (8 * i)) & 0xff);
        }
      }
    }

    _encodeNegativeInteger(value) {
      this._encodePositiveInteger(-1 - value);
      this.buffer[this.buffer.length - 1] |= 0x20;
    }

    _encodeFloat(value) {
      const buffer = new ArrayBuffer(8);
      new DataView(buffer).setFloat64(0, value);
      this.buffer.push(0xfb, ...new Uint8Array(buffer));
    }

    _encodeString(value) {
      const utf8 = new TextEncoder().encode(value);
      this._encodePositiveInteger(utf8.length);
      this.buffer[this.buffer.length - 1] |= 0x60;
      this.buffer.push(...utf8);
    }

    _encodeArray(value) {
      this._encodePositiveInteger(value.length);
      this.buffer[this.buffer.length - 1] |= 0x80;
      value.forEach(item => this._encodeValue(item));
    }

    _encodeObject(value) {
      const keys = Object.keys(value);
      this._encodePositiveInteger(keys.length);
      this.buffer[this.buffer.length - 1] |= 0xa0;
      keys.forEach(key => {
        this._encodeString(key);
        this._encodeValue(value[key]);
      });
    }
  }
};

// Example usage:
let plainObject = { name: "Alice", age: 30, isAdmin: false, scores: [85, 92, 78] };
let bytes = CBOR.encode(plainObject);
let hex = CBOR.bytesToHex(bytes);
console.log(hex); // Outputs the CBOR-encoded hexadecimal string

If it's correct, it would just need the class state refactored out.

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

No branches or pull requests

1 participant