Skip to content

Conversation

@SystemVll
Copy link

@SystemVll SystemVll commented Jan 30, 2025

Add binary encoding support to Parser

Overview

This PR adds the ability to encode JavaScript objects back into binary buffers according to the parser's specification, complementing the existing parsing functionality.

Features

  • New

encode()

method that converts objects to binary buffers based on parser configuration

  • Support for encoding:
    • Primitive types (int8/16/32/64, uint8/16/32/64, float32/64)
    • Bit fields
    • Strings (fixed-length, zero-terminated)
    • Arrays of primitives and complex types
    • Nested structures
  • Size calculation to pre-allocate exact buffer size
  • Type checking and validation of input values
  • Endianness handling for multi-byte values

Example Usage

const parser = new Parser()
  .int8('age')
  .string('name', { zeroTerminated: true });

const buffer = parser.encode({
  age: 25,
  name: 'John'
}); 

// Results in: <Buffer 19 4a 6f 68 6e 00>

Implementation Details

  • Added

encode()

public method that orchestrates the encoding process

  • Added

calculateSize()

private method to determine required buffer size

  • Added

encodeValue()

private method that handles the actual encoding logic

  • Uses DataView for consistent endianness handling
  • Validates input values against type constraints
  • Maintains consistency with existing parsing behavior

Testing

  • Added comprehensive test suite covering all supported types
  • Tests both simple and complex nested structures
  • Tests edge cases and error conditions
  • Validates round-trip encoding/parsing

Documentation

  • Added JSDoc comments explaining usage
  • Updated README with encoding examples
  • Added error descriptions

Breaking Changes

None. This is a purely additive feature that maintains backwards compatibility.

@SystemVll SystemVll closed this Feb 9, 2025
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 this pull request may close these issues.

1 participant