Skip to content

Instantly share code, notes, and snippets.

@drmalex07
Created February 6, 2021 00:52
Show Gist options
  • Save drmalex07/4182c671f3091450ce3f423171752900 to your computer and use it in GitHub Desktop.
Save drmalex07/4182c671f3091450ce3f423171752900 to your computer and use it in GitHub Desktop.
Mimic escapism Python package in Java. #escapism
import java.util.Objects;
/**
* Mimic escaping logic from Python {@code escapism} package.
*/
public class Escapism
{
public static final String SAFE_CHARS = "abcdefghijklmnopqrstuvwxyz0123456789";
public static final char ESCAPE_CHAR = '-';
public static String escape(String s)
{
return escape(s, SAFE_CHARS, ESCAPE_CHAR);
}
public static String unescape(String s)
{
return unescape(s, SAFE_CHARS, ESCAPE_CHAR);
}
public static String escape(String s, String safeChars, Character escapeChar)
{
Objects.requireNonNull(safeChars);
Objects.requireNonNull(escapeChar);
checkEscapeCharacter(escapeChar, safeChars);
final int n = s.length();
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; ++i) {
final char c = s.charAt(i);
if (safeChars.indexOf(c) < 0) {
sb.append(String.format("%c%02x", escapeChar, (int) c));
} else {
sb.append(c);
}
}
return sb.toString();
}
public static String unescape(String s, String safeChars, Character escapeChar)
{
Objects.requireNonNull(safeChars);
Objects.requireNonNull(escapeChar);
checkEscapeCharacter(escapeChar, safeChars);
final int n = s.length();
final StringBuilder sb = new StringBuilder();
int i = 0;
while (i < n) {
final char c = s.charAt(i++);
if (c == escapeChar) {
int d = Integer.valueOf(s.substring(i, i + 2), 16);
i += 2;
sb.append((char) d);
} else {
sb.append(c);
}
}
return sb.toString();
}
private static void checkEscapeCharacter(Character escapeChar, String safeChars)
{
if (safeChars.indexOf(escapeChar) >= 0) {
throw new IllegalArgumentException("escape character cannot also be a safe character!");
}
}
public static void main(String[] args)
{
final String s = "[email protected]";
final String s1a = "someone_2d123_40example_2ecom";
final String s1b = escape(s);
System.err.println(s1a);
System.err.println(s1b);
String x = unescape(s1b);
System.err.println(s);
System.err.println(x);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment