Skip to content

Commit

Permalink
refactor: improve byte length computation of str
Browse files Browse the repository at this point in the history
Smaller code produces smaller bundle and more efficient computation :)
  • Loading branch information
Conaclos committed Jan 9, 2022
1 parent 6fe63ac commit d556887
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 12 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@

* Smaller CommonJS bundle

* Improve byte-length computation of small string

## 0.1.0 (2022-01-02)

* `ByteCursor` abstraction to read and write safely a buffer of bytes
Expand Down
21 changes: 9 additions & 12 deletions src/codec/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,20 +131,17 @@ function encodeUtf8Js(bc: ByteCursor, s: string): void {

function utf8ByteLength(s: string): number {
const sLen = s.length
let result = 0
let i = 0
while (i < sLen) {
let result = sLen
for (let i = 0; i < sLen; i++) {
const codePoint = s.codePointAt(i) as number | 0 // i is a valid index
i++
if (codePoint < 128) {
if (codePoint >= 128) {
result++
} else if (codePoint < 0x800) {
result += 2
} else if (codePoint < 0x10_000) {
result += 3
} else {
result += 4
i++ // surrogate pair encoded as two ucs2 chars
if (codePoint >= 0x800) {
result++
if (codePoint >= 0x10_000) {
i++ // surrogate pair encoded as two ucs2 chars
}
}
}
}
return result
Expand Down

0 comments on commit d556887

Please sign in to comment.