Created
August 29, 2024 23:25
-
-
Save bigmistqke/8781d79e418b757d2dccb21e9f8ade34 to your computer and use it in GitHub Desktop.
struct utility
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
const s = { | |
int64: <T extends string>(key: T) => [key, 8] as const, | |
uint64: <T extends string>(key: T) => [key, 8] as const, | |
float32: <T extends string>(key: T) => [key, 4] as const, | |
float64: <T extends string>(key: T) => [key, 8] as const, | |
int8: <T extends string>(key: T) => [key, 1] as const, | |
int16: <T extends string>(key: T) => [key, 2] as const, | |
int32: <T extends string>(key: T) => [key, 4] as const, | |
uint8: <T extends string>(key: T) => [key, 1] as const, | |
uint8clamped: <T extends string>(key: T) => [key, 1] as const, | |
uint16: <T extends string>(key: T) => [key, 2] as const, | |
uint32: <T extends string>(key: T) => [key, 4] as const, | |
} as const; | |
type Offsets = ReturnType<(typeof s)[keyof typeof s]>; | |
type Unique<T extends Offsets[]> = T extends [infer F, ...infer R] | |
? F extends Offsets | |
? R extends Offsets[] | |
? F[0] extends R[number][0] | |
? [never, ...Unique<R>] | |
: [F, ...Unique<R>] | |
: never | |
: never | |
: T; | |
function struct<T extends Offsets[]>(...scheme: Unique<T>) { | |
let offset = 0; | |
return Object.fromEntries( | |
scheme.map(([key, value]) => { | |
offset += value; | |
return [key, offset]; | |
}), | |
) as Record<T[number][0], number>; | |
} | |
// Usage | |
const cons = struct(s.int32("cdr"), s.int32("car")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment