Skip to content

Commit

Permalink
fix: adjust codec exports to make TS defn's more correct
Browse files Browse the repository at this point in the history
Fixes: #116
  • Loading branch information
rvagg committed Sep 3, 2021
1 parent cfb9830 commit c3df816
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 22 deletions.
26 changes: 17 additions & 9 deletions src/codecs/json.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,26 @@
// @ts-check

/**
* @template {number} Code
* @template T
* @typedef {import('./interface').BlockCodec<Code, T>} BlockCodec
* @typedef {import('./interface').ByteView<T>} ByteView
*/

const textEncoder = new TextEncoder()
const textDecoder = new TextDecoder()

export const name = 'json'
export const code = 0x0200

/**
* @template T
* @param {T} node
* @returns {ByteView<T>}
*/
export const encode = (node) => textEncoder.encode(JSON.stringify(node))

/**
* @template T
* @type {BlockCodec<0x0200, T>}
* @param {ByteView<T>} data
* @returns {T}
*/
export const { name, code, encode, decode } = {
name: 'json',
code: 0x0200,
encode: json => new TextEncoder().encode(JSON.stringify(json)),
decode: bytes => JSON.parse(new TextDecoder().decode(bytes))
}
export const decode = (data) => JSON.parse(textDecoder.decode(data))
23 changes: 10 additions & 13 deletions src/codecs/raw.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,21 @@
import { coerce } from '../bytes.js'

/**
* @template {number} Code
* @template T
* @typedef {import('./interface').BlockCodec<Code, T>} BlockCodec
* @typedef {import('./interface').ByteView<T>} ByteView
*/

export const name = 'raw'
export const code = 0x55

/**
* @param {Uint8Array} bytes
* @returns {Uint8Array}
* @param {Uint8Array} node
* @returns {ByteView<Uint8Array>}
*/
const raw = (bytes) => coerce(bytes)
export const encode = (node) => coerce(node)

/**
* @template T
* @type {BlockCodec<0x55, Uint8Array>}
* @param {ByteView<Uint8Array>} data
* @returns {Uint8Array}
*/
export const { name, code, encode, decode } = {
name: 'raw',
code: 0x55,
decode: raw,
encode: raw
}
export const decode = (data) => coerce(data)

0 comments on commit c3df816

Please sign in to comment.