Skip to content

Commit

Permalink
feat: simple codec support float32
Browse files Browse the repository at this point in the history
  • Loading branch information
seven332 committed Dec 17, 2023
1 parent 0291c6d commit a9735e8
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 0 deletions.
6 changes: 6 additions & 0 deletions packages/util/src/dynamic-buffer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,12 @@ export class DynamicBuffer {
this.size_ += 4
}

public writeFloat32(value: number) {
this.ensureAppend(4)
new DataView(this.data_.buffer).setFloat32(this.size_, value, true)
this.size_ += 4
}

public writeString(value: string) {
const data = new TextEncoder().encode(value)

Expand Down
4 changes: 4 additions & 0 deletions packages/util/src/float.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export class Float {
public static kZero = new Float(0)
public constructor(public readonly value: number) {}
}
5 changes: 5 additions & 0 deletions packages/util/src/simple-codec.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Float } from './float'
import { encode, decode } from './simple-codec'

interface TestObject {
Expand Down Expand Up @@ -35,6 +36,10 @@ describe('SimpleBuffer', () => {
expect(decode<number>(encode(2147483647), 0)).toBe(2147483647)
})

it('float32', () => {
expect(decode<Float>(encode(new Float(1.25)), Float.kZero)).toStrictEqual(new Float(1.25))
})

it('string', () => {
expect(decode<string>(encode('hello🌎𠮷'), '')).toBe('hello🌎𠮷')
})
Expand Down
5 changes: 5 additions & 0 deletions packages/util/src/simple-codec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { DynamicBuffer } from './dynamic-buffer'
import { Float } from './float'

export function encode(value: unknown): Uint8Array {
const buffer = new DynamicBuffer()
Expand All @@ -18,6 +19,8 @@ function encodeToBuffer(buffer: DynamicBuffer, value: unknown) {
for (const element of value) {
encodeToBuffer(buffer, element)
}
} else if (value instanceof Float) {
buffer.writeFloat32(value.value)
} else if (typeof value == 'object' && value != null) {
for (const element of Object.values(value)) {
encodeToBuffer(buffer, element)
Expand Down Expand Up @@ -69,6 +72,8 @@ function decodeFromBuffer<T>(buffer: DataView, offset: number, dummy: T): [T, nu
}

return [result as T, read]
} else if (dummy instanceof Float) {
return [new Float(buffer.getFloat32(offset, true)) as T, 4]
} else if (typeof dummy == 'object' && dummy != null) {
const result = {}
let read = 0
Expand Down

0 comments on commit a9735e8

Please sign in to comment.