Debian Codegraph @

jdbm1/src/main/java/jdbm/htree/HashDirectory.java

raw
1 /**
2 * JDBM LICENSE v1.00
3 *
4 * Redistribution and use of this software and associated documentation
5 * ("Software"), with or without modification, are permitted provided
6 * that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain copyright
9 * statements and notices. Redistributions must also contain a
10 * copy of this document.
11 *
12 * 2. Redistributions in binary form must reproduce the
13 * above copyright notice, this list of conditions and the
14 * following disclaimer in the documentation and/or other
15 * materials provided with the distribution.
16 *
17 * 3. The name "JDBM" must not be used to endorse or promote
18 * products derived from this Software without prior written
19 * permission of Cees de Groot. For written permission,
20 * please contact [email protected].
21 *
22 * 4. Products derived from this Software may not be called "JDBM"
23 * nor may "JDBM" appear in their names without prior written
24 * permission of Cees de Groot.
25 *
26 * 5. Due credit should be given to the JDBM Project
27 * (http://jdbm.sourceforge.net/).
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE JDBM PROJECT AND CONTRIBUTORS
30 * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
31 * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
32 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
33 * CEES DE GROOT OR ANY CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
34 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
35 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
36 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
38 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
39 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
40 * OF THE POSSIBILITY OF SUCH DAMAGE.
41 *
42 * Copyright 2000 (C) Cees de Groot. All Rights Reserved.
43 * Contributions are Copyright (C) 2000 by their associated contributors.
44 *
45 */
46
47 package jdbm.htree;
48
49
50 import java.io.Externalizable;
51 import java.io.IOException;
52 import java.io.ObjectInput;
53 import java.io.ObjectOutput;
54 import java.util.ArrayList;
55 import java.util.Iterator;
56
57 import jdbm.I18n;
58 import jdbm.RecordManager;
59 import jdbm.helper.FastIterator;
60 import jdbm.helper.IterationException;
61
62
63 /**
64 * Hashtable directory page.
65 *
66 * @author <a href="mailto:[email protected]">Alex Boisvert</a>
67 */
68 final class HashDirectory
69 extends HashNode
70 implements Externalizable
71 {
72
73 static final long serialVersionUID = 1L;
74
75 /**
76 * Maximum number of children in a directory.
77 *
78 * (Must be a power of 2 -- if you update this value, you must also
79 * update BIT_SIZE and MAX_DEPTH.)
80 */
81 static final int MAX_CHILDREN = 256;
82
83 /**
84 * Number of significant bits per directory level.
85 */
86 static final int BIT_SIZE = 8; // log2(256) = 8
87
88 /**
89 * Maximum number of levels (zero-based)
90 *
91 * (4 * 8 bits = 32 bits, which is the size of an "int", and as
92 * you know, hashcodes in Java are "ints")
93 */
94 static final int MAX_DEPTH = 3; // 4 levels
95
96 /**
97 * Record ids of children pages.
98 */
99 private long[] _children;
100
101 /**
102 * Depth of this directory page, zero-based
103 */
104 private byte _depth;
105
106 /**
107 * PageManager used to persist changes in directory and buckets
108 */
109 private transient RecordManager _recman;
110
111 /**
112 * This directory's record ID in the PageManager. (transient)
113 */
114 private transient long _recid;
115
116
117 /**
118 * Public constructor used by serialization
119 */
120 public HashDirectory()
121 {
122 // empty
123 }
124
125
126 /**
127 * Construct a HashDirectory
128 *
129 * @param depth Depth of this directory page.
130 */
131 HashDirectory( byte depth )
132 {
133 _depth = depth;
134 _children = new long[MAX_CHILDREN];
135 }
136
137
138 /**
139 * Sets persistence context. This method must be called before any
140 * persistence-related operation.
141 *
142 * @param recman RecordManager which stores this directory
143 * @param recid Record id of this directory.
144 */
145 void setPersistenceContext( RecordManager recman, long recid )
146 {
147 this._recman = recman;
148 this._recid = recid;
149 }
150
151
152 /**
153 * Get the record identifier used to load this hashtable.
154 */
155 long getRecid()
156 {
157 return _recid;
158 }
159
160
161 /**
162 * Returns whether or not this directory is empty. A directory
163 * is empty when it no longer contains buckets or sub-directories.
164 */
165 boolean isEmpty()
166 {
167 for ( int i = 0; i < _children.length; i++ )
168 {
169 if ( _children[i] != 0 )
170 {
171 return false;
172 }
173 }
174 return true;
175 }
176
177
178 /**
179 * Returns the value which is associated with the given key. Returns
180 * <code>null</code> if there is not association for this key.
181 *
182 * @param key key whose associated value is to be returned
183 */
184 Object get( Object key )
185 throws IOException
186 {
187 int hash = hashCode( key );
188 long child_recid = _children[hash];
189 if ( child_recid == 0 )
190 {
191 // not bucket/page --> not found
192 return null;
193 }
194 else
195 {
196 HashNode node = ( HashNode ) _recman.fetch( child_recid );
197 // System.out.println("HashDirectory.get() child is : "+node);
198
199 if ( node instanceof HashDirectory )
200 {
201 // recurse into next directory level
202 HashDirectory dir = ( HashDirectory ) node;
203 dir.setPersistenceContext( _recman, child_recid );
204 return dir.get( key );
205 }
206 else
207 {
208 // node is a bucket
209 HashBucket bucket = ( HashBucket ) node;
210 return bucket.getValue( key );
211 }
212 }
213 }
214
215
216 /**
217 * Associates the specified value with the specified key.
218 *
219 * @param key key with which the specified value is to be assocated.
220 * @param value value to be associated with the specified key.
221 * @return object which was previously associated with the given key,
222 * or <code>null</code> if no association existed.
223 */
224 Object put( Object key, Object value )
225 throws IOException
226 {
227 if ( value == null )
228 {
229 return remove( key );
230 }
231 int hash = hashCode( key );
232 long child_recid = _children[hash];
233 if ( child_recid == 0 )
234 {
235 // no bucket/page here yet, let's create a bucket
236 HashBucket bucket = new HashBucket( _depth + 1 );
237
238 // insert (key,value) pair in bucket
239 Object existing = bucket.addElement( key, value );
240
241 long b_recid = _recman.insert( bucket );
242 _children[hash] = b_recid;
243
244 _recman.update( _recid, this );
245
246 // System.out.println("Added: "+bucket);
247 return existing;
248 }
249 else
250 {
251 HashNode node = ( HashNode ) _recman.fetch( child_recid );
252
253 if ( node instanceof HashDirectory )
254 {
255 // recursive insert in next directory level
256 HashDirectory dir = ( HashDirectory ) node;
257 dir.setPersistenceContext( _recman, child_recid );
258 return dir.put( key, value );
259 }
260 else
261 {
262 // node is a bucket
263 HashBucket bucket = ( HashBucket ) node;
264 if ( bucket.hasRoom() )
265 {
266 Object existing = bucket.addElement( key, value );
267 _recman.update( child_recid, bucket );
268 // System.out.println("Added: "+bucket);
269 return existing;
270 }
271 else
272 {
273 // overflow, so create a new directory
274 if ( _depth == MAX_DEPTH )
275 {
276 throw new RuntimeException( I18n.err( I18n.ERR_535, _depth ) );
277 }
278 HashDirectory dir = new HashDirectory( ( byte ) ( _depth + 1 ) );
279 long dir_recid = _recman.insert( dir );
280 dir.setPersistenceContext( _recman, dir_recid );
281
282 _children[hash] = dir_recid;
283 _recman.update( _recid, this );
284
285 // discard overflown bucket
286 _recman.delete( child_recid );
287
288 // migrate existing bucket elements
289 ArrayList keys = bucket.getKeys();
290 ArrayList values = bucket.getValues();
291 int entries = keys.size();
292 for ( int i = 0; i < entries; i++ )
293 {
294 dir.put( keys.get( i ), values.get( i ) );
295 }
296
297 // (finally!) insert new element
298 return dir.put( key, value );
299 }
300 }
301 }
302 }
303
304
305 /**
306 * Remove the value which is associated with the given key. If the
307 * key does not exist, this method simply ignores the operation.
308 *
309 * @param key key whose associated value is to be removed
310 * @return object which was associated with the given key, or
311 * <code>null</code> if no association existed with given key.
312 */
313 Object remove( Object key ) throws IOException
314 {
315 int hash = hashCode( key );
316 long child_recid = _children[hash];
317 if ( child_recid == 0 )
318 {
319 // not bucket/page --> not found
320 return null;
321 }
322 else
323 {
324 HashNode node = ( HashNode ) _recman.fetch( child_recid );
325 // System.out.println("HashDirectory.remove() child is : "+node);
326
327 if ( node instanceof HashDirectory )
328 {
329 // recurse into next directory level
330 HashDirectory dir = ( HashDirectory ) node;
331 dir.setPersistenceContext( _recman, child_recid );
332 Object existing = dir.remove( key );
333 if ( existing != null && dir.isEmpty() )
334 {
335 // delete empty directory
336 _recman.delete( child_recid );
337 _children[hash] = 0;
338 _recman.update( _recid, this );
339 }
340 return existing;
341 }
342 else
343 {
344 // node is a bucket
345 HashBucket bucket = ( HashBucket ) node;
346 Object existing = bucket.removeElement( key );
347 if ( existing != null )
348 {
349 if ( bucket.getElementCount() >= 1 )
350 {
351 _recman.update( child_recid, bucket );
352 }
353 else
354 {
355 // delete bucket, it's empty
356 _recman.delete( child_recid );
357 _children[hash] = 0;
358 _recman.update( _recid, this );
359 }
360 }
361 return existing;
362 }
363 }
364 }
365
366
367 /**
368 * Calculates the hashcode of a key, based on the current directory
369 * depth.
370 */
371 private int hashCode( Object key )
372 {
373 int hashMask = hashMask();
374 int hash = key.hashCode();
375 hash = hash & hashMask;
376 hash = hash >>> ( ( MAX_DEPTH - _depth ) * BIT_SIZE );
377 hash = hash % MAX_CHILDREN;
378 /*
379 System.out.println("HashDirectory.hashCode() is: 0x"
380 +Integer.toHexString(hash)
381 +" for object hashCode() 0x"
382 +Integer.toHexString(key.hashCode()));
383 */
384 return hash;
385 }
386
387
388 /**
389 * Calculates the hashmask of this directory. The hashmask is the
390 * bit mask applied to a hashcode to retain only bits that are
391 * relevant to this directory level.
392 */
393 int hashMask()
394 {
395 int bits = MAX_CHILDREN - 1;
396 int hashMask = bits << ( ( MAX_DEPTH - _depth ) * BIT_SIZE );
397 /*
398 System.out.println("HashDirectory.hashMask() is: 0x"
399 +Integer.toHexString(hashMask));
400 */
401 return hashMask;
402 }
403
404
405 /**
406 * Returns an enumeration of the keys contained in this
407 */
408 FastIterator keys()
409 throws IOException
410 {
411 return new HDIterator( true );
412 }
413
414
415 /**
416 * Returns an enumeration of the values contained in this
417 */
418 FastIterator values()
419 throws IOException
420 {
421 return new HDIterator( false );
422 }
423
424
425 /**
426 * Implement Externalizable interface
427 */
428 public void writeExternal( ObjectOutput out )
429 throws IOException
430 {
431 out.writeByte( _depth );
432 out.writeObject( _children );
433 }
434
435
436 /**
437 * Implement Externalizable interface
438 */
439 public synchronized void readExternal( ObjectInput in )
440 throws IOException, ClassNotFoundException
441 {
442 _depth = in.readByte();
443 _children = ( long[] ) in.readObject();
444 }
445
446 ////////////////////////////////////////////////////////////////////////
447 // INNER CLASS
448 ////////////////////////////////////////////////////////////////////////
449
450 /**
451 * Utility class to enumerate keys/values in a HTree
452 */
453 public class HDIterator
454 extends FastIterator
455 {
456
457 /**
458 * True if we're iterating on keys, False if enumerating on values.
459 */
460 private boolean _iterateKeys;
461
462 /**
463 * Stacks of directories & last enumerated child position
464 */
465 private ArrayList _dirStack;
466 private ArrayList _childStack;
467
468 /**
469 * Current HashDirectory in the hierarchy
470 */
471 private HashDirectory _dir;
472
473 /**
474 * Current child position
475 */
476 private int _child;
477
478 /**
479 * Current bucket iterator
480 */
481 private Iterator _iter;
482
483
484 /**
485 * Construct an iterator on this directory.
486 *
487 * @param iterateKeys True if iteration supplies keys, False
488 * if iterateKeys supplies values.
489 */
490 HDIterator( boolean iterateKeys )
491 throws IOException
492 {
493 _dirStack = new ArrayList();
494 _childStack = new ArrayList();
495 _dir = HashDirectory.this;
496 _child = -1;
497 _iterateKeys = iterateKeys;
498
499 prepareNext();
500 }
501
502
503 /**
504 * Returns the next object.
505 */
506 public Object next()
507 {
508 Object next = null;
509 if ( _iter != null && _iter.hasNext() )
510 {
511 next = _iter.next();
512 }
513 else
514 {
515 try
516 {
517 prepareNext();
518 }
519 catch ( IOException except )
520 {
521 throw new IterationException( except );
522 }
523 if ( _iter != null && _iter.hasNext() )
524 {
525 return next();
526 }
527 }
528 return next;
529 }
530
531
532 /**
533 * Prepare internal state so we can answer <code>hasMoreElements</code>
534 *
535 * Actually, this code prepares an Enumeration on the next
536 * Bucket to enumerate. If no following bucket is found,
537 * the next Enumeration is set to <code>null</code>.
538 */
539 private void prepareNext() throws IOException
540 {
541 long child_recid = 0;
542
543 // find next bucket/directory to enumerate
544 do
545 {
546 _child++;
547 if ( _child >= MAX_CHILDREN )
548 {
549
550 if ( _dirStack.isEmpty() )
551 {
552 // no more directory in the stack, we're finished
553 return;
554 }
555
556 // try next page
557 _dir = ( HashDirectory ) _dirStack.remove( _dirStack.size() - 1 );
558 _child = ( ( Integer ) _childStack.remove( _childStack.size() - 1 ) ).intValue();
559 continue;
560 }
561 child_recid = _dir._children[_child];
562 }
563 while ( child_recid == 0 );
564
565 if ( child_recid == 0 )
566 {
567 throw new Error( "child_recid cannot be 0" );
568 }
569
570 HashNode node = ( HashNode ) _recman.fetch( child_recid );
571 // System.out.println("HDEnumeration.get() child is : "+node);
572
573 if ( node instanceof HashDirectory )
574 {
575 // save current position
576 _dirStack.add( _dir );
577 _childStack.add( Integer.valueOf( _child ) );
578
579 _dir = ( HashDirectory ) node;
580 _child = -1;
581
582 // recurse into
583 _dir.setPersistenceContext( _recman, child_recid );
584 prepareNext();
585 }
586 else
587 {
588 // node is a bucket
589 HashBucket bucket = ( HashBucket ) node;
590 if ( _iterateKeys )
591 {
592 _iter = bucket.getKeys().iterator();
593 }
594 else
595 {
596 _iter = bucket.getValues().iterator();
597 }
598 }
599 }
600 }
601
602 }