1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
|
/* DBKBTree.m
*
* Copyright (C) 2005 Free Software Foundation, Inc.
*
* Author: Enrico Sersale <enrico@imago.ro>
* Date: June 2005
*
* This file is part of the GNUstep GWorkspace application
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111 USA.
*/
#include "DBKBTree.h"
#include "DBKBTreeNode.h"
#include "DBKFreeNodesPage.h"
#include "DBKFixLenRecordsFile.h"
#define MIN_ORDER 3
#define HEADLEN 512
#define FREE_NPAGE_LEN 512
NSRecursiveLock *dbkbtree_lock = nil;
@implementation DBKBTree
+ (void)initialize
{
static BOOL initialized = NO;
if (initialized == NO) {
if ([self class] == [DBKBTree class]) {
dbkbtree_lock = [NSRecursiveLock new];
}
initialized = YES;
}
}
- (void)dealloc
{
if (file) {
[file close];
RELEASE (file);
}
RELEASE (headData);
RELEASE (root);
RELEASE (rootOffset);
RELEASE (freeNodesPage);
RELEASE (unsavedNodes);
[super dealloc];
}
- (id)initWithPath:(NSString *)path
order:(int)ord
delegate:(id)deleg
{
self = [super init];
if (self) {
if (ord < MIN_ORDER) {
DESTROY (self);
[NSException raise: NSInvalidArgumentException
format: @"the order must be at least %i", MIN_ORDER];
return self;
}
if (deleg == nil) {
DESTROY (self);
[NSException raise: NSInvalidArgumentException
format: @"DBKBTree requires a delegate"];
return self;
}
if ([deleg conformsToProtocol: @protocol(DBKBTreeDelegate)] == NO) {
DESTROY (self);
[NSException raise: NSInvalidArgumentException
format: @"the delegate doesn't implement the DBKBTreeDelegate protocol"];
return self;
}
file = [[DBKFixLenRecordsFile alloc] initWithPath: path cacheLength: 10000];
[file setAutoflush: YES];
order = ord;
minkeys = order - 1;
maxkeys = order * 2 - 1;
ulen = sizeof(unsigned);
llen = sizeof(unsigned long);
delegate = deleg;
nodesize = [delegate nodesize];
unsavedNodes = [[NSMutableSet alloc] initWithCapacity: 1];
ASSIGN (rootOffset, [NSNumber numberWithUnsignedLong: HEADLEN]);
fnpageOffset = HEADLEN + nodesize;
headData = [[NSMutableData alloc] initWithCapacity: 1];
[self readHeader];
[self createRootNode];
[self createFreeNodesPage];
begin = NO;
}
return self;
}
- (void)begin
{
if (begin == YES) {
[NSException raise: NSInternalInconsistencyException
format: @"begin already called"];
}
begin = YES;
}
- (void)end
{
NSArray *subnodes = [root subnodes];
int i;
if (begin == NO) {
[NSException raise: NSInternalInconsistencyException
format: @"end without begin"];
}
[self saveNodes];
[file flush];
for (i = 0; i < [subnodes count]; i++) {
[[subnodes objectAtIndex: i] unload];
}
begin = NO;
}
- (void)readHeader
{
NSData *data = [file dataOfLength: HEADLEN
atOffset: [NSNumber numberWithUnsignedLong: 0L]];
[headData setLength: 0];
/* TODO add the version */
if ([data length] == HEADLEN) {
[headData appendData: data];
} else { // new file
[self writeHeader];
}
}
- (void)writeHeader
{
[headData setLength: HEADLEN];
[file writeData: headData
atOffset: [NSNumber numberWithUnsignedLong: 0L]];
[file flush];
}
- (void)createRootNode
{
NSData *data;
root = [[DBKBTreeNode alloc] initInTree: self
withParent: nil
atOffset: rootOffset];
data = [self dataForNode: root];
if (data) {
[root setNodeData: data];
} else {
[root setLoaded];
}
[self saveNode: root];
[file flush];
}
- (void)setRoot:(DBKBTreeNode *)newroot
{
ASSIGN (root, newroot);
[root setRoot];
[root setOffset: rootOffset];
[root setLoaded];
[self addUnsavedNode: root];
}
- (DBKBTreeNode *)root
{
return root;
}
- (DBKBTreeNode *)insertKey:(id)key
{
CREATE_AUTORELEASE_POOL(arp);
BOOL autoflush = [file autoflush];
DBKBTreeNode *insnode = nil;
int index;
BOOL exists;
[self checkBegin];
[file setAutoflush: NO];
index = [root indexForKey: key existing: &exists];
if (exists == NO) {
if ([[root keys] count] == maxkeys) {
DBKBTreeNode *newroot = [[DBKBTreeNode alloc] initInTree: self
withParent: nil
atOffset: rootOffset];
[root setOffset: [self offsetForNewNode]];
[self addUnsavedNode: root];
[newroot addSubnode: root];
[self setRoot: newroot];
RELEASE (newroot);
[newroot splitSubnodeAtIndex: 0];
insnode = [self insertKey: key inNode: newroot];
} else {
insnode = [self insertKey: key inNode: root];
}
}
[self saveNodes];
[file setAutoflush: autoflush];
[file flushIfNeeded];
TEST_RETAIN (insnode);
RELEASE (arp);
return TEST_AUTORELEASE (insnode);
}
- (DBKBTreeNode *)insertKey:(id)key
inNode:(DBKBTreeNode *)node
{
if ([node isLoaded] == NO) {
[node loadNodeData];
}
if ([node isLeaf]) {
if ([node insertKey: key]) {
[node setLoaded];
[self addUnsavedNode: node];
return node;
}
} else {
int index;
BOOL exists;
index = [node indexForKey: key existing: &exists];
if (exists == NO) {
DBKBTreeNode *subnode = [[node subnodes] objectAtIndex: index];
BOOL insert = NO;
if ([subnode isLoaded] == NO) {
[subnode loadNodeData];
}
if ([[subnode keys] count] == maxkeys) {
[subnode indexForKey: key existing: &exists];
if (exists == NO) {
[node splitSubnodeAtIndex: index];
index = [node indexForKey: key existing: &exists];
subnode = [[node subnodes] objectAtIndex: index];
if ([subnode isLoaded] == NO) {
[subnode loadNodeData];
}
insert = YES;
}
} else {
insert = YES;
}
if (insert) {
return [self insertKey: key inNode: subnode];
}
}
}
return nil;
}
- (DBKBTreeNode *)nodeOfKey:(id)key
getIndex:(int *)index
{
CREATE_AUTORELEASE_POOL(arp);
DBKBTreeNode *node = root;
BOOL exists;
[self checkBegin];
*index = [node indexForKey: key existing: &exists];
while (exists == NO) {
NSArray *subnodes = [node subnodes];
if ([subnodes count]) {
node = [subnodes objectAtIndex: *index];
if ([node isLoaded] == NO) {
[node loadNodeData];
}
*index = [node indexForKey: key existing: &exists];
} else {
RELEASE (arp);
return nil;
}
}
RETAIN (node);
RELEASE (arp);
return [node autorelease];
}
- (DBKBTreeNode *)nodeOfKey:(id)key
getIndex:(int *)index
didExist:(BOOL *)exists
{
CREATE_AUTORELEASE_POOL(arp);
DBKBTreeNode *node = root;
[self checkBegin];
*index = [node indexForKey: key existing: exists];
while (*exists == NO) {
NSArray *subnodes = [node subnodes];
if ([subnodes count]) {
node = [subnodes objectAtIndex: *index];
if ([node isLoaded] == NO) {
[node loadNodeData];
}
*index = [node indexForKey: key existing: exists];
} else {
*index = [node indexForKey: key existing: exists];
break;
}
}
RETAIN (node);
RELEASE (arp);
return [node autorelease];
}
- (DBKBTreeNode *)nodeOfKey:(id)key
{
DBKBTreeNode *node;
BOOL exists;
int index;
[self checkBegin];
node = [self nodeOfKey: key getIndex: &index didExist: &exists];
return (exists ? node : nil);
}
- (NSArray *)keysGreaterThenKey:(id)akey
andLesserThenKey:(id)bkey
{
CREATE_AUTORELEASE_POOL(pool);
NSMutableArray *keys = [NSMutableArray array];
DBKBTreeNode *node;
id key;
BOOL exists;
int index;
[self checkBegin];
key = akey;
node = [self nodeOfKey: key getIndex: &index didExist: &exists];
if (exists == NO) {
key = [node predecessorKeyInNode: &node forKeyAtIndex: index];
if (key == nil) {
key = [node minKeyInSubnode: &node];
[keys addObject: key];
} else {
node = [self nodeOfKey: key getIndex: &index didExist: &exists];
}
}
while (node != nil) {
CREATE_AUTORELEASE_POOL(arp);
key = [node successorKeyInNode: &node forKeyAtIndex: index];
if (key == nil) {
break;
}
if (bkey && ([delegate compareNodeKey: key withKey: bkey] != NSOrderedAscending)) {
break;
}
index = [node indexOfKey: key];
[keys addObject: key];
RELEASE (arp);
}
RETAIN (keys);
RELEASE (pool);
return [keys autorelease];
}
- (BOOL)replaceKey:(id)key
withKey:(id)newkey
{
DBKBTreeNode *node;
BOOL exists;
int index;
[self checkBegin];
node = [self nodeOfKey: key getIndex: &index didExist: &exists];
if (exists == NO) {
return (([self insertKey: newkey] != nil) ? YES : NO);
} else {
[node replaceKeyAtIndex: index withKey: newkey];
return YES;
}
return NO;
}
- (BOOL)deleteKey:(id)key
{
CREATE_AUTORELEASE_POOL(arp);
DBKBTreeNode *node;
int index;
[self checkBegin];
node = [self nodeOfKey: key getIndex: &index];
if (node) {
BOOL autoflush = [file autoflush];
[file setAutoflush: NO];
if ([self deleteKey: key atIndex: index ofNode: node]) {
if ([[root keys] count] == 0) {
NSArray *subnodes = [root subnodes];
if ([subnodes count]) {
DBKBTreeNode *nd = [subnodes objectAtIndex: 0];
if ([nd isLoaded] == NO) {
[nd loadNodeData];
}
RETAIN (nd);
[root removeSubnodeAtIndex: 0];
[self nodeWillFreeOffset: [nd offset]];
[self setRoot: nd];
RELEASE (nd);
}
}
[self saveNodes];
[file setAutoflush: autoflush];
[file flushIfNeeded];
RELEASE (arp);
return YES;
}
[file setAutoflush: autoflush];
}
RELEASE (arp);
return NO;
}
- (BOOL)deleteKey:(id)key
atIndex:(int)index
ofNode:(DBKBTreeNode *)node
{
DBKBTreeNode *chknode = nil;
if ([node isLeaf] == NO) {
DBKBTreeNode *scnode;
id sckey;
sckey = [node successorKeyInNode: &scnode forKeyAtIndex: index];
if (sckey) {
[node replaceKeyAtIndex: index withKey: sckey];
[self addUnsavedNode: node];
[scnode removeKey: sckey];
[self addUnsavedNode: scnode];
chknode = scnode;
} else {
return NO;
}
} else {
[node removeKeyAtIndex: index];
[self addUnsavedNode: node];
chknode = node;
}
while ([[chknode keys] count] < minkeys) {
DBKBTreeNode *chkparent = [chknode parent];
if (chkparent) {
int chkind = [chkparent indexOfSubnode: chknode];
DBKBTreeNode *sibling;
if (chkind == 0) {
sibling = [chknode rightSibling];
if (sibling && ([sibling isLoaded] == NO)) {
[sibling loadNodeData];
}
if (sibling && ([[sibling keys] count] > minkeys)) {
[chknode borrowFromRightSibling: sibling];
} else {
[chknode mergeWithBestSibling];
}
} else if (chkind == ([[chkparent subnodes] count] - 1)) {
sibling = [chknode leftSibling];
if (sibling && ([sibling isLoaded] == NO)) {
[sibling loadNodeData];
}
if (sibling && ([[sibling keys] count] > minkeys)) {
[chknode borrowFromLeftSibling: sibling];
} else {
[chknode mergeWithBestSibling];
}
} else {
BOOL borrowed = NO;
sibling = [chknode leftSibling];
if (sibling && ([sibling isLoaded] == NO)) {
[sibling loadNodeData];
}
if (sibling && ([[sibling keys] count] > minkeys)) {
[chknode borrowFromLeftSibling: sibling];
borrowed = YES;
} else {
sibling = [chknode rightSibling];
if (sibling && ([sibling isLoaded] == NO)) {
[sibling loadNodeData];
}
if (sibling && ([[sibling keys] count] > minkeys)) {
[chknode borrowFromRightSibling: sibling];
borrowed = YES;
}
}
if (borrowed == NO) {
[chknode mergeWithBestSibling];
}
}
chknode = chkparent;
chkparent = [chknode parent];
} else {
break;
}
}
return YES;
}
- (NSNumber *)offsetForNewNode
{
NSMutableData *data = [NSMutableData dataWithLength: nodesize];
unsigned long ofst = [freeNodesPage getFreeOffset];
NSNumber *offset;
if (ofst == 0) {
offset = [file offsetForNewData];
} else {
offset = [NSNumber numberWithUnsignedLong: ofst];
}
[file writeData: data atOffset: offset];
return offset;
}
- (unsigned long)offsetForFreeNodesPage
{
NSMutableData *data = [NSMutableData dataWithCapacity: 1];
unsigned long prevOffset = [freeNodesPage currentPageOffset];
NSNumber *offset = [file offsetForNewData];
unsigned long ofs = [offset unsignedLongValue];
[data appendData: [NSData dataWithBytes: &ofs length: llen]];
[data appendData: [NSData dataWithBytes: &prevOffset length: llen]];
[data setLength: FREE_NPAGE_LEN];
[file writeData: data atOffset: offset];
return ofs;
}
- (void)nodeWillFreeOffset:(NSNumber *)offset
{
if ([offset isEqual: rootOffset] == NO) {
[freeNodesPage addFreeOffset: [offset unsignedLongValue]];
}
}
- (void)createFreeNodesPage
{
NSMutableData *data = [NSMutableData dataWithCapacity: 1];
NSData *page = [file dataOfLength: FREE_NPAGE_LEN
atOffset: [NSNumber numberWithUnsignedLong: fnpageOffset]];
[data appendData: page];
if ([data length] != FREE_NPAGE_LEN) {
[data setLength: 0];
[data appendData: [NSData dataWithBytes: &fnpageOffset length: llen]];
[data setLength: FREE_NPAGE_LEN];
[file writeData: data
atOffset: [NSNumber numberWithUnsignedLong: fnpageOffset]];
[file flush];
}
freeNodesPage = [[DBKFreeNodesPage alloc] initInTree: self
withFile: file
atOffset: fnpageOffset
length: FREE_NPAGE_LEN];
}
- (NSArray *)keysFromData:(NSData *)data
withLength:(unsigned *)dlen
{
return [delegate keysFromData: data withLength: dlen];
}
- (NSData *)dataFromKeys:(NSArray *)keys
{
return [delegate dataFromKeys: keys];
}
- (NSComparisonResult)compareNodeKey:(id)akey
withKey:(id)bkey
{
return [delegate compareNodeKey: akey withKey: bkey];
}
- (NSData *)dataForNode:(DBKBTreeNode *)node
{
NSData *data = [file dataOfLength: nodesize atOffset: [node offset]];
if ([data length] == nodesize) {
unsigned keyscount;
[data getBytes: &keyscount range: NSMakeRange(0, ulen)];
if (keyscount != 0) {
return data;
}
}
return nil;
}
- (void)addUnsavedNode:(DBKBTreeNode *)node
{
[unsavedNodes addObject: node];
}
- (void)saveNodes
{
NSEnumerator *enumerator = [unsavedNodes objectEnumerator];
DBKBTreeNode *node;
while ((node = [enumerator nextObject])) {
[self saveNode: node];
}
[unsavedNodes removeAllObjects];
[freeNodesPage writeCurrentPage];
}
- (void)synchronize
{
[file flush];
}
- (void)saveNode:(DBKBTreeNode *)node
{
CREATE_AUTORELEASE_POOL (arp);
NSMutableData *data = [NSMutableData dataWithCapacity: 1];
[data appendData: [node nodeData]];
[data setLength: nodesize];
[file writeData: data atOffset: [node offset]];
RELEASE (arp);
}
- (unsigned)order
{
return order;
}
- (void)checkBegin
{
if (begin == NO) {
[NSException raise: NSInternalInconsistencyException
format: @"begin not called!"];
}
}
@end
|