Skip to content

Commit

Permalink
Fix JSON string length calculations
Browse files Browse the repository at this point in the history
A JSON String length is the number of its Unicode code points; unfortunately,
String's .length() counts the number of `char`s, that is the number of UTF-16
code units.

But for Unicode code points outside the BMP, UTF-16 requires two code units, and
String two `char`s as well.

Change the length calculation by calling .codePointCount() instead.

Fixes: java-json-tools#92

Signed-off-by: Francis Galiegue <[email protected]>
  • Loading branch information
fge committed Apr 7, 2014
1 parent 5d6b04c commit 1b7ca76
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public void validate(final Processor<FullData, FullData> processor,
throws ProcessingException
{
final String value = data.getInstance().getNode().textValue();
final int size = value.length();
final int size = value.codePointCount(0, value.length());

if (size > intValue)
report.error(newMsg(data, bundle, "err.common.maxLength.tooLong")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public void validate(final Processor<FullData, FullData> processor,
throws ProcessingException
{
final String value = data.getInstance().getNode().textValue();
final int size = value.length();
final int size = value.codePointCount(0, value.length());

if (size < intValue)
report.error(newMsg(data, bundle, "err.common.minLength.tooShort")
Expand Down
5 changes: 5 additions & 0 deletions src/test/resources/keyword/validators/common/maxLength.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,10 @@
"digest": { "maxLength": 4 },
"data": "foo",
"valid": true
},
{
"digest": { "maxLength": 3 },
"data": "\uD83D\uDCA9\uD83D\uDCA9",
"valid": true
}
]
12 changes: 12 additions & 0 deletions src/test/resources/keyword/validators/common/minLength.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,17 @@
"digest": { "minLength": 4 },
"data": "foobar",
"valid": true
},
{
"digest": { "minLength": 4 },
"data": "\uD83D\uDCA9\uD83D\uDCA9",
"valid": false,
"message": "err.common.minLength.tooShort",
"msgData": {
"value": "\uD83D\uDCA9\uD83D\uDCA9",
"minLength": 4,
"found": 2
},
"msgParams": [ "value", "found", "minLength" ]
}
]

0 comments on commit 1b7ca76

Please sign in to comment.