MCPcopy
hub / github.com/feross/buffer / byteLength

Function byteLength

index.js:432–478  ·  view source on GitHub ↗
(string, encoding)

Source from the content-addressed store, hash-verified

430}
431
432function byteLength (string, encoding) {
433 if (Buffer.isBuffer(string)) {
434 return string.length
435 }
436 if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
437 return string.byteLength
438 }
439 if (typeof string !== 'string') {
440 throw new TypeError(
441 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
442 'Received type ' + typeof string
443 )
444 }
445
446 const len = string.length
447 const mustMatch = (arguments.length > 2 && arguments[2] === true)
448 if (!mustMatch && len === 0) return 0
449
450 // Use a for loop to avoid recursion
451 let loweredCase = false
452 for (;;) {
453 switch (encoding) {
454 case 'ascii':
455 case 'latin1':
456 case 'binary':
457 return len
458 case 'utf8':
459 case 'utf-8':
460 return utf8ToBytes(string).length
461 case 'ucs2':
462 case 'ucs-2':
463 case 'utf16le':
464 case 'utf-16le':
465 return len * 2
466 case 'hex':
467 return len >>> 1
468 case 'base64':
469 return base64ToBytes(string).length
470 default:
471 if (loweredCase) {
472 return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
473 }
474 encoding = ('' + encoding).toLowerCase()
475 loweredCase = true
476 }
477 }
478}
479Buffer.byteLength = byteLength
480
481function slowToString (encoding, start, end) {

Callers 1

fromStringFunction · 0.85

Calls 3

isInstanceFunction · 0.85
utf8ToBytesFunction · 0.85
base64ToBytesFunction · 0.85

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…