pylucene 3.5.0-3
[pylucene.git] / lucene-java-3.5.0 / lucene / src / java / org / apache / lucene / analysis / BaseCharFilter.java
1 /**
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements.  See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License.  You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 package org.apache.lucene.analysis;
19
20 import org.apache.lucene.util.ArrayUtil;
21
22 /**
23  * Base utility class for implementing a {@link CharFilter}.
24  * You subclass this, and then record mappings by calling
25  * {@link #addOffCorrectMap}, and then invoke the correct
26  * method to correct an offset.
27  */
28 public abstract class BaseCharFilter extends CharFilter {
29
30   private int offsets[];
31   private int diffs[];
32   private int size = 0;
33   
34   public BaseCharFilter(CharStream in) {
35     super(in);
36   }
37
38   /** Retrieve the corrected offset. */
39   @Override
40   protected int correct(int currentOff) {
41     if (offsets == null || currentOff < offsets[0]) {
42       return currentOff;
43     }
44     
45     int hi = size - 1;
46     if(currentOff >= offsets[hi])
47       return currentOff + diffs[hi];
48
49     int lo = 0;
50     int mid = -1;
51     
52     while (hi >= lo) {
53       mid = (lo + hi) >>> 1;
54       if (currentOff < offsets[mid])
55         hi = mid - 1;
56       else if (currentOff > offsets[mid])
57         lo = mid + 1;
58       else
59         return currentOff + diffs[mid];
60     }
61
62     if (currentOff < offsets[mid])
63       return mid == 0 ? currentOff : currentOff + diffs[mid-1];
64     else
65       return currentOff + diffs[mid];
66   }
67   
68   protected int getLastCumulativeDiff() {
69     return offsets == null ?
70       0 : diffs[size-1];
71   }
72
73   protected void addOffCorrectMap(int off, int cumulativeDiff) {
74     if (offsets == null) {
75       offsets = new int[64];
76       diffs = new int[64];
77     } else if (size == offsets.length) {
78       offsets = ArrayUtil.grow(offsets);
79       diffs = ArrayUtil.grow(diffs);
80     }
81     
82     offsets[size] = off;
83     diffs[size++] = cumulativeDiff; 
84   }
85 }