@jsonjoy.com/json-type
Version:
High-performance JSON Pointer implementation
70 lines • 2.29 kB
JavaScript
;
/**
* High-performance string format validation utilities.
* These functions are optimized for maximum performance.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateStringFormat = exports.isUtf8 = exports.isAscii = void 0;
/**
* Validates if a string contains only ASCII characters (0-127).
* This is highly optimized for performance.
*/
const isAscii = (str) => {
const length = str.length;
for (let i = 0; i < length; i++) {
if (str.charCodeAt(i) > 127) {
return false;
}
}
return true;
};
exports.isAscii = isAscii;
/**
* Validates if a string represents valid UTF-8 when encoded.
* JavaScript strings are UTF-16, but we need to validate they don't contain
* invalid Unicode sequences that would produce invalid UTF-8.
*
* This checks for:
* - Unpaired surrogates (invalid UTF-16 sequences)
* - Characters that would produce invalid UTF-8
*/
const isUtf8 = (str) => {
const length = str.length;
for (let i = 0; i < length; i++) {
const code = str.charCodeAt(i);
// Check for high surrogate
if (code >= 0xd800 && code <= 0xdbff) {
// High surrogate must be followed by low surrogate
if (i + 1 >= length) {
return false; // Unpaired high surrogate at end
}
const nextCode = str.charCodeAt(i + 1);
if (nextCode < 0xdc00 || nextCode > 0xdfff) {
return false; // High surrogate not followed by low surrogate
}
i++; // Skip the low surrogate
}
else if (code >= 0xdc00 && code <= 0xdfff) {
// Low surrogate without preceding high surrogate
return false;
}
// All other characters (0x0000-0xD7FF and 0xE000-0xFFFF) are valid
}
return true;
};
exports.isUtf8 = isUtf8;
/**
* Validates a string according to the specified format.
*/
const validateStringFormat = (str, format) => {
switch (format) {
case 'ascii':
return (0, exports.isAscii)(str);
case 'utf8':
return (0, exports.isUtf8)(str);
default:
return true;
}
};
exports.validateStringFormat = validateStringFormat;
//# sourceMappingURL=stringFormats.js.map