Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions src/bytes/bytes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,12 +154,19 @@ export class Bytes {
}

/**
* Decodes the bytes as UTF-8 JSON.
* Parses the bytes as UTF-8 JSON.
*/
public toJSON(): unknown {
public parseJson(): unknown {
return JSON.parse(this.toUtf8())
}

/**
* Serialized as its hex string by `JSON.stringify`.
*/
public toJSON(): string {
return this.toHex()
}

/**
* Byte-wise equality against another Bytes instance, raw bytes, or hex string.
*/
Expand All @@ -173,4 +180,11 @@ export class Bytes {
public represent(): string {
return this.toHex()
}

/**
* Printed as its hex string by `console.log` and `util.inspect` in Node.
*/
public [Symbol.for('nodejs.util.inspect.custom')](): string {
return this.represent()
}
}
18 changes: 17 additions & 1 deletion test/typed-bytes.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { inspect } from 'node:util'
import { describe, expect, it } from 'vitest'
import { keccak256 } from '../src/crypto/keccak.js'
import { BatchId } from '../src/bytes/batch-id.js'
Expand Down Expand Up @@ -63,7 +64,22 @@ describe('Bytes', () => {

it('parses JSON from its UTF-8 content', () => {
const bytes = Bytes.fromUtf8(JSON.stringify({ a: 1 }))
expect(bytes.toJSON()).toEqual({ a: 1 })
expect(bytes.parseJson()).toEqual({ a: 1 })
})

it('stringifies to hex, standalone and as a property', () => {
const id = new BatchId('ab'.repeat(32))
expect(id.toJSON()).toBe('ab'.repeat(32))
expect(JSON.stringify(id)).toBe(`"${'ab'.repeat(32)}"`)
expect(JSON.stringify({ id })).toBe(`{"id":"${'ab'.repeat(32)}"}`)
expect(`${id}`).toBe('ab'.repeat(32))
})

it('inspects as hex, standalone and nested', () => {
const id = new BatchId('ab'.repeat(32))
expect(inspect(id)).toBe('ab'.repeat(32))
expect(inspect({ id }, { breakLength: Infinity })).toBe(`{ id: ${'ab'.repeat(32)} }`)
expect(inspect([new Span('0102030405060708')])).toBe('[ 0102030405060708 ]')
})

it('static keccak256 matches the direct function', () => {
Expand Down
Loading