Created
August 12, 2024 13:46
-
-
Save schickling/9f002b2cb4d526fe0ea3d3374e164f70 to your computer and use it in GitHub Desktop.
Effect schema Uint8ArrayList
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Schema } from '@effect/schema' | |
/** | |
* The encoded structure is alternating 4 bytes to represent the length of the following Uint8Array, | |
* followed by the Uint8Array itself, repeated. | |
*/ | |
export const Uint8ArrayList = Schema.transform(Schema.Uint8ArrayFromSelf, Schema.Array(Schema.Uint8ArrayFromSelf), { | |
decode: (encodedArrayList) => { | |
const arrayList: Uint8Array[] = [] | |
const dataView = new DataView(encodedArrayList.buffer) | |
let offset = 0 | |
while (offset < dataView.byteLength) { | |
const length = dataView.getUint32(offset) | |
const array = new Uint8Array(dataView.buffer, offset + 4, length) | |
arrayList.push(array) | |
offset += 4 + length | |
} | |
return arrayList | |
}, | |
encode: (arrayList) => { | |
const numberOfTotalBytes = arrayList.reduce((acc, array) => acc + array.byteLength, 0) | |
const encodedArrayList = new Uint8Array(numberOfTotalBytes) | |
let offset = 0 | |
for (const array of arrayList) { | |
encodedArrayList.set(array, offset) | |
offset += array.byteLength | |
} | |
return encodedArrayList | |
}, | |
strict: true, | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment