1
package org.apache.lucene.util.encoding;
3
import java.io.IOException;
6
* Licensed to the Apache Software Foundation (ASF) under one or more
7
* contributor license agreements. See the NOTICE file distributed with
8
* this work for additional information regarding copyright ownership.
9
* The ASF licenses this file to You under the Apache License, Version 2.0
10
* (the "License"); you may not use this file except in compliance with
11
* the License. You may obtain a copy of the License at
13
* http://www.apache.org/licenses/LICENSE-2.0
15
* Unless required by applicable law or agreed to in writing, software
16
* distributed under the License is distributed on an "AS IS" BASIS,
17
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
* See the License for the specific language governing permissions and
19
* limitations under the License.
23
* An {@link IntEncoder} which implements variable length encoding. A number is
26
* <li>If it is less than 127 and non-negative, i.e. uses only 7 bits, it is
27
* encoded as a single byte: 0bbbbbbb.
28
* <li>If it occupies more than 7 bits, it is represented as a series of bytes,
29
* each byte carrying 7 bits. All but the last byte have the MSB set, the last
34
* <li>n = 117 = 01110101: This has less than 8 significant bits, therefore is
35
* encoded as 01110101 = 0x75.
36
* <li>n = 100000 = (binary) 11000011010100000. This has 17 significant bits,
37
* thus needs three Vint8 bytes. Pad it to a multiple of 7 bits, then split it
38
* into chunks of 7 and add an MSB, 0 for the last byte, 1 for the others:
39
* 1|0000110 1|0001101 0|0100000 = 0x86 0x8D 0x20.
41
* <b>NOTE:</b> although this encoder is not limited to values ≥ 0, it is not
42
* recommended for use with negative values, as their encoding will result in 5
43
* bytes written to the output stream, rather than 4. For such values, either
44
* use {@link SimpleIntEncoder} or write your own version of variable length
45
* encoding, which can better handle negative values.
47
* @lucene.experimental
49
public class VInt8IntEncoder extends IntEncoder {
52
public void encode(int value) throws IOException {
53
if ((value & ~0x7F) == 0) {
55
} else if ((value & ~0x3FFF) == 0) {
56
out.write(0x80 | (value >> 7));
57
out.write(0x7F & value);
58
} else if ((value & ~0x1FFFFF) == 0) {
59
out.write(0x80 | (value >> 14));
60
out.write(0x80 | (value >> 7));
61
out.write(0x7F & value);
62
} else if ((value & ~0xFFFFFFF) == 0) {
63
out.write(0x80 | (value >> 21));
64
out.write(0x80 | (value >> 14));
65
out.write(0x80 | (value >> 7));
66
out.write(0x7F & value);
68
out.write(0x80 | (value >> 28));
69
out.write(0x80 | (value >> 21));
70
out.write(0x80 | (value >> 14));
71
out.write(0x80 | (value >> 7));
72
out.write(0x7F & value);
77
public IntDecoder createMatchingDecoder() {
78
return new VInt8IntDecoder();
82
public String toString() {