aboutsummaryrefslogtreecommitdiffstats
path: root/vespajlib/src/main/java/com/yahoo/text/StringUtilities.java
blob: 025eeba3998fd21e9906b3345f729a00d94f6f7f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.text;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.List;
import java.io.ByteArrayOutputStream;
import java.util.Set;

/**
 * Escapes strings into and out of a format where they only contain printable characters.
 *
 * Need to duplicate escape / unescape of strings as we have in C++ for java version of system states.
 *
 * @author Haakon Humberset
 */
// TODO: Text utilities should which are still needed should move to Text. This should be deprecated.
public class StringUtilities {

    private static final Charset UTF8 = StandardCharsets.UTF_8;

    private static byte toHex(int val) { return (byte) (val < 10 ? '0' + val : 'a' + (val - 10)); }

    private static class ReplacementCharacters {

        public byte[] needEscape = new byte[256];
        public byte[] replacement1 = new byte[256];
        public byte[] replacement2 = new byte[256];

        public ReplacementCharacters() {
            for (int i=0; i<256; ++i) {
                if (i >= 32 && i <= 126) {
                    needEscape[i] = 0;
                } else {
                    needEscape[i] = 3;
                    replacement1[i] = toHex((i >> 4) & 0xF);
                    replacement2[i] = toHex(i & 0xF);
                }
            }
            makeSimpleEscape('"', '"');
            makeSimpleEscape('\\', '\\');
            makeSimpleEscape('\t', 't');
            makeSimpleEscape('\n', 'n');
            makeSimpleEscape('\r', 'r');
            makeSimpleEscape('\f', 'f');
        }

        private void makeSimpleEscape(char source, char dest) {
            needEscape[source] = 1;
            replacement1[source] = '\\';
            replacement2[source] = (byte) dest;
        }
    }

    private final static ReplacementCharacters replacementCharacters = new ReplacementCharacters();

    public static String escape(String source) { return escape(source, '\0'); }

    /**
     * Escapes strings into a format with only printable ASCII characters.
     *
     * @param source The string to escape
     * @param delimiter Escape this character too, even if it is printable.
     * @return The escaped string
     */
    public static String escape(String source, char delimiter) {
        byte[] bytes = source.getBytes(UTF8);
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        for (byte b : bytes) {
            int val = b;
            if (val < 0) val += 256;
            if (b == delimiter) {
                result.write('\\');
                result.write('x');
                result.write(toHex((val >> 4) & 0xF));
                result.write(toHex(val & 0xF));
            } else if (replacementCharacters.needEscape[val] == 0) {
                result.write(b);
            } else {
                if (replacementCharacters.needEscape[val] == 3) {
                    result.write('\\');
                    result.write('x');
                }
                result.write(replacementCharacters.replacement1[val]);
                result.write(replacementCharacters.replacement2[val]);
            }
        }
        return result.toString(UTF8);
    }

    public static String unescape(String source) {
        byte[] bytes = source.getBytes(UTF8);
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        for (int i=0; i<bytes.length; ++i) {
            if (bytes[i] != '\\') {
                result.write(bytes[i]);
                continue;
            }
            if (i + 1 == bytes.length) throw new IllegalArgumentException("Found backslash at end of input");

            if (bytes[i + 1] != (byte) 'x') {
                switch (bytes[i + 1]) {
                    case '\\' -> result.write('\\');
                    case '"' -> result.write('"');
                    case 't' -> result.write('\t');
                    case 'n' -> result.write('\n');
                    case 'r' -> result.write('\r');
                    case 'f' -> result.write('\f');
                    default -> throw new IllegalArgumentException("Illegal escape sequence \\" + ((char) bytes[i + 1]) + " found");
                }
                ++i;
                continue;
            }

            if (i + 3 >= bytes.length) throw new IllegalArgumentException("Found \\x at end of input");

            String hexdigits = "" + ((char) bytes[i + 2]) + ((char) bytes[i + 3]);
            result.write((byte) Integer.parseInt(hexdigits, 16));
            i += 3;
        }
        return result.toString(UTF8);
    }

    /**
     * Returns the given array flattened to string, with the given separator string
     * @param array the array
     * @param sepString or null
     * @return imploded array
     */
    public static String implode(String[] array, String sepString) {
        if (array==null) return null;
        StringBuilder ret = new StringBuilder();
        if (sepString==null) sepString="";
        for (int i = 0 ; i<array.length ; i++) {
            ret.append(array[i]);
            if (!(i==array.length-1)) ret.append(sepString);
        }
        return ret.toString();
    }

    /**
     * Returns the given list flattened to one with newline between
     *
     * @return flattened string
     */
    public static String implodeMultiline(List<String> lines) {
        if (lines==null) return null;
        return implode(lines.toArray(new String[0]), "\n");
    }

    /**
     * This will truncate sequences in a string of the same character that exceed the maximum
     * allowed length.
     *
     * @return The same string or a new one if truncation is done.
     */
    public static String truncateSequencesIfNecessary(String text, int maxConsecutiveLength) {
        char prev = 0;
        int sequenceCount = 1;
        for (int i = 0, m = text.length(); i < m ; i++) {
            char curr = text.charAt(i);
            if (prev == curr) {
                sequenceCount++;
                if (sequenceCount > maxConsecutiveLength) {
                    return truncateSequences(text, maxConsecutiveLength, i);
                }
            } else {
                sequenceCount = 1;
                prev = curr;
            }
        }
        return text;
    }

    private static String truncateSequences(String text, int maxConsecutiveLength, int firstTruncationPos) {
        char [] truncated = text.toCharArray();
        char prev = truncated[firstTruncationPos];
        int sequenceCount = maxConsecutiveLength + 1;
        int wp=firstTruncationPos;
        for (int rp=wp+1; rp < truncated.length; rp++) {
            char curr = truncated[rp];
            if (prev == curr) {
                sequenceCount++;
                if (sequenceCount <= maxConsecutiveLength) {
                    truncated[wp++] = curr;
                }
            } else {
                truncated[wp++] = curr;
                sequenceCount = 1;
                prev = curr;
            }
        }
        return String.copyValueOf(truncated, 0, wp);
    }

    public static String stripSuffix(String string, String suffix) {
        int index = string.lastIndexOf(suffix);
        return index == -1 ? string : string.substring(0, index);
    }

    /**
     * Adds single quotes around object.toString
     * Example:  '12'
     */
    public static String quote(Object object) {
        return "'" + object.toString() + "'";
    }

    /** Splits a string on both space and comma */
    public static Set<String> split(String s) {
        if (s == null || s.isEmpty()) return Set.of();
        Set<String> b = new HashSet<>();
        for (String item : s.split("[\\s,]"))
            if ( ! item.isEmpty())
                b.add(item);
        return Set.copyOf(b);
    }

}