1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.text.translate;
18
19 import java.io.IOException;
20 import java.io.Writer;
21 import java.util.HashMap;
22 import java.util.HashSet;
23
24
25
26
27
28
29
30 public class SingleLookupTranslator extends CharSequenceTranslator {
31
32 private final HashMap<String, String> lookupMap;
33 private final HashSet<Character> prefixSet;
34 private final int shortest;
35 private final int longest;
36 private final int shortestValue;
37 private final int longestValue;
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54 public SingleLookupTranslator(final String[][]... inputArrays) {
55 String[][] lookup = new String[0][];
56 for (String[][] input : inputArrays) {
57 lookup = append(lookup, input);
58 }
59 lookupMap = new HashMap<String, String>();
60 prefixSet = new HashSet<Character>();
61 int _shortest = Integer.MAX_VALUE;
62 int _longest = 0;
63 int _shortestValue = Integer.MAX_VALUE;
64 int _longestValue = 0;
65 if (lookup != null) {
66 for (final CharSequence[] seq : lookup) {
67 this.lookupMap.put(seq[0].toString(), seq[1].toString());
68 this.prefixSet.add(seq[0].charAt(0));
69 final int sz = seq[0].length();
70 if (sz < _shortest) {
71 _shortest = sz;
72 }
73 if (sz > _longest) {
74 _longest = sz;
75 }
76 final int sizeOfValue = seq[1].length();
77 if (sizeOfValue < _shortestValue) {
78 _shortestValue = sizeOfValue;
79 }
80 if (sizeOfValue > _longestValue) {
81 _longestValue = sizeOfValue;
82 }
83 }
84 }
85 shortest = _shortest;
86 longest = _longest;
87 shortestValue = _shortestValue;
88 longestValue = _longestValue;
89 }
90
91 private static String[][] append(String[][] a, String[][] b) {
92 String[][] result = new String[a.length + b.length][];
93 System.arraycopy(a, 0, result, 0, a.length);
94 System.arraycopy(b, 0, result, a.length, b.length);
95 return result;
96 }
97
98
99
100
101
102
103
104
105
106
107
108
109
110 @Override
111 public int translate(CharSequence input, int index, Writer out) throws IOException {
112
113 int maxValue = longestValue;
114 if (index + maxValue > input.length()) {
115 maxValue = input.length() - index;
116 }
117
118 for (int i = maxValue; i >= shortestValue; i--) {
119 final CharSequence subSeq = input.subSequence(index, index + i);
120
121 if (lookupMap.containsValue(subSeq.toString())) {
122 return 0;
123 }
124 }
125
126
127 if (prefixSet.contains(input.charAt(index))) {
128 int max = longest;
129 if (index + longest > input.length()) {
130 max = input.length() - index;
131 }
132
133 for (int i = max; i >= shortest; i--) {
134 final CharSequence subSeq = input.subSequence(index, index + i);
135 final String result = lookupMap.get(subSeq.toString());
136
137 if (result != null) {
138 out.write(result);
139 return i;
140 }
141 }
142 }
143 return 0;
144 }
145 }