pylucene 3.5.0-3
[pylucene.git] / lucene-java-3.5.0 / lucene / src / java / org / apache / lucene / index / ByteSliceWriter.java
1 package org.apache.lucene.index;
2
3 /**
4  * Licensed to the Apache Software Foundation (ASF) under one or more
5  * contributor license agreements.  See the NOTICE file distributed with
6  * this work for additional information regarding copyright ownership.
7  * The ASF licenses this file to You under the Apache License, Version 2.0
8  * (the "License"); you may not use this file except in compliance with
9  * the License.  You may obtain a copy of the License at
10  *
11  *     http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19
20
21 /**
22  * Class to write byte streams into slices of shared
23  * byte[].  This is used by DocumentsWriter to hold the
24  * posting list for many terms in RAM.
25  */
26
27 final class ByteSliceWriter {
28
29   private byte[] slice;
30   private int upto;
31   private final ByteBlockPool pool;
32
33   int offset0;
34
35   public ByteSliceWriter(ByteBlockPool pool) {
36     this.pool = pool;
37   }
38
39   /**
40    * Set up the writer to write at address.
41    */ 
42   public void init(int address) {
43     slice = pool.buffers[address >> DocumentsWriter.BYTE_BLOCK_SHIFT];
44     assert slice != null;
45     upto = address & DocumentsWriter.BYTE_BLOCK_MASK;
46     offset0 = address;
47     assert upto < slice.length;
48   }
49
50   /** Write byte into byte slice stream */
51   public void writeByte(byte b) {
52     assert slice != null;
53     if (slice[upto] != 0) {
54       upto = pool.allocSlice(slice, upto);
55       slice = pool.buffer;
56       offset0 = pool.byteOffset;
57       assert slice != null;
58     }
59     slice[upto++] = b;
60     assert upto != slice.length;
61   }
62
63   public void writeBytes(final byte[] b, int offset, final int len) {
64     final int offsetEnd = offset + len;
65     while(offset < offsetEnd) {
66       if (slice[upto] != 0) {
67         // End marker
68         upto = pool.allocSlice(slice, upto);
69         slice = pool.buffer;
70         offset0 = pool.byteOffset;
71       }
72
73       slice[upto++] = b[offset++];
74       assert upto != slice.length;
75     }
76   }
77
78   public int getAddress() {
79     return upto + (offset0 & DocumentsWriter.BYTE_BLOCK_NOT_MASK);
80   }
81
82   public void writeVInt(int i) {
83     while ((i & ~0x7F) != 0) {
84       writeByte((byte)((i & 0x7f) | 0x80));
85       i >>>= 7;
86     }
87     writeByte((byte) i);
88   }
89 }