Skip to content

Commit

Permalink
fix: use Buffer.from for stringification where available (#36)
Browse files Browse the repository at this point in the history
Before:

```
Uint8Arrays.fromString x 1,203,638 ops/sec ±1.53% (85 runs sampled)
Uint8Arrays.toString x 376,183 ops/sec ±2.20% (74 runs sampled)
```

After:

```
Uint8Arrays.fromString x 2,051,032 ops/sec ±0.54% (88 runs sampled)
Uint8Arrays.toString x 2,912,464 ops/sec ±0.38% (91 runs sampled)
```
  • Loading branch information
achingbrain authored Aug 2, 2022
1 parent cf6242d commit 0a18849
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/from-string.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ export function fromString (string, encoding = 'utf8') {
throw new Error(`Unsupported encoding "${encoding}"`)
}

if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) {
return globalThis.Buffer.from(string, 'utf8')
}

// add multibase prefix
return base.decoder.decode(`${base.prefix}${string}`)
}
4 changes: 4 additions & 0 deletions src/to-string.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ export function toString (array, encoding = 'utf8') {
throw new Error(`Unsupported encoding "${encoding}"`)
}

if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) {
return globalThis.Buffer.from(array.buffer, array.byteOffset, array.byteLength).toString('utf8')
}

// strip multibase prefix
return base.encoder.encode(array).substring(1)
}

0 comments on commit 0a18849

Please sign in to comment.