pylucene 3.5.0-3
[pylucene.git] / lucene-java-3.5.0 / lucene / contrib / facet / src / java / org / apache / lucene / util / encoding / NOnesIntDecoder.java
1 package org.apache.lucene.util.encoding;
2
3 import java.io.IOException;
4 import java.io.InputStream;
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  * Decodes data which was encoded by {@link NOnesIntEncoder}. Uses a
25  * {@link FourFlagsIntDecoder} to perform the actual encoding and translates the
26  * values back as described in {@link NOnesIntEncoder}.
27  * 
28  * @see NOnesIntEncoder
29  * @lucene.experimental
30  */
31 public class NOnesIntDecoder extends FourFlagsIntDecoder {
32
33   /** Number of consecutive '1's to generate upon decoding a '2'. */
34   private int n;
35
36   private int onesCounter;
37
38   /**
39    * Constructs a decoder with a given N (Number of consecutive '1's which are
40    * translated into a single target value '2'.
41    */
42   public NOnesIntDecoder(int n) {
43     this.n = n;
44   }
45
46   @Override
47   public long decode() throws IOException {
48     // If we read '2', we should return n '1's.
49     if (onesCounter > 0) {
50       --onesCounter;
51       return 1;
52     }
53
54     long decode = super.decode();
55     if (decode == 1) {
56       return 1;
57     }
58     if (decode == 2) {
59       onesCounter = n - 1;
60       return 1;
61     }
62     if (decode == 3) {
63       return 2;
64     }
65     return decode == EOS ? EOS : decode - 1;
66   }
67
68   @Override
69   public void reInit(InputStream in) {
70     super.reInit(in);
71     onesCounter = 0;
72   }
73
74   @Override
75   public String toString() {
76     return "NOnes (" + n + ") (" + super.toString() + ")";
77   }
78
79 }