
br.com.objectos.core.lang.Escaper Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of strings Show documentation
Show all versions of strings Show documentation
A very small Java8 String utility library.
The newest version!
/*
* Copyright 2011-present Objectos, Fábrica de Software LTDA.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package br.com.objectos.core.lang;
import java.util.HashMap;
import java.util.Map;
/**
* Based on Guava's ArrayBasedCharEscaper
*
* @author [email protected] (Marcio Endo)
*/
public class Escaper {
private final char[][] replacementMap;
private final int length;
private Escaper(char[][] map) {
replacementMap = map;
length = map.length;
}
public static Builder builder() {
return new Builder();
}
public String escape(String string) {
int length = string.length();
for (int index = 0; index < length; index++) {
if (escape(string.charAt(index)) != null) {
return escapeSlow(string, index);
}
}
return string;
}
private char[] escape(char c) {
if (c < length) {
char[] chars = replacementMap[c];
if (chars != null) {
return chars;
}
}
return null;
}
private String escapeSlow(String string, int index) {
StringBuilder builder = new StringBuilder(string.length() + 16);
builder.append(string.substring(0, index));
for (int i = index; i < string.length(); i++) {
char c = string.charAt(i);
char[] replacement = escape(c);
if (replacement == null) {
builder.append(c);
} else {
builder.append(replacement);
}
}
return builder.toString();
}
public static class Builder {
private final Map map = new HashMap<>();
private char max = Character.MIN_VALUE;
private Builder() {
}
public Builder addEscape(char c, String replacement) {
map.put(c, replacement);
if (c > max) {
max = c;
}
return this;
}
public Escaper build() {
char[][] replacementMap = new char[max + 1][];
map.entrySet()
.stream()
.forEach(e -> replacementMap[e.getKey().charValue()] = e.getValue().toCharArray());
return new Escaper(replacementMap);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy