Skip to content

Commit

Permalink
feat: add Schema.bytes (#300)
Browse files Browse the repository at this point in the history
  • Loading branch information
Gozala authored May 2, 2023
1 parent 400d8e9 commit 2bbdd1c
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
30 changes: 29 additions & 1 deletion packages/core/src/schema/schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -920,6 +920,28 @@ class AnyString extends UnknownString {
const anyString = new AnyString()
export const string = () => anyString

/**
* @template [I=unknown]
* @extends {API<Uint8Array, I, void>}
*/
class BytesSchema extends API {
/**
* @param {I} input
* @returns {Schema.ReadResult<Uint8Array>}
*/
readWith(input) {
if (input instanceof Uint8Array) {
return { ok: input }
} else {
return typeError({ expect: 'Uint8Array', actual: input })
}
}
}

/** @type {Schema.Schema<Uint8Array, unknown>} */
export const Bytes = new BytesSchema()
export const bytes = () => Bytes

/**
* @template {string} Prefix
* @template {string} Body
Expand Down Expand Up @@ -1380,7 +1402,13 @@ const displayTypeName = value => {
case 'undefined':
return String(value)
case 'object':
return value === null ? 'null' : Array.isArray(value) ? 'array' : 'object'
return value === null
? 'null'
: Array.isArray(value)
? 'array'
: Symbol.toStringTag in /** @type {object} */ (value)
? value[Symbol.toStringTag]
: 'object'
default:
return type
}
Expand Down
21 changes: 21 additions & 0 deletions packages/core/test/schema.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -657,3 +657,24 @@ test('record defaults', () => {
end: { x: 1, y: 3 },
})
})

test('bytes schema', () => {
const schema = Schema.bytes()
matchError(schema.read(undefined), /expect.* Uint8Array .* got undefined/is)

const bytes = new Uint8Array([1, 2, 3])

assert.equal(schema.read(bytes).ok, bytes, 'returns same bytes back')

matchError(
schema.read(bytes.buffer),
/expect.* Uint8Array .* got ArrayBuffer/is
)

matchError(
schema.read(new Int8Array(bytes.buffer)),
/expect.* Uint8Array .* got Int8Array/is
)

matchError(schema.read([...bytes]), /expect.* Uint8Array .* got array/is)
})

0 comments on commit 2bbdd1c

Please sign in to comment.