Debian Codegraph @

jdbm1/src/main/java/jdbm/btree/BPage.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 2001 (C) Alex Boisvert. All Rights Reserved.
43 * Contributions are Copyright (C) 2001 by their associated contributors.
44 *
45 */
46
47 package jdbm.btree;
48
49
50 import java.io.ByteArrayInputStream;
51 import java.io.ByteArrayOutputStream;
52 import java.io.IOException;
53 import java.io.ObjectInput;
54 import java.io.ObjectInputStream;
55 import java.io.ObjectOutput;
56 import java.io.ObjectOutputStream;
57
58 import jdbm.I18n;
59 import jdbm.helper.Serializer;
60 import jdbm.helper.Tuple;
61 import jdbm.helper.TupleBrowser;
62
63
64 /**
65 * Page of a Btree.
66 * <p>
67 * The page contains a number of key-value pairs. Keys are ordered to allow
68 * dichotomic search.
69 * <p>
70 * If the page is a leaf page, the keys and values are user-defined and
71 * represent entries inserted by the user.
72 * <p>
73 * If the page is non-leaf, each key represents the greatest key in the
74 * underlying BPages and the values are recids pointing to the children BPages.
75 * The only exception is the rightmost BPage, which is considered to have an
76 * "infinite" key value, meaning that any insert will be to the left of this
77 * pseudo-key
78 *
79 * @author <a href="mailto:[email protected]">Alex Boisvert</a>
80 */
81 public class BPage<K, V> implements Serializer
82 {
83 private static final boolean DEBUG = false;
84
85 /** Version id for serialization. */
86 final static long serialVersionUID = 1L;
87
88 /** Parent B+Tree. */
89 transient BTree<K, V> btree;
90
91 /** This BPage's record ID in the PageManager. */
92 protected transient long recordId;
93
94 /** Flag indicating if this is a leaf BPage. */
95 protected boolean isLeaf;
96
97 /** Keys of children nodes */
98 protected K[] keys;
99
100 /** Values associated with keys. (Only valid if leaf BPage) */
101 protected V[] values;
102
103 /** Children pages (recids) associated with keys. (Only valid if non-leaf BPage) */
104 protected long[] children;
105
106 /** Index of first used item at the page */
107 protected int first;
108
109 /** Previous leaf BPage (only if this BPage is a leaf) */
110 protected long previous;
111
112 /** Next leaf BPage (only if this BPage is a leaf) */
113 protected long next;
114
115
116 /**
117 * No-argument constructor used by serialization.
118 */
119 public BPage()
120 {
121 // empty
122 }
123
124
125 /**
126 * Root page overflow constructor
127 */
128 @SuppressWarnings("unchecked")
129 BPage( BTree btree, BPage<K, V> root, BPage<K, V> overflow ) throws IOException
130 {
131 this.btree = btree;
132
133 isLeaf = false;
134
135 first = btree.pageSize - 2;
136
137 keys = ( K[] ) new Object[btree.pageSize];
138 keys[btree.pageSize - 2] = overflow.getLargestKey();
139 keys[btree.pageSize - 1] = root.getLargestKey();
140
141 children = new long[btree.pageSize];
142 children[btree.pageSize - 2] = overflow.recordId;
143 children[btree.pageSize - 1] = root.recordId;
144
145 recordId = btree.recordManager.insert( this, this );
146 }
147
148
149 /**
150 * Root page (first insert) constructor.
151 */
152 @SuppressWarnings("unchecked")
153 // Cannot create an array of generic objects
154 BPage( BTree btree, K key, V value ) throws IOException
155 {
156 this.btree = btree;
157
158 isLeaf = true;
159
160 first = btree.pageSize - 2;
161
162 keys = ( K[] ) new Object[btree.pageSize];
163 keys[btree.pageSize - 2] = key;
164 keys[btree.pageSize - 1] = null; // I am the root BPage for now
165
166 values = ( V[] ) new Object[btree.pageSize];
167 values[btree.pageSize - 2] = value;
168 values[btree.pageSize - 1] = null; // I am the root BPage for now
169
170 recordId = btree.recordManager.insert( this, this );
171 }
172
173
174 /**
175 * Overflow page constructor. Creates an empty BPage.
176 */
177 @SuppressWarnings("unchecked")
178 // Cannot create an array of generic objects
179 BPage( BTree btree, boolean isLeaf ) throws IOException
180 {
181 this.btree = btree;
182
183 this.isLeaf = isLeaf;
184
185 // page will initially be half-full
186 first = btree.pageSize / 2;
187
188 keys = ( K[] ) new Object[btree.pageSize];
189
190 if ( isLeaf )
191 {
192 values = ( V[] ) new Object[btree.pageSize];
193 }
194 else
195 {
196 children = new long[btree.pageSize];
197 }
198
199 recordId = btree.recordManager.insert( this, this );
200 }
201
202
203 /**
204 * Get largest key under this BPage. Null is considered to be the
205 * greatest possible key.
206 */
207 K getLargestKey()
208 {
209 return keys[btree.pageSize - 1];
210 }
211
212
213 /**
214 * @return The record ID
215 */
216 public long getRecordId()
217 {
218 return recordId;
219 }
220
221
222 /**
223 * Set the recordId
224 *
225 * @param recordId The recordId
226 */
227 public void setRecordId( long recordId )
228 {
229 this.recordId = recordId;
230 }
231
232
233 /**
234 * Return true if BPage is empty.
235 */
236 boolean isEmpty()
237 {
238 if ( isLeaf )
239 {
240 return ( first == values.length - 1 );
241 }
242 else
243 {
244 return ( first == children.length - 1 );
245 }
246 }
247
248
249 /**
250 * Return true if BPage is full.
251 */
252 boolean isFull()
253 {
254 return ( first == 0 );
255 }
256
257
258 /**
259 * Find the object associated with the given key.
260 *
261 * @param height Height of the current BPage (zero is leaf page)
262 * @param key The key
263 * @return TupleBrowser positionned just before the given key, or before
264 * next greater key if key isn't found.
265 */
266 TupleBrowser<K, V> find( int height, K key ) throws IOException
267 {
268 int index = this.findChildren( key );
269
270 if ( index < 0 )
271 {
272 index = -( index + 1 );
273 }
274
275 BPage<K, V> child = this;
276
277 while ( !child.isLeaf )
278 {
279 // non-leaf BPage
280 child = child.loadBPage( child.children[index] );
281 index = child.findChildren( key );
282
283 if ( index < 0 )
284 {
285 index = -( index + 1 );
286 }
287 }
288
289 return new Browser( child, index );
290 }
291
292
293 /**
294 * Find first entry and return a browser positioned before it.
295 *
296 * @return TupleBrowser positionned just before the first entry.
297 */
298 TupleBrowser<K, V> findFirst() throws IOException
299 {
300 if ( isLeaf )
301 {
302 return new Browser( this, first );
303 }
304 else
305 {
306 BPage<K, V> child = childBPage( first );
307
308 return child.findFirst();
309 }
310 }
311
312
313 /**
314 * Insert the given key and value.
315 * <p>
316 * Since the Btree does not support duplicate entries, the caller must
317 * specify whether to replace the existing value.
318 *
319 * @param height Height of the current BPage (zero is leaf page)
320 * @param key Insert key
321 * @param value Insert value
322 * @param replace Set to true to replace the existing value, if one exists.
323 * @return Insertion result containing existing value OR a BPage if the key
324 * was inserted and provoked a BPage overflow.
325 */
326 InsertResult<K, V> insert( int height, K key, V value, boolean replace ) throws IOException
327 {
328 InsertResult<K, V> result;
329 long overflow;
330
331 int index = findChildren( key );
332 boolean keyExists = index < 0;
333
334 if ( index < 0 )
335 {
336 index = -( index + 1 );
337 }
338
339 height -= 1;
340
341 if ( height == 0 )
342 {
343 result = new InsertResult<K, V>();
344
345 // inserting on a leaf BPage
346 overflow = -1;
347
348 if ( DEBUG )
349 {
350 System.out.println( "Bpage.insert() Insert on leaf Bpage key=" + key + " value=" + value + " index="
351 + index );
352 }
353
354 // This is to deal with the special case where the key already exists.
355 // In this case, the index will contain the key's position, but as a
356 // negative number
357 if ( keyExists )
358 {
359 // key already exists
360 if ( DEBUG )
361 {
362 System.out.println( "Bpage.insert() Key already exists." );
363 }
364
365 result.existing = values[index];
366
367 if ( replace )
368 {
369 values[index] = value;
370 btree.recordManager.update( recordId, this, this );
371 }
372
373 // return the existing key
374 return result;
375 }
376 }
377 else
378 {
379 // non-leaf BPage
380 BPage<K, V> child = childBPage( index );
381 result = child.insert( height, key, value, replace );
382
383 if ( result.existing != null )
384 {
385 // return existing key, if any.
386 return result;
387 }
388
389 if ( result.overflow == null )
390 {
391 // no overflow means we're done with insertion
392 return result;
393 }
394
395 // there was an overflow, we need to insert the overflow page
396 // on this BPage
397 if ( DEBUG )
398 {
399 System.out.println( "BPage.insert() Overflow page: " + result.overflow.recordId );
400 }
401
402 key = result.overflow.getLargestKey();
403 overflow = result.overflow.recordId;
404
405 // update child's largest key
406 keys[index] = child.getLargestKey();
407
408 // clean result so we can reuse it
409 result.overflow = null;
410 }
411
412 // if we get here, we need to insert a new entry on the BPage
413 // before children[ index ]
414 if ( !isFull() )
415 {
416 if ( height == 0 )
417 {
418 insertEntry( this, index - 1, key, value );
419 }
420 else
421 {
422 insertChild( this, index - 1, key, overflow );
423 }
424
425 btree.recordManager.update( recordId, this, this );
426 return result;
427 }
428
429 // page is full, we must divide the page
430 int half = btree.pageSize >> 1;
431 BPage<K, V> newPage = new BPage<K, V>( btree, isLeaf );
432
433 if ( index < half )
434 {
435 // move lower-half of entries to overflow BPage,
436 // including new entry
437 if ( DEBUG )
438 {
439 System.out
440 .println( "Bpage.insert() move lower-half of entries to overflow BPage, including new entry." );
441 }
442
443 if ( height == 0 )
444 {
445 copyEntries( this, 0, newPage, half, index );
446 setEntry( newPage, half + index, key, value );
447 copyEntries( this, index, newPage, half + index + 1, half - index - 1 );
448 }
449 else
450 {
451 copyChildren( this, 0, newPage, half, index );
452 setChild( newPage, half + index, key, overflow );
453 copyChildren( this, index, newPage, half + index + 1, half - index - 1 );
454 }
455 }
456 else
457 {
458 // move lower-half of entries to overflow BPage,
459 // new entry stays on this BPage
460 if ( DEBUG )
461 {
462 System.out.println( "Bpage.insert() move lower-half of entries to overflow BPage. New entry stays" );
463 }
464
465 if ( height == 0 )
466 {
467 copyEntries( this, 0, newPage, half, half );
468 copyEntries( this, half, this, half - 1, index - half );
469 setEntry( this, index - 1, key, value );
470 }
471 else
472 {
473 copyChildren( this, 0, newPage, half, half );
474 copyChildren( this, half, this, half - 1, index - half );
475 setChild( this, index - 1, key, overflow );
476 }
477 }
478
479 first = half - 1;
480
481 // nullify lower half of entries
482 for ( int i = 0; i < first; i++ )
483 {
484 if ( height == 0 )
485 {
486 setEntry( this, i, null, null );
487 }
488 else
489 {
490 setChild( this, i, null, -1 );
491 }
492 }
493
494 if ( isLeaf )
495 {
496 // link newly created BPage
497 newPage.previous = previous;
498 newPage.next = recordId;
499
500 if ( previous != 0 )
501 {
502 BPage<K, V> previousBPage = loadBPage( previous );
503 previousBPage.next = newPage.recordId;
504 btree.recordManager.update( previous, previousBPage, this );
505 }
506
507 previous = newPage.recordId;
508 }
509
510 btree.recordManager.update( recordId, this, this );
511 btree.recordManager.update( newPage.recordId, newPage, this );
512
513 result.overflow = newPage;
514 return result;
515 }
516
517
518 /**
519 * Remove the entry associated with the given key.
520 *
521 * @param height Height of the current BPage (zero is leaf page)
522 * @param key Removal key
523 * @return Remove result object
524 */
525 RemoveResult<V> remove( int height, K key ) throws IOException
526 {
527 RemoveResult<V> result;
528
529 int half = btree.pageSize / 2;
530 int index = findChildren( key );
531 boolean keyExists = index < 0;
532
533 if ( index < 0 )
534 {
535 index = -( index + 1 );
536 }
537
538 height -= 1;
539
540 if ( height == 0 )
541 {
542 // remove leaf entry
543 if ( !keyExists )
544 {
545 throw new IllegalArgumentException( I18n.err( I18n.ERR_514, key ) );
546 }
547
548 result = new RemoveResult<V>();
549 result.value = values[index];
550 removeEntry( this, index );
551
552 // update this BPage
553 btree.recordManager.update( recordId, this, this );
554 }
555 else
556 {
557 // recurse into Btree to remove entry on a children page
558 BPage<K, V> child = childBPage( index );
559 result = child.remove( height, key );
560
561 // update children
562 keys[index] = child.getLargestKey();
563 btree.recordManager.update( recordId, this, this );
564
565 if ( result.underflow )
566 {
567 // underflow occured
568 if ( child.first != half + 1 )
569 {
570 throw new IllegalStateException( I18n.err( I18n.ERR_513, "1" ) );
571 }
572
573 if ( index < children.length - 1 )
574 {
575 // exists greater brother page
576 BPage<K, V> brother = childBPage( index + 1 );
577 int bfirst = brother.first;
578
579 if ( bfirst < half )
580 {
581 // steal entries from "brother" page
582 int steal = ( half - bfirst + 1 ) / 2;
583 brother.first += steal;
584 child.first -= steal;
585
586 if ( child.isLeaf )
587 {
588 copyEntries( child, half + 1, child, half + 1 - steal, half - 1 );
589 copyEntries( brother, bfirst, child, 2 * half - steal, steal );
590 }
591 else
592 {
593 copyChildren( child, half + 1, child, half + 1 - steal, half - 1 );
594 copyChildren( brother, bfirst, child, 2 * half - steal, steal );
595 }
596
597 for ( int i = bfirst; i < bfirst + steal; i++ )
598 {
599 if ( brother.isLeaf )
600 {
601 setEntry( brother, i, null, null );
602 }
603 else
604 {
605 setChild( brother, i, null, -1 );
606 }
607 }
608
609 // update child's largest key
610 keys[index] = child.getLargestKey();
611
612 // no change in previous/next BPage
613
614 // update BPages
615 btree.recordManager.update( recordId, this, this );
616 btree.recordManager.update( brother.recordId, brother, this );
617 btree.recordManager.update( child.recordId, child, this );
618
619 }
620 else
621 {
622 // move all entries from page "child" to "brother"
623 if ( brother.first != half )
624 {
625 throw new IllegalStateException( I18n.err( I18n.ERR_513, "2" ) );
626 }
627
628 brother.first = 1;
629
630 if ( child.isLeaf )
631 {
632 copyEntries( child, half + 1, brother, 1, half - 1 );
633 }
634 else
635 {
636 copyChildren( child, half + 1, brother, 1, half - 1 );
637 }
638
639 btree.recordManager.update( brother.recordId, brother, this );
640
641 // remove "child" from current BPage
642 if ( isLeaf )
643 {
644 copyEntries( this, first, this, first + 1, index - first );
645 setEntry( this, first, null, null );
646 }
647 else
648 {
649 copyChildren( this, first, this, first + 1, index - first );
650 setChild( this, first, null, -1 );
651 }
652
653 first += 1;
654 btree.recordManager.update( recordId, this, this );
655
656 // re-link previous and next BPages
657 if ( child.previous != 0 )
658 {
659 BPage<K, V> prev = loadBPage( child.previous );
660 prev.next = child.next;
661 btree.recordManager.update( prev.recordId, prev, this );
662 }
663
664 if ( child.next != 0 )
665 {
666 BPage<K, V> next = loadBPage( child.next );
667 next.previous = child.previous;
668 btree.recordManager.update( next.recordId, next, this );
669 }
670
671 // delete "child" BPage
672 btree.recordManager.delete( child.recordId );
673 }
674 }
675 else
676 {
677 // page "brother" is before "child"
678 BPage<K, V> brother = childBPage( index - 1 );
679 int bfirst = brother.first;
680
681 if ( bfirst < half )
682 {
683 // steal entries from "brother" page
684 int steal = ( half - bfirst + 1 ) / 2;
685 brother.first += steal;
686 child.first -= steal;
687
688 if ( child.isLeaf )
689 {
690 copyEntries( brother, 2 * half - steal, child, half + 1 - steal, steal );
691 copyEntries( brother, bfirst, brother, bfirst + steal, 2 * half - bfirst - steal );
692 }
693 else
694 {
695 copyChildren( brother, 2 * half - steal, child, half + 1 - steal, steal );
696 copyChildren( brother, bfirst, brother, bfirst + steal, 2 * half - bfirst - steal );
697 }
698
699 for ( int i = bfirst; i < bfirst + steal; i++ )
700 {
701 if ( brother.isLeaf )
702 {
703 setEntry( brother, i, null, null );
704 }
705 else
706 {
707 setChild( brother, i, null, -1 );
708 }
709 }
710
711 // update brother's largest key
712 keys[index - 1] = brother.getLargestKey();
713
714 // no change in previous/next BPage
715
716 // update BPages
717 btree.recordManager.update( recordId, this, this );
718 btree.recordManager.update( brother.recordId, brother, this );
719 btree.recordManager.update( child.recordId, child, this );
720
721 }
722 else
723 {
724 // move all entries from page "brother" to "child"
725 if ( brother.first != half )
726 {
727 throw new IllegalStateException( I18n.err( I18n.ERR_513, "3" ) );
728 }
729
730 child.first = 1;
731
732 if ( child.isLeaf )
733 {
734 copyEntries( brother, half, child, 1, half );
735 }
736 else
737 {
738 copyChildren( brother, half, child, 1, half );
739 }
740
741 btree.recordManager.update( child.recordId, child, this );
742
743 // remove "brother" from current BPage
744 if ( isLeaf )
745 {
746 copyEntries( this, first, this, first + 1, index - 1 - first );
747 setEntry( this, first, null, null );
748 }
749 else
750 {
751 copyChildren( this, first, this, first + 1, index - 1 - first );
752 setChild( this, first, null, -1 );
753 }
754
755 first += 1;
756 btree.recordManager.update( recordId, this, this );
757
758 // re-link previous and next BPages
759 if ( brother.previous != 0 )
760 {
761 BPage<K, V> prev = loadBPage( brother.previous );
762 prev.next = brother.next;
763 btree.recordManager.update( prev.recordId, prev, this );
764 }
765
766 if ( brother.next != 0 )
767 {
768 BPage<K, V> next = loadBPage( brother.next );
769 next.previous = brother.previous;
770 btree.recordManager.update( next.recordId, next, this );
771 }
772
773 // delete "brother" BPage
774 btree.recordManager.delete( brother.recordId );
775 }
776 }
777 }
778 }
779
780 // underflow if page is more than half-empty
781 result.underflow = first > half;
782
783 return result;
784 }
785
786
787 /**
788 * Find the first children node with a key equal or greater than the given
789 * key.
790 *
791 * @return index of first children with equal or greater key. If the
792 * key already exists, the index value will be negative
793 */
794 private int findChildren( K key )
795 {
796 int left = first;
797 int right = btree.pageSize - 1;
798
799 // binary search
800 while ( left < right )
801 {
802 int middle = ( left + right ) >>> 1;
803
804 int comp = compare( keys[middle], key );
805
806 if ( comp < 0 )
807 {
808 left = middle + 1;
809 }
810 else if ( comp > 0 )
811 {
812 right = middle;
813 }
814 else
815 {
816 // Special case : the key already exists,
817 // we can return immediately
818 return -middle - 1;
819 }
820 }
821
822 if ( left == right )
823 {
824 // Special case : we don't know if the key is present
825 if ( compare( keys[left], key ) == 0 )
826 {
827 return -right - 1;
828 }
829 }
830
831 return right;
832 }
833
834
835 /**
836 * Insert entry at given position.
837 */
838 private void insertEntry( BPage<K, V> page, int index, K key, V value )
839 {
840 K[] keys = page.keys;
841 V[] values = page.values;
842 int start = page.first;
843 int count = index - page.first + 1;
844
845 // shift entries to the left
846 System.arraycopy( keys, start, keys, start - 1, count );
847 System.arraycopy( values, start, values, start - 1, count );
848 page.first -= 1;
849 keys[index] = key;
850 values[index] = value;
851 }
852
853
854 /**
855 * Insert child at given position.
856 */
857 private void insertChild( BPage<K, V> page, int index, K key, long child )
858 {
859 K[] keys = page.keys;
860 long[] children = page.children;
861 int start = page.first;
862 int count = index - page.first + 1;
863
864 // shift entries to the left
865 System.arraycopy( keys, start, keys, start - 1, count );
866 System.arraycopy( children, start, children, start - 1, count );
867 page.first -= 1;
868 keys[index] = key;
869 children[index] = child;
870 }
871
872
873 /**
874 * Remove entry at given position.
875 */
876 private void removeEntry( BPage<K, V> page, int index )
877 {
878 K[] keys = page.keys;
879 V[] values = page.values;
880 int start = page.first;
881 int count = index - page.first;
882
883 System.arraycopy( keys, start, keys, start + 1, count );
884 keys[start] = null;
885 System.arraycopy( values, start, values, start + 1, count );
886 values[start] = null;
887 page.first++;
888 }
889
890
891 /**
892 * Set the entry at the given index.
893 */
894 private void setEntry( BPage<K, V> page, int index, K key, V value )
895 {
896 page.keys[index] = key;
897 page.values[index] = value;
898 }
899
900
901 /**
902 * Set the child BPage recordId at the given index.
903 */
904 private void setChild( BPage<K, V> page, int index, K key, long recid )
905 {
906 page.keys[index] = key;
907 page.children[index] = recid;
908 }
909
910
911 /**
912 * Copy entries between two BPages
913 */
914 private void copyEntries( BPage<K, V> source, int indexSource, BPage<K, V> dest, int indexDest, int count )
915 {
916 System.arraycopy( source.keys, indexSource, dest.keys, indexDest, count );
917 System.arraycopy( source.values, indexSource, dest.values, indexDest, count );
918 }
919
920
921 /**
922 * Copy child BPage recids between two BPages
923 */
924 private void copyChildren( BPage<K, V> source, int indexSource, BPage<K, V> dest, int indexDest, int count )
925 {
926 System.arraycopy( source.keys, indexSource, dest.keys, indexDest, count );
927 System.arraycopy( source.children, indexSource, dest.children, indexDest, count );
928 }
929
930
931 /**
932 * Return the child BPage at given index.
933 */
934 // False positive
935 @SuppressWarnings("PMD.UnnecessaryFinalModifier")
936 BPage<K, V> childBPage( int index ) throws IOException
937 {
938 return loadBPage( children[index] );
939 }
940
941
942 /**
943 * Load the BPage at the given recordId.
944 */
945 @SuppressWarnings("unchecked")
946 // The fetch method returns an Object
947 private BPage<K, V> loadBPage( long recid ) throws IOException
948 {
949 BPage<K, V> child = ( BPage<K, V> ) btree.recordManager.fetch( recid, this );
950 child.recordId = recid;
951 child.btree = btree;
952
953 return child;
954 }
955
956
957 private final int compare( K value1, K value2 )
958 {
959 if ( value1 == value2 )
960 {
961 return 0;
962 }
963
964 if ( value1 == null )
965 {
966 return 1;
967 }
968
969 if ( value2 == null )
970 {
971 return -1;
972 }
973
974 return btree.getComparator().compare( value1, value2 );
975 }
976
977
978 static byte[] readByteArray( ObjectInput in ) throws IOException
979 {
980 int len = in.readInt();
981
982 if ( len < 0 )
983 {
984 return null;
985 }
986
987 byte[] buf = new byte[len];
988 in.readFully( buf );
989
990 return buf;
991 }
992
993
994 static void writeByteArray( ObjectOutput out, byte[] buf ) throws IOException
995 {
996 if ( buf == null )
997 {
998 out.writeInt( -1 );
999 }
1000 else
1001 {
1002 out.writeInt( buf.length );
1003 out.write( buf );
1004 }
1005 }
1006
1007
1008 /**
1009 * Dump the structure of the tree on the screen. This is used for debugging
1010 * purposes only.
1011 */
1012 private void dump( int height )
1013 {
1014 String prefix = "";
1015
1016 for ( int i = 0; i < height; i++ )
1017 {
1018 prefix += " ";
1019 }
1020
1021 System.out.println( prefix + "-------------------------------------- BPage recordId=" + recordId );
1022 System.out.println( prefix + "first=" + first );
1023
1024 for ( int i = 0; i < btree.pageSize; i++ )
1025 {
1026 if ( isLeaf )
1027 {
1028 System.out.println( prefix + "BPage [" + i + "] " + keys[i] + " " + values[i] );
1029 }
1030 else
1031 {
1032 System.out.println( prefix + "BPage [" + i + "] " + keys[i] + " " + children[i] );
1033 }
1034 }
1035
1036 System.out.println( prefix + "--------------------------------------" );
1037 }
1038
1039
1040 /**
1041 * Recursively dump the state of the BTree on screen. This is used for
1042 * debugging purposes only.
1043 */
1044 void dumpRecursive( int height, int level ) throws IOException
1045 {
1046 height -= 1;
1047 level += 1;
1048
1049 if ( height > 0 )
1050 {
1051 for ( int i = first; i < btree.pageSize; i++ )
1052 {
1053 if ( keys[i] == null )
1054 {
1055 break;
1056 }
1057
1058 BPage<K, V> child = childBPage( i );
1059 child.dump( level );
1060 child.dumpRecursive( height, level );
1061 }
1062 }
1063 }
1064
1065
1066 /**
1067 * Assert the ordering of the keys on the BPage. This is used for testing
1068 * purposes only.
1069 */
1070 private void assertConsistency()
1071 {
1072 for ( int i = first; i < btree.pageSize - 1; i++ )
1073 {
1074 if ( compare( keys[i], keys[i + 1] ) >= 0 )
1075 {
1076 dump( 0 );
1077 throw new Error( I18n.err( I18n.ERR_515 ) );
1078 }
1079 }
1080 }
1081
1082
1083 /**
1084 * Recursively assert the ordering of the BPage entries on this page
1085 * and sub-pages. This is used for testing purposes only.
1086 */
1087 void assertConsistencyRecursive( int height ) throws IOException
1088 {
1089 assertConsistency();
1090
1091 if ( --height > 0 )
1092 {
1093 for ( int i = first; i < btree.pageSize; i++ )
1094 {
1095 if ( keys[i] == null )
1096 {
1097 break;
1098 }
1099
1100 BPage<K, V> child = childBPage( i );
1101
1102 if ( compare( keys[i], child.getLargestKey() ) != 0 )
1103 {
1104 dump( 0 );
1105 child.dump( 0 );
1106 throw new Error( I18n.err( I18n.ERR_516 ) );
1107 }
1108
1109 child.assertConsistencyRecursive( height );
1110 }
1111 }
1112 }
1113
1114
1115 /**
1116 * Deserialize the content of an object from a byte array.
1117 *
1118 * @param serialized Byte array representation of the object
1119 * @return deserialized object
1120 *
1121 */
1122 @SuppressWarnings("unchecked")
1123 // Cannot create an array of generic objects
1124 public BPage<K, V> deserialize( byte[] serialized ) throws IOException
1125 {
1126 ByteArrayInputStream bais;
1127 ObjectInputStream ois;
1128 BPage<K, V> bpage;
1129
1130 bpage = new BPage<K, V>();
1131 bais = new ByteArrayInputStream( serialized );
1132 ois = new ObjectInputStream( bais );
1133
1134 bpage.isLeaf = ois.readBoolean();
1135
1136 if ( bpage.isLeaf )
1137 {
1138 bpage.previous = ois.readLong();
1139 bpage.next = ois.readLong();
1140 }
1141
1142 bpage.first = ois.readInt();
1143
1144 bpage.keys = ( K[] ) new Object[btree.pageSize];
1145
1146 try
1147 {
1148 for ( int i = bpage.first; i < btree.pageSize; i++ )
1149 {
1150 if ( btree.keySerializer == null )
1151 {
1152 bpage.keys[i] = ( K ) ois.readObject();
1153 }
1154 else
1155 {
1156 serialized = readByteArray( ois );
1157
1158 if ( serialized != null )
1159 {
1160 bpage.keys[i] = ( K ) btree.keySerializer.deserialize( serialized );
1161 }
1162 }
1163 }
1164 }
1165 catch ( ClassNotFoundException except )
1166 {
1167 throw new IOException( except.getLocalizedMessage() );
1168 }
1169
1170 if ( bpage.isLeaf )
1171 {
1172 bpage.values = ( V[] ) new Object[btree.pageSize];
1173
1174 try
1175 {
1176 for ( int i = bpage.first; i < btree.pageSize; i++ )
1177 {
1178 if ( btree.valueSerializer == null )
1179 {
1180 bpage.values[i] = ( V ) ois.readObject();
1181 }
1182 else
1183 {
1184 serialized = readByteArray( ois );
1185
1186 if ( serialized != null )
1187 {
1188 bpage.values[i] = ( V ) btree.valueSerializer.deserialize( serialized );
1189 }
1190 }
1191 }
1192 }
1193 catch ( ClassNotFoundException except )
1194 {
1195 throw new IOException( except.getLocalizedMessage() );
1196 }
1197 }
1198 else
1199 {
1200 bpage.children = new long[btree.pageSize];
1201
1202 for ( int i = bpage.first; i < btree.pageSize; i++ )
1203 {
1204 bpage.children[i] = ois.readLong();
1205 }
1206 }
1207
1208 ois.close();
1209 bais.close();
1210
1211 return bpage;
1212 }
1213
1214
1215 /**
1216 * Serialize the content of an object into a byte array.
1217 *
1218 * @param obj Object to serialize
1219 * @return a byte array representing the object's state
1220 *
1221 */
1222 @SuppressWarnings("unchecked")
1223 // The serialize signature requires an Object, so we have to cast
1224 public byte[] serialize( Object obj ) throws IOException
1225 {
1226 byte[] serialized;
1227 ByteArrayOutputStream baos;
1228 ObjectOutputStream oos;
1229 BPage<K, V> bpage;
1230 byte[] data;
1231
1232 // note: It is assumed that BPage instance doing the serialization is the parent
1233 // of the BPage object being serialized.
1234 bpage = ( BPage<K, V> ) obj;
1235 baos = new ByteArrayOutputStream();
1236 oos = new ObjectOutputStream( baos );
1237
1238 oos.writeBoolean( bpage.isLeaf );
1239
1240 if ( bpage.isLeaf )
1241 {
1242 oos.writeLong( bpage.previous );
1243 oos.writeLong( bpage.next );
1244 }
1245
1246 oos.writeInt( bpage.first );
1247
1248 for ( int i = bpage.first; i < btree.pageSize; i++ )
1249 {
1250 if ( btree.keySerializer == null )
1251 {
1252 oos.writeObject( bpage.keys[i] );
1253 }
1254 else
1255 {
1256 if ( bpage.keys[i] != null )
1257 {
1258 serialized = btree.keySerializer.serialize( bpage.keys[i] );
1259 writeByteArray( oos, serialized );
1260 }
1261 else
1262 {
1263 writeByteArray( oos, null );
1264 }
1265 }
1266 }
1267
1268 if ( bpage.isLeaf )
1269 {
1270 for ( int i = bpage.first; i < btree.pageSize; i++ )
1271 {
1272 if ( btree.valueSerializer == null )
1273 {
1274 oos.writeObject( bpage.values[i] );
1275 }
1276 else
1277 {
1278 if ( bpage.values[i] != null )
1279 {
1280 serialized = btree.valueSerializer.serialize( bpage.values[i] );
1281 writeByteArray( oos, serialized );
1282 }
1283 else
1284 {
1285 writeByteArray( oos, null );
1286 }
1287 }
1288 }
1289 }
1290 else
1291 {
1292 for ( int i = bpage.first; i < btree.pageSize; i++ )
1293 {
1294 oos.writeLong( bpage.children[i] );
1295 }
1296 }
1297
1298 oos.flush();
1299 data = baos.toByteArray();
1300 oos.close();
1301 baos.close();
1302 return data;
1303 }
1304
1305 /** STATIC INNER CLASS
1306 * Result from insert() method call. If the insertion has created
1307 * a new page, it will be contained in the overflow field.
1308 * If the inserted element already exist, then we will store
1309 * the existing element.
1310 */
1311 static class InsertResult<K, V>
1312 {
1313
1314 /**
1315 * Overflow page.
1316 */
1317 BPage<K, V> overflow;
1318
1319 /**
1320 * Existing value for the insertion key.
1321 */
1322 V existing;
1323 }
1324
1325 /** STATIC INNER CLASS
1326 * Result from remove() method call. If we had to removed a BPage,
1327 * it will be stored into the underflow field.
1328 */
1329 static class RemoveResult<V>
1330 {
1331 /**
1332 * Set to true if underlying pages underflowed
1333 */
1334 boolean underflow;
1335
1336 /**
1337 * Removed entry value
1338 */
1339 V value;
1340 }
1341
1342 /** PRIVATE INNER CLASS
1343 * Browser to traverse leaf BPages.
1344 */
1345 class Browser extends TupleBrowser<K, V>
1346 {
1347 /** Current page. */
1348 private BPage<K, V> page;
1349
1350 /**
1351 * Current index in the page. The index positionned on the next
1352 * tuple to return.
1353 */
1354 private int index;
1355
1356
1357 /**
1358 * Create a browser.
1359 *
1360 * @param page Current page
1361 * @param index Position of the next tuple to return.
1362 */
1363 Browser( BPage<K, V> page, int index )
1364 {
1365 this.page = page;
1366 this.index = index;
1367 }
1368
1369
1370 /**
1371 * Get the next Tuple in the current BTree. We have 3 cases to deal with :
1372 * 1) we are at the end of the btree. We will return false, the tuple won't be set.
1373 * 2) we are in the middle of a page : grab the values and store them into the tuple
1374 * 3) we are at the end of the page : grab the next page, and get the tuple from it.
1375 *
1376 * @return true if we have found a tumple, false otherwise.
1377 */
1378 public boolean getNext( Tuple<K, V> tuple ) throws IOException
1379 {
1380 // First, check that we are within a page
1381 if ( index < page.btree.pageSize )
1382 {
1383 // We are. Now check that we have a Tuple
1384 if ( page.keys[index] == null )
1385 {
1386 // no : reached end of the tree.
1387 return false;
1388 }
1389 }
1390 // all the tuple for this page has been read. Move to the
1391 // next page, if we have one.
1392 else if ( page.next != 0 )
1393 {
1394 // move to next page
1395 page = page.loadBPage( page.next );
1396 index = page.first;
1397 }
1398
1399 tuple.setKey( page.keys[index] );
1400 tuple.setValue( page.values[index] );
1401 index++;
1402
1403 return true;
1404 }
1405
1406
1407 public boolean getPrevious( Tuple<K, V> tuple ) throws IOException
1408 {
1409 if ( index == page.first )
1410 {
1411 if ( page.previous != 0 )
1412 {
1413 page = page.loadBPage( page.previous );
1414 index = page.btree.pageSize;
1415 }
1416 else
1417 {
1418 // reached beginning of the tree
1419 return false;
1420 }
1421 }
1422
1423 index--;
1424 tuple.setKey( page.keys[index] );
1425 tuple.setValue( page.values[index] );
1426
1427 return true;
1428 }
1429 }
1430
1431
1432 public String toString()
1433 {
1434 StringBuilder sb = new StringBuilder();
1435
1436 if ( isLeaf )
1437 {
1438 sb.append( "Leaf(" );
1439 }
1440 else
1441 {
1442 sb.append( "Node(" );
1443 }
1444
1445 sb.append( keys.length );
1446 sb.append( ") : [" );
1447
1448 if ( isLeaf )
1449 {
1450 boolean isFirst = true;
1451 int index = 0;
1452
1453 for ( K key : keys )
1454 {
1455 if ( isFirst )
1456 {
1457 isFirst = false;
1458 }
1459 else
1460 {
1461 sb.append( ", " );
1462 }
1463
1464 sb.append( "<" );
1465 sb.append( String.valueOf( key ) );
1466 sb.append( "/" );
1467 sb.append( values[index] );
1468 sb.append( ">" );
1469
1470 index++;
1471 }
1472 }
1473 else
1474 {
1475 boolean isFirst = true;
1476 //int index = 0;
1477
1478 for ( K key : keys )
1479 {
1480 if ( isFirst )
1481 {
1482 isFirst = false;
1483 }
1484 else
1485 {
1486 sb.append( ", " );
1487 }
1488
1489 sb.append( "<" );
1490 sb.append( key );
1491 //sb.append( "/" );
1492 //sb.append( values[index] );
1493 sb.append( ">" );
1494 }
1495 }
1496
1497 sb.append( "]\n" );
1498 return sb.toString();
1499 }
1500 }