From 733242f9800eebe84436deaee4eaa415bafda8f6 Mon Sep 17 00:00:00 2001 From: Fabio Lima Date: Tue, 2 Jan 2024 18:27:49 -0300 Subject: [PATCH] fix: ArrayIndexOutOfBoundsException with multiple bytes for a character #32 --- src/main/java/com/github/f4b6a3/ulid/Ulid.java | 16 ++++++++++------ .../java/com/github/f4b6a3/ulid/UlidTest.java | 12 +++++++++++- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/github/f4b6a3/ulid/Ulid.java b/src/main/java/com/github/f4b6a3/ulid/Ulid.java index 1c655e1..40bcc5e 100644 --- a/src/main/java/com/github/f4b6a3/ulid/Ulid.java +++ b/src/main/java/com/github/f4b6a3/ulid/Ulid.java @@ -793,6 +793,16 @@ public final class Ulid implements Serializable, Comparable { return false; // null or wrong size! } + for (int i = 0; i < chars.length; i++) { + try { + if (ALPHABET_VALUES[chars[i]] == -1) { + return false; // invalid character! + } + } catch (ArrayIndexOutOfBoundsException e) { + return false; // Multibyte character! + } + } + // The time component has 48 bits. // The base32 encoded time component has 50 bits. // The time component cannot be greater than than 2^48-1. @@ -805,12 +815,6 @@ public final class Ulid implements Serializable, Comparable { return false; // time overflow! } - for (int i = 0; i < chars.length; i++) { - if (ALPHABET_VALUES[chars[i]] == -1) { - return false; // invalid character! - } - } - return true; // It seems to be OK. } } diff --git a/src/test/java/com/github/f4b6a3/ulid/UlidTest.java b/src/test/java/com/github/f4b6a3/ulid/UlidTest.java index 62d1349..cbcb9d7 100644 --- a/src/test/java/com/github/f4b6a3/ulid/UlidTest.java +++ b/src/test/java/com/github/f4b6a3/ulid/UlidTest.java @@ -104,7 +104,7 @@ public class UlidTest extends UlidFactoryTest { } @Test - public void testFromStrings() { + public void testFromString() { Random random = new Random(); for (int i = 0; i < DEFAULT_LOOP_MAX; i++) { final long msb = random.nextLong(); @@ -610,6 +610,16 @@ public class UlidTest extends UlidFactoryTest { } catch (IllegalArgumentException e) { // success } + + // https://github.com/f4b6a3/ulid-creator/issues/32 + // https://www.compart.com/en/unicode/U+3617 (㘗: whisper; to whistle) + ulid = "0123456789ABCDEFGHJKMNPQR\u3617"; + try { + Ulid.toCharArray(ulid); + fail("Should throw an exception"); + } catch (IllegalArgumentException e) { + // success + } } @Test