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.

[backport from 2.1.x]

Fixes: java-json-tools#92

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

if (size > intValue)
report.error(newMsg(data).message(STRING_TOO_LONG)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ public void validate(final Processor<FullData, FullData> processor,
final ProcessingReport report, final FullData data)
throws ProcessingException
{
final int size = data.getInstance().getNode().textValue()
.length();
final String value = data.getInstance().getNode().textValue();
final int size = value.codePointCount(0, value.length());

if (size < intValue)
report.error(newMsg(data).message(STRING_TOO_SHORT)
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 @@ -18,5 +18,10 @@
"digest": { "maxLength": 4 },
"data": "foo",
"valid": true
},
{
"digest": { "maxLength": 3 },
"data": "\uD83D\uDCA9\uD83D\uDCA9",
"valid": true
}
]
10 changes: 10 additions & 0 deletions src/test/resources/keyword/validators/common/minLength.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,15 @@
"digest": { "minLength": 4 },
"data": "foobar",
"valid": true
},
{
"digest": { "minLength": 4 },
"data": "\uD83D\uDCA9\uD83D\uDCA9",
"valid": false,
"message": "STRING_TOO_SHORT",
"msgData": {
"minLength": 4,
"found": 2
}
}
]

0 comments on commit 8e451cc

Please sign in to comment.