Skip to content

Commit

Permalink
Fix decoding when alphabet contains regex-like special chars (#10)
Browse files Browse the repository at this point in the history
Fix decoding when the alphabet contains regex-like special chars.
  • Loading branch information
JordanArmstrong authored Nov 29, 2023
1 parent 4893e1b commit 21bc107
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 20 deletions.
39 changes: 19 additions & 20 deletions src/main/java/org/sqids/Sqids.java
Original file line number Diff line number Diff line change
Expand Up @@ -137,22 +137,23 @@ public List<Long> decode(final String id) {
.append(this.alphabet, 0, offset)
.reverse()
.toString();
String slicedId = id.substring(1);

while (!slicedId.isEmpty()) {
int index = 1;
while (true) {
final char separator = alphabet.charAt(0);
final String[] chunks = slicedId.split(String.valueOf(separator), 2);
final int chunksLength = chunks.length;
if (chunksLength > 0) {
if (chunks[0].isEmpty()) {
return ret;
}
ret.add(toNumber(chunks[0], alphabet.substring(1)));
if (chunksLength > 1) {
alphabet = shuffle(alphabet);
}
int separatorIndex = id.indexOf(separator, index);
if (separatorIndex == -1) {
separatorIndex = id.length();
} else if (index == separatorIndex) {
break;
}
ret.add(toNumber(id, index, separatorIndex, alphabet.substring(1)));
index = separatorIndex + 1;
if (index < id.length()) {
alphabet = shuffle(alphabet);
} else {
break;
}
slicedId = chunksLength > 1 ? chunks[1] : "";
}
return ret;
}
Expand Down Expand Up @@ -230,15 +231,13 @@ private StringBuilder toId(long num, final String alphabet) {
return id.reverse();
}

private long toNumber(final String id, final String alphabet) {
char[] chars = alphabet.toCharArray();
int charLength = chars.length;
private long toNumber(final String id, final int fromInclusive, final int toExclusive, final String alphabet) {
int alphabetLength = alphabet.length();
long number = 0;

for (char c : id.toCharArray()) {
number = number * charLength + alphabet.indexOf(c);
for (int i = fromInclusive; i < toExclusive; i++) {
char c = id.charAt(i);
number = number * alphabetLength + alphabet.indexOf(c);
}

return number;
}

Expand Down
9 changes: 9 additions & 0 deletions src/test/java/org/sqids/AlphabetTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,15 @@ public void shortAlphabet() {
Assertions.assertEquals(sqids.decode(sqids.encode(numbers)), numbers);
}

@Test
public void specialCharsAlphabet() {
Sqids sqids = Sqids.builder()
.alphabet(".\\?")
.build();
List<Long> numbers = Arrays.asList(1L, 2L, 3L);
Assertions.assertEquals(sqids.decode(sqids.encode(numbers)), numbers);
}

@Test
public void multibyteCharacters() {
Assertions.assertThrows(IllegalArgumentException.class, () -> Sqids.builder()
Expand Down

0 comments on commit 21bc107

Please sign in to comment.