Debian Codegraph @

morfologik-stemming/src/main/java/morfologik/stemming/TrimSuffixEncoder.java

raw
1 package morfologik.stemming;
2
3 import java.nio.ByteBuffer;
4
5 /**
6 * Encodes <code>dst</code> relative to <code>src</code> by trimming whatever
7 * non-equal suffix <code>src</code> has. The output code is (bytes):
8 *
9 * <pre>
10 * {K}{suffix}
11 * </pre>
12 *
13 * where (<code>K</code> - 'A') bytes should be trimmed from the end of
14 * <code>src</code> and then the <code>suffix</code> should be appended to the
15 * resulting byte sequence.
16 *
17 * <p>
18 * Examples:
19 * </p>
20 *
21 * <pre>
22 * src: foo
23 * dst: foobar
24 * encoded: Abar
25 *
26 * src: foo
27 * dst: bar
28 * encoded: Dbar
29 * </pre>
30 */
31 public class TrimSuffixEncoder implements ISequenceEncoder {
32 /**
33 * Maximum encodable single-byte code.
34 */
35 private static final int REMOVE_EVERYTHING = 255;
36
37 public ByteBuffer encode(ByteBuffer reuse, ByteBuffer source, ByteBuffer target) {
38 int sharedPrefix = BufferUtils.sharedPrefixLength(source, target);
39 int truncateBytes = source.remaining() - sharedPrefix;
40 if (truncateBytes >= REMOVE_EVERYTHING) {
41 truncateBytes = REMOVE_EVERYTHING;
42 sharedPrefix = 0;
43 }
44
45 reuse = BufferUtils.clearAndEnsureCapacity(reuse, 1 + target.remaining() - sharedPrefix);
46
47 assert target.hasArray() &&
48 target.position() == 0 &&
49 target.arrayOffset() == 0;
50
51 final byte suffixTrimCode = (byte) (truncateBytes + 'A');
52 reuse.put(suffixTrimCode)
53 .put(target.array(), sharedPrefix, target.remaining() - sharedPrefix)
54 .flip();
55
56 return reuse;
57 }
58
59 @Override
60 public int prefixBytes() {
61 return 1;
62 }
63
64 public ByteBuffer decode(ByteBuffer reuse, ByteBuffer source, ByteBuffer encoded) {
65 assert encoded.remaining() >= 1;
66
67 int suffixTrimCode = encoded.get(encoded.position());
68 int truncateBytes = (suffixTrimCode - 'A') & 0xFF;
69 if (truncateBytes == REMOVE_EVERYTHING) {
70 truncateBytes = source.remaining();
71 }
72
73 final int len1 = source.remaining() - truncateBytes;
74 final int len2 = encoded.remaining() - 1;
75
76 reuse = BufferUtils.clearAndEnsureCapacity(reuse, len1 + len2);
77
78 assert source.hasArray() &&
79 source.position() == 0 &&
80 source.arrayOffset() == 0;
81
82 assert encoded.hasArray() &&
83 encoded.position() == 0 &&
84 encoded.arrayOffset() == 0;
85
86 reuse.put(source.array(), 0, len1)
87 .put(encoded.array(), 1, len2)
88 .flip();
89
90 return reuse;
91 }
92
93 @Override
94 public String toString() {
95 return getClass().getSimpleName();
96 }
97 }