Skip to content

Commit 4619f05

Browse files
committed
feat: add $Uint8ArrayLike
1 parent b1cf915 commit 4619f05

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

src/__tests__/zod.test.ts

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import * as module from 'node:module';
33
import { describe, expect, it } from 'vitest';
44
import { z } from 'zod';
55

6-
import { $BooleanLike, $NumberLike, $UrlLike, isZodType } from '../zod.js';
6+
import { $BooleanLike, $NumberLike, $Uint8ArrayLike, $UrlLike, isZodType } from '../zod.js';
77

88
const require = module.createRequire(import.meta.url);
99

@@ -84,3 +84,35 @@ describe('$UrlLike', () => {
8484
expect(result.data).toBeInstanceOf(URL);
8585
});
8686
});
87+
88+
describe('$Uint8ArrayLike', () => {
89+
it('should pass when given a Uint8Array', () => {
90+
const input = new Uint8Array([1, 2, 3]);
91+
const result = $Uint8ArrayLike.parse(input);
92+
expect(result).toBeInstanceOf(Uint8Array);
93+
expect([...result]).toEqual([1, 2, 3]);
94+
});
95+
96+
it('should convert an array to Uint8Array', () => {
97+
const input = [4, 5, 6];
98+
const result = $Uint8ArrayLike.parse(input);
99+
expect(result).toBeInstanceOf(Uint8Array);
100+
expect([...result]).toEqual([4, 5, 6]);
101+
});
102+
103+
it('should fail to convert an invalid array', () => {
104+
expect($Uint8ArrayLike.safeParse([-1, 2, 3]).success).toBe(false);
105+
expect($Uint8ArrayLike.safeParse([1, 2, 256]).success).toBe(false);
106+
expect($Uint8ArrayLike.safeParse([1, 2, NaN]).success).toBe(false);
107+
});
108+
109+
it('should convert an ArrayBuffer to Uint8Array', () => {
110+
const buffer = new ArrayBuffer(3);
111+
const view = new Uint8Array(buffer);
112+
view.set([7, 8, 9]);
113+
const result = $Uint8ArrayLike.safeParse(buffer);
114+
expect(result.success).toBe(true);
115+
expect(result.data).toBeInstanceOf(Uint8Array);
116+
expect([...result.data!]).toEqual([7, 8, 9]);
117+
});
118+
});

src/zod.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,3 +42,12 @@ export const $UrlLike: z.ZodType<URL, z.ZodTypeDef, any> = z.preprocess(
4242
.url()
4343
.transform((arg) => new URL(arg))
4444
);
45+
46+
export const $Uint8ArrayLike: z.ZodType<Uint8Array, z.ZodTypeDef, any> = z
47+
.union([z.array(z.number().int().min(0).max(255)), z.instanceof(Uint8Array), z.instanceof(ArrayBuffer)])
48+
.transform((arg) => {
49+
if (!(arg instanceof Uint8Array)) {
50+
return new Uint8Array(arg);
51+
}
52+
return arg;
53+
});

0 commit comments

Comments
 (0)