summaryrefslogtreecommitdiffstats
path: root/container-search/src/main/java/com/yahoo/search/grouping/vespa/IntegerDecoder.java
blob: c398fb41db26e87003f5726d975ab28da4dcd906 (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
// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.grouping.vespa;

/**
 * @author <a href="mailto:simon@yahoo-inc.com">Simon Thoresen</a>
 */
class IntegerDecoder {

    private static final int CHAR_MIN = IntegerEncoder.CHARS[0];
    private static final int CHAR_MAX = IntegerEncoder.CHARS[IntegerEncoder.CHARS.length - 1];
    private final String input;
    private int pos = 0;

    public IntegerDecoder(String input) {
        this.input = input;
    }

    public boolean hasNext() {
        return pos < input.length();
    }

    public int next() {
        int val = 0;
        int len = decodeChar(input.charAt(pos++));
        for (int i = 0; i < len; i++) {
            val = (val << 4) | decodeChar(input.charAt(pos + i));
        }
        pos += len;
        return (val >>> 1) ^ (-(val & 0x1));
    }

    private static int decodeChar(char c) {
        if (c >= CHAR_MIN && c <= CHAR_MAX) {
            return (0xF & (c - CHAR_MIN));
        } else {
            throw new NumberFormatException(String.valueOf(c));
        }
    }
}