Skip to content

Commit

Permalink
perf: improve that of $.str (#167)
Browse files Browse the repository at this point in the history
  • Loading branch information
tjjfvi authored Jul 6, 2023
1 parent dd4297d commit ee7b8ea
Showing 1 changed file with 5 additions and 3 deletions.
8 changes: 5 additions & 3 deletions codecs/str.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@ import { u32 } from "./int.ts"

const compactU32 = compact(u32)

const textEncoder = new TextEncoder()
const textDecoder = new TextDecoder()
export const str: Codec<string> = createCodec({
_metadata: metadata("$.str"),
_staticSize: compactU32._staticSize,
_encode(buffer, value) {
const array = new TextEncoder().encode(value)
const array = textEncoder.encode(value)
compactU32._encode(buffer, array.length)
buffer.insertArray(array)
},
Expand All @@ -17,9 +19,9 @@ export const str: Codec<string> = createCodec({
if (buffer.array.length < buffer.index + len) {
throw new ScaleDecodeError(this, buffer, "Attempting to `str`-decode beyond bounds of input bytes")
}
const slice = buffer.array.slice(buffer.index, buffer.index + len)
const slice = buffer.array.subarray(buffer.index, buffer.index + len)
buffer.index += len
return new TextDecoder().decode(slice)
return textDecoder.decode(slice)
},
_assert(assert) {
assert.typeof(this, "string")
Expand Down

0 comments on commit ee7b8ea

Please sign in to comment.