Skip to content

Commit

Permalink
Add fast paths that skip UTF8 encoding
Browse files Browse the repository at this point in the history
  • Loading branch information
gaearon committed Dec 10, 2024
1 parent 6488907 commit d7cc7d2
Showing 1 changed file with 42 additions and 17 deletions.
59 changes: 42 additions & 17 deletions packages/lexicon/src/validators/primitives.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,27 +198,52 @@ export function string(
}

// maxLength and minLength
if (typeof def.maxLength === 'number' || typeof def.minLength === 'number') {
const len = utf8Len(value)
if (typeof def.minLength === 'number' || typeof def.maxLength === 'number') {
// If the JavaScript string length * 3 is below the maximum limit,
// its UTF8 length (which <= .length * 3) will also be below.
if (typeof def.minLength === 'number' && value.length * 3 < def.minLength) {
return {
success: false,
error: new ValidationError(
`${path} must not be shorter than ${def.minLength} characters`,
),
}
}

if (typeof def.maxLength === 'number') {
if (len > def.maxLength) {
return {
success: false,
error: new ValidationError(
`${path} must not be longer than ${def.maxLength} characters`,
),
// If the JavaScript string length * 3 is within the maximum limit,
// its UTF8 length (which <= .length * 3) will also be within.
// When there's no minimal length, this lets us skip the UTF8 length check.
let canSkipUtf8LenChecks = false
if (
typeof def.minLength === 'undefined' &&
typeof def.maxLength === 'number' &&
value.length * 3 <= def.maxLength
) {
canSkipUtf8LenChecks = true
}

if (!canSkipUtf8LenChecks) {
const len = utf8Len(value)

if (typeof def.maxLength === 'number') {
if (len > def.maxLength) {
return {
success: false,
error: new ValidationError(
`${path} must not be longer than ${def.maxLength} characters`,
),
}
}
}
}

if (typeof def.minLength === 'number') {
if (len < def.minLength) {
return {
success: false,
error: new ValidationError(
`${path} must not be shorter than ${def.minLength} characters`,
),
if (typeof def.minLength === 'number') {
if (len < def.minLength) {
return {
success: false,
error: new ValidationError(
`${path} must not be shorter than ${def.minLength} characters`,
),
}
}
}
}
Expand Down

0 comments on commit d7cc7d2

Please sign in to comment.