Skip to content

Commit

Permalink
add ISOUtil.toASCII and toLatin helper methods
Browse files Browse the repository at this point in the history
  • Loading branch information
ar committed Apr 10, 2024
1 parent 49299b1 commit 81e1047
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
28 changes: 28 additions & 0 deletions jpos/src/main/java/org/jpos/iso/ISOUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -1733,4 +1733,32 @@ public static String charDecode(String s, char delimiter, int i) {
return i < split.length ? split[i] : "";
}
}

public static String toUnicodeString(String input) {
StringBuilder sb = new StringBuilder();
for (char c : input.toCharArray()) {
sb.append(String.format("\\u%04x", (int) c));
}
return sb.toString();
}

public static String toASCII(String s) {
return toSingleByte (s, 0x7F);
}
public static String toLatin(String s) {
return toSingleByte (s, 0xFF);
}

private static String toSingleByte(String s, int mask) {
StringBuilder sb = new StringBuilder();
s.codePoints().forEach(cp -> {
if (cp > mask) {
sb.append(" ");
if (cp > 0xFFFF) // multi-byte character
sb.append(" ");
} else
sb.appendCodePoint(cp); // Append the single-byte character
});
return sb.toString();
}
}
13 changes: 13 additions & 0 deletions jpos/src/test/java/org/jpos/iso/ISOUtilTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -5072,4 +5072,17 @@ public void testCharEncodeAndDecode() {
assertEquals("", ISOUtil.charDecode("a:b:c", ':', 4), "error getting part 4 of \"a:b:c\"");
assertEquals("b", ISOUtil.charDecode(":b:c", ':', 1), "error getting part 1 of \":b:c\"");
}

@Test
public void testUTF () {
String s = "- \uD83D\uDC7D\uD83D\uDC94LTUS Lei\u0091s 19 Ñandú Rally\u0092sINUS";
String expectedLatin = "- LTUS Lei\u0091s 19 Ñandú Rally\u0092sINUS";
String expectedASCII = "- LTUS Lei s 19 and Rally sINUS";
String d = ISOUtil.toLatin(s);
assertEquals(s.length(), d.length());
assertEquals(expectedLatin, d);
d = ISOUtil.toASCII(s);
assertEquals(s.length(), d.length());
assertEquals(expectedASCII, d);
}
}

0 comments on commit 81e1047

Please sign in to comment.