mirror of
https://github.com/denoland/deno.git
synced 2025-09-27 20:59:10 +00:00
fix(std/node): add encoding argument to Buffer.byteLength (#6639)
This commit is contained in:
parent
91767501e1
commit
43db7aa05d
2 changed files with 91 additions and 3 deletions
|
@ -28,6 +28,46 @@ function checkEncoding(encoding = "utf8", strict = true): string {
|
|||
return normalized;
|
||||
}
|
||||
|
||||
interface EncodingOp {
|
||||
byteLength(string: string): number;
|
||||
}
|
||||
|
||||
// https://github.com/nodejs/node/blob/56dbe466fdbc598baea3bfce289bf52b97b8b8f7/lib/buffer.js#L598
|
||||
const encodingOps: { [key: string]: EncodingOp } = {
|
||||
utf8: {
|
||||
byteLength: (string: string): number =>
|
||||
new TextEncoder().encode(string).byteLength,
|
||||
},
|
||||
ucs2: {
|
||||
byteLength: (string: string): number => string.length * 2,
|
||||
},
|
||||
utf16le: {
|
||||
byteLength: (string: string): number => string.length * 2,
|
||||
},
|
||||
latin1: {
|
||||
byteLength: (string: string): number => string.length,
|
||||
},
|
||||
ascii: {
|
||||
byteLength: (string: string): number => string.length,
|
||||
},
|
||||
base64: {
|
||||
byteLength: (string: string): number =>
|
||||
base64ByteLength(string, string.length),
|
||||
},
|
||||
hex: {
|
||||
byteLength: (string: string): number => string.length >>> 1,
|
||||
},
|
||||
};
|
||||
|
||||
function base64ByteLength(str: string, bytes: number): number {
|
||||
// Handle padding
|
||||
if (str.charCodeAt(bytes - 1) === 0x3d) bytes--;
|
||||
if (bytes > 1 && str.charCodeAt(bytes - 1) === 0x3d) bytes--;
|
||||
|
||||
// Base64 ratio: 3/4
|
||||
return (bytes * 3) >>> 2;
|
||||
}
|
||||
|
||||
/**
|
||||
* See also https://nodejs.org/api/buffer.html
|
||||
*/
|
||||
|
@ -95,10 +135,13 @@ export default class Buffer extends Uint8Array {
|
|||
* used to convert the string into bytes.
|
||||
*/
|
||||
static byteLength(
|
||||
string: string | Buffer | ArrayBufferView | ArrayBuffer | SharedArrayBuffer
|
||||
string: string | Buffer | ArrayBufferView | ArrayBuffer | SharedArrayBuffer,
|
||||
encoding = "utf8"
|
||||
): number {
|
||||
if (typeof string != "string") return string.byteLength;
|
||||
return new TextEncoder().encode(string).length;
|
||||
|
||||
encoding = normalizeEncoding(encoding) || "utf8";
|
||||
return encodingOps[encoding].byteLength(string);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue