pylucene 3.5.0-3
[pylucene.git] / lucene-java-3.5.0 / lucene / contrib / facet / src / java / org / apache / lucene / util / encoding / SimpleIntDecoder.java
1 package org.apache.lucene.util.encoding;
2
3 import java.io.IOException;
4 import java.io.StreamCorruptedException;
5
6 /**
7  * Licensed to the Apache Software Foundation (ASF) under one or more
8  * contributor license agreements.  See the NOTICE file distributed with
9  * this work for additional information regarding copyright ownership.
10  * The ASF licenses this file to You under the Apache License, Version 2.0
11  * (the "License"); you may not use this file except in compliance with
12  * the License.  You may obtain a copy of the License at
13  *
14  *     http://www.apache.org/licenses/LICENSE-2.0
15  *
16  * Unless required by applicable law or agreed to in writing, software
17  * distributed under the License is distributed on an "AS IS" BASIS,
18  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  * See the License for the specific language governing permissions and
20  * limitations under the License.
21  */
22
23 /**
24  * A simple stream decoder which can decode values encoded with
25  * {@link SimpleIntEncoder}.
26  * 
27  * @lucene.experimental
28  */
29 public class SimpleIntDecoder extends IntDecoder {
30
31   /**
32    * reusable buffer - allocated only once as this is not a thread-safe object
33    */
34   private byte[] buffer = new byte[4];
35
36   @Override
37   public long decode() throws IOException {
38
39     // we need exactly 4 bytes to decode an int in this decoder impl, otherwise, throw an exception
40     int offset = 0;
41     while (offset < 4) {
42       int nRead = in.read(buffer, offset, 4 - offset);
43       if (nRead == -1) {
44         if (offset > 0) {
45           throw new StreamCorruptedException(
46               "Need 4 bytes for decoding an int, got only " + offset);
47         }
48         return EOS;
49       }
50       offset += nRead;
51     }
52
53     int v = buffer[3] & 0xff;
54     v |= (buffer[2] << 8) & 0xff00;
55     v |= (buffer[1] << 16) & 0xff0000;
56     v |= (buffer[0] << 24) & 0xff000000;
57
58     return v;
59   }
60
61   @Override
62   public String toString() {
63     return "Simple";
64   }
65
66 }