add --shared
[pylucene.git] / lucene-java-3.4.0 / lucene / contrib / facet / src / java / org / apache / lucene / util / encoding / SortingIntEncoder.java
1 package org.apache.lucene.util.encoding;
2
3 import java.io.IOException;
4 import java.io.OutputStream;
5 import java.util.Arrays;
6
7 /**
8  * Licensed to the Apache Software Foundation (ASF) under one or more
9  * contributor license agreements.  See the NOTICE file distributed with
10  * this work for additional information regarding copyright ownership.
11  * The ASF licenses this file to You under the Apache License, Version 2.0
12  * (the "License"); you may not use this file except in compliance with
13  * the License.  You may obtain a copy of the License at
14  *
15  *     http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  */
23
24 /**
25  * An {@link IntEncoderFilter} which sorts the values to encode in ascending
26  * order before encoding them. Encoding therefore happens upon calling
27  * {@link #close()}. Since this encoder is usually chained with another encoder
28  * that relies on sorted values, it does not offer a default constructor.
29  * 
30  * @lucene.experimental
31  */
32 public class SortingIntEncoder extends IntEncoderFilter {
33
34   private float grow = 2.0f;
35   private int index = 0;
36   private int[] set = new int[1024];
37
38   /** Initializes with the given encoder. */
39   public SortingIntEncoder(IntEncoder encoder) {
40     super(encoder);
41   }
42
43   @Override
44   public void close() throws IOException {
45     if (index == 0) {
46       return;
47     }
48
49     Arrays.sort(set, 0, index);
50     for (int i = 0; i < index; i++) {
51       encoder.encode(set[i]);
52     }
53     encoder.close();
54     index = 0;
55
56     super.close();
57   }
58
59   @Override
60   public void encode(int value) throws IOException {
61     if (index == set.length) {
62       int[] newSet = new int[(int) (set.length * grow)];
63       System.arraycopy(set, 0, newSet, 0, set.length);
64       set = newSet;
65     }
66     set[index++] = value;
67   }
68
69   @Override
70   public IntDecoder createMatchingDecoder() {
71     return encoder.createMatchingDecoder();
72   }
73   
74   @Override
75   public void reInit(OutputStream out) {
76     super.reInit(out);
77     index = 0;
78   }
79
80   @Override
81   public String toString() {
82     return "Sorting (" + encoder.toString() + ")";
83   }
84   
85 }