Skip to content

Commit 363a714

Browse files
committed
refactor: separate latin1fromString in single-byte.node
1 parent 9bc8264 commit 363a714

1 file changed

Lines changed: 9 additions & 8 deletions

File tree

single-byte.node.js

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ export function createSinglebyteDecoder(encoding, loose = false) {
3939
return (arr) => {
4040
assertU8(arr)
4141
if (arr.byteLength === 0) return ''
42-
if (isLatin1 || isAscii(arr)) return toBuf(arr).latin1Slice() // .latin1Slice is faster than .asciiSlice
42+
if (isLatin1 || isAscii(arr)) return toBuf(arr).latin1Slice(0, arr.byteLength) // .latin1Slice is faster than .asciiSlice
4343

4444
// Node.js TextDecoder is broken, so we can't use it. It's also slow anyway
4545

@@ -87,19 +87,21 @@ function encode(s, m) {
8787
return new Uint8Array(x)
8888
}
8989

90+
export function latin1fromString(s) {
91+
if (typeof s !== 'string') throw new TypeError(E_STRING)
92+
if (NON_LATIN.test(s)) throw new TypeError(E_STRICT)
93+
const b = Buffer.from(s, 'latin1')
94+
return new Uint8Array(b.buffer, b.byteOffset, b.byteLength)
95+
}
96+
9097
export function createSinglebyteEncoder(encoding, { mode = 'fatal' } = {}) {
9198
// TODO: replacement, truncate (replacement will need varying length)
9299
if (mode !== 'fatal') throw new Error('Unsupported mode')
100+
if (encoding === 'iso-8859-1') return latin1fromString
93101
const m = encodeMap(encoding) // asserts
94-
const isLatin1 = encoding === 'iso-8859-1'
95102

96103
return (s) => {
97104
if (typeof s !== 'string') throw new TypeError(E_STRING)
98-
if (isLatin1) {
99-
if (NON_LATIN.test(s)) throw new TypeError(E_STRICT)
100-
const b = Buffer.from(s, 'latin1')
101-
return new Uint8Array(b.buffer, b.byteOffset, b.byteLength)
102-
}
103105

104106
// Instead of an ASCII regex check, encode optimistically - this is faster
105107
// Check for 8-bit string with a regex though, this is instant on 8-bit strings so doesn't hurt the ASCII fast path
@@ -115,6 +117,5 @@ export function createSinglebyteEncoder(encoding, { mode = 'fatal' } = {}) {
115117
}
116118

117119
export const latin1toString = /* @__PURE__ */ createSinglebyteDecoder('iso-8859-1')
118-
export const latin1fromString = /* @__PURE__ */ createSinglebyteEncoder('iso-8859-1')
119120
export const windows1252toString = /* @__PURE__ */ createSinglebyteDecoder('windows-1252')
120121
export const windows1252fromString = /* @__PURE__ */ createSinglebyteEncoder('windows-1252')

0 commit comments

Comments
 (0)