(value: string, encoding: string)
| 511 | } |
| 512 | |
| 513 | function stringToBuffer(value: string, encoding: string) { |
| 514 | encoding = encoding.toLowerCase() as Encoding |
| 515 | |
| 516 | if (encoding === 'utf8' || encoding === 'utf-8') { |
| 517 | return new BufferClass(encoder.encode(value)) |
| 518 | } |
| 519 | if (encoding === 'base64' || encoding === 'base64url') { |
| 520 | value = value.replace(/-/g, '+').replace(/_/g, '/') |
| 521 | value = value.replace(/[^A-Za-z0-9+/]/g, '') |
| 522 | |
| 523 | return new BufferClass([...atob(value)].map((v) => v.charCodeAt(0))) |
| 524 | } |
| 525 | if (encoding === 'binary' || encoding === 'ascii' || encoding === 'latin1' || encoding === 'latin-1') { |
| 526 | return new BufferClass([...value].map((v) => v.charCodeAt(0))) |
| 527 | } |
| 528 | if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { |
| 529 | const buffer = new BufferClass(value.length * 2) |
| 530 | const view = new DataView(buffer.buffer) |
| 531 | for (let i = 0; i < value.length; i++) { |
| 532 | view.setUint16(i * 2, value.charCodeAt(i), true) |
| 533 | } |
| 534 | return buffer |
| 535 | } |
| 536 | if (encoding === 'hex') { |
| 537 | const bytes = new BufferClass(value.length / 2) |
| 538 | for (let byteIndex = 0, i = 0; i < value.length; i += 2, byteIndex++) { |
| 539 | bytes[byteIndex] = parseInt(value.slice(i, i + 2), 16) |
| 540 | } |
| 541 | |
| 542 | return bytes |
| 543 | } |
| 544 | |
| 545 | bufferPolyfillDoesNotImplement(`encoding "${encoding}"`) |
| 546 | } |
| 547 | |
| 548 | function initReadMethods(prototype: BufferClass) { |
| 549 | const dataViewProtoProps = Object.getOwnPropertyNames(DataView.prototype) |
no test coverage detected