File: DBKVarLenRecordsFile.m

package info (click to toggle)
gworkspace 1.1.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 15,124 kB
  • sloc: objc: 71,982; sh: 488; makefile: 43
file content (507 lines) | stat: -rw-r--r-- 11,116 bytes parent folder | download
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
/* DBKVarLenRecordsFile.m
 *  
 * Copyright (C) 2005-2012 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., 31 Milk Street #960789 Boston, MA 02196 USA.
 */

#import "DBKVarLenRecordsFile.h"
#import "DBKBTreeNode.h"

#define FIRST_OFFSET 512

@implementation	DBKVarLenRecordsFile

- (void)dealloc
{
  if (handle) {
    [handle closeFile];
    RELEASE (handle);
  }
  RELEASE (freeOffsetsTree);

  RELEASE (cacheDict);
  RELEASE (offsets);
            
  [super dealloc];
}

- (id)initWithPath:(NSString *)path
       cacheLength:(unsigned)len
{
  self = [super init];
  
  if (self) {
    NSMutableData *data = [NSMutableData dataWithCapacity: 1];
    NSFileManager *fm = [NSFileManager defaultManager];
    BOOL exists, isdir;  
    
    exists = [fm fileExistsAtPath: path isDirectory: &isdir];

    if (exists == NO) {
      if ([fm createDirectoryAtPath: path attributes: nil] == NO) {
        DESTROY (self);
        [NSException raise: NSInvalidArgumentException
		                format: @"cannot create directory at: %@", path];     
        return self;
      }    
    
      isdir = YES;
    }
    
    if (isdir == NO) {
      DESTROY (self);
      [NSException raise: NSInvalidArgumentException
		              format: @"%@ is not a directory!", path];     
      return self;
    } else {
      NSString *recordsPath = [path stringByAppendingPathComponent: @"records"];
      NSString *freePath = [path stringByAppendingPathComponent: @"free"];

      exists = [fm fileExistsAtPath: recordsPath isDirectory: &isdir];

      if (isdir) {
        DESTROY (self);
        [NSException raise: NSInvalidArgumentException
		                format: @"%@ is a directory!", recordsPath];     
        return self;
      } else if (exists == NO) {
        if ([fm createFileAtPath: recordsPath contents: nil attributes: nil] == NO) {
          DESTROY (self);
          [NSException raise: NSInvalidArgumentException
		                  format: @"cannot create file at: %@", recordsPath];     
          return self;
        }
      }

      cacheDict = [NSMutableDictionary new];
      offsets = [NSMutableArray new];
      maxlen = len;
      autoflush = YES;

      ulen = sizeof(unsigned);
      llen = sizeof(unsigned long);

      handle = [NSFileHandle fileHandleForUpdatingAtPath: recordsPath];
      RETAIN (handle);
      
      [data setLength: FIRST_OFFSET];
      [handle writeData: data];
      
      [handle seekToEndOfFile];
      eof = [handle offsetInFile];

      freeOffsetsTree = [[DBKBTree alloc] initWithPath: freePath 
                                                 order: 16 
                                              delegate: self];
    }
  }
  
  return self;
}

- (void)setAutoflush:(BOOL)value
{
  autoflush = value;
}

- (BOOL)autoflush
{
  return autoflush;
}

- (void)flushIfNeeded
{
  if (([cacheDict count] >= maxlen) && autoflush) {
    [self flush];
  }
}

- (void)flush
{
  int i;

  for (i = 0; i < [offsets count]; i++) {
    CREATE_AUTORELEASE_POOL (arp);
    NSNumber *offset = [offsets objectAtIndex: i];
    NSData *dictdata = [cacheDict objectForKey: offset];
    unsigned datalen = [dictdata length];  
    NSMutableData *data = [NSMutableData dataWithCapacity: 1];
    unsigned long ofst;
    
    [data appendBytes: &datalen length: ulen];
    [data appendData: dictdata];
    
    [handle seekToFileOffset: [offset unsignedLongValue]];
    [handle writeData: data];    
    
    ofst = [handle offsetInFile];
    
    if (ofst > eof) {
      eof = ofst;
    }
    
    RELEASE (arp);
  }
  
  [cacheDict removeAllObjects];
  [offsets removeAllObjects];
}

- (NSData *)dataAtOffset:(NSNumber *)offset
{
  NSData *data = [cacheDict objectForKey: offset];
  
  if (data == nil) {
    unsigned long ofst = [offset unsignedLongValue];
    unsigned datalen;
  
    [handle seekToFileOffset: ofst];
    data = [handle readDataOfLength: ulen];
    [data getBytes: &datalen range: NSMakeRange(0, ulen)];
    data = [handle readDataOfLength: datalen];
  } 

  return data;
}

- (NSNumber *)writeData:(NSData *)data
{
  NSNumber *offset = [self offsetForNewData: data];

  [self writeData: data atOffset: offset];
    
  return offset;
}

- (void)writeData:(NSData *)data
         atOffset:(NSNumber *)offset
{
  int index = [self insertionIndexForOffset: offset];
  
  if (index != -1) {
    [offsets insertObject: offset atIndex: index];
  }

  [cacheDict setObject: data forKey: offset];

  if (([cacheDict count] > maxlen) && autoflush) {
    [self flush];
  }
}

- (void)deleteDataAtOffset:(NSNumber *)offset
{
  NSData *data = [cacheDict objectForKey: offset];
  
  if (data) {  
    [cacheDict removeObjectForKey: offset];
    [offsets removeObject: offset];

  } else {
    CREATE_AUTORELEASE_POOL(arp);
    unsigned long ofst = [offset unsignedLongValue];
    NSData *lndata;
    unsigned datalen;
    DBKBFreeNodeEntry *entry;    
    
    [handle seekToFileOffset: ofst];
    lndata = [handle readDataOfLength: ulen];
    [lndata getBytes: &datalen range: NSMakeRange(0, ulen)];
            
    entry = [DBKBFreeNodeEntry entryWithLength: datalen atOffset: ofst];
  
    [freeOffsetsTree begin];
    [freeOffsetsTree insertKey: entry];  
    [freeOffsetsTree end];  
        
    RELEASE (arp);
  }
}

- (NSNumber *)offsetForNewData:(NSData *)data
{
  NSNumber *offset = [self freeOffsetForData: data];
  
  if (offset == nil) {  
    unsigned count = [offsets count];
    unsigned long coffs = 0;
  
    if (count > 0) {
      NSNumber *key = [offsets objectAtIndex: (count - 1)];
      NSData *dictData = [cacheDict objectForKey: key];

      coffs = [key unsignedLongValue] + ulen + [dictData length];
    }
    
    offset = [NSNumber numberWithUnsignedLong: ((coffs > eof) ? coffs : eof)];
  }
  
  return offset;
}

- (int)insertionIndexForOffset:(NSNumber *)offset
{
  CREATE_AUTORELEASE_POOL(arp);
  unsigned count = [offsets count]; 
  int ins = 0;
  
  if (count) {
    NSNumber *ofst = nil;
    int first = 0;
    int last = count;
    int pos = 0; 
    NSComparisonResult result;

    while (1) {
      if (first == last) {
        ins = first;
        break;
      }

      pos = (first + last) / 2;
      ofst = [offsets objectAtIndex: pos];
      
      result = [ofst compare: offset];

      if (result == NSOrderedSame) {
        RELEASE (arp);
        return -1;
        
      } else if (result == NSOrderedAscending) { 
        first = pos + 1;
      } else {
        last = pos;	
      }
    } 
  } 
  
  RELEASE (arp);
    
  return ins;  
}

- (NSNumber *)freeOffsetForData:(NSData *)data
{
  CREATE_AUTORELEASE_POOL(arp);
  DBKBFreeNodeEntry *entry = [DBKBFreeNodeEntry entryWithLength: [data length] atOffset: 0];
  DBKBFreeNodeEntry *freeEntry = nil;
  NSNumber *offset = nil;
  DBKBTreeNode *node;
  BOOL exists;
  NSUInteger index;
  
  [freeOffsetsTree begin];
    
  node = [freeOffsetsTree nodeOfKey: entry getIndex: &index didExist: &exists];
  
  if (node && [[node keys] count]) {
    freeEntry = [node successorKeyInNode: &node forKeyAtIndex: index];
  } 

  if (freeEntry) {
    offset = RETAIN ([freeEntry offsetNum]);
    [freeOffsetsTree deleteKey: freeEntry];
  }

  [freeOffsetsTree end];
  
  RELEASE (arp);
  
  return AUTORELEASE (offset);
}


//
// DBKBTreeDelegate methods
//
- (unsigned long)nodesize
{
  return 512;
} 

- (NSArray *)keysFromData:(NSData *)data
               withLength:(unsigned *)dlen
{
  NSMutableArray *keys = [NSMutableArray array];
  NSRange range;
  unsigned kcount;
  unsigned i;
  
  range = NSMakeRange(0, ulen);
  [data getBytes: &kcount range: range];
  range.location += ulen;
  
  range.length = llen;

  for (i = 0; i < kcount; i++) {
    CREATE_AUTORELEASE_POOL(arp);
    DBKBFreeNodeEntry *entry;
    unsigned long length;
    unsigned long offset;
  
    [data getBytes: &length range: range];
    range.location += llen;
    [data getBytes: &offset range: range];
    range.location += llen;
    
    entry = [[DBKBFreeNodeEntry alloc] initWithLength: length atOffset: offset];
    [keys addObject: entry];
    RELEASE (entry);
    
    RELEASE (arp);
  }
  
  *dlen = range.location;
  
  return keys;
}

- (NSData *)dataFromKeys:(NSArray *)keys
{
  CREATE_AUTORELEASE_POOL(arp);
  NSMutableData *data = [NSMutableData dataWithCapacity: 1];
  unsigned kcount = [keys count];
  unsigned i;
  
  [data appendData: [NSData dataWithBytes: &kcount length: ulen]];
    
  for (i = 0; i < kcount; i++) {
    DBKBFreeNodeEntry *entry = [keys objectAtIndex: i];
    unsigned long length = [entry length];
    unsigned long offset = [entry offset];
  
    [data appendData: [NSData dataWithBytes: &length length: llen]];
    [data appendData: [NSData dataWithBytes: &offset length: llen]];
  }
  
  RETAIN (data);
  RELEASE (arp);
    
  return [data autorelease];  
}

- (NSComparisonResult)compareNodeKey:(id)akey 
                             withKey:(id)bkey
{
  NSComparisonResult result = [[akey lengthNum] compare: [bkey lengthNum]];

  if (result == NSOrderedSame) {
    result = [[akey offsetNum] compare: [bkey offsetNum]];
  }
  
  return result;
}

@end


@implementation	DBKBFreeNodeEntry

- (void)dealloc
{
  RELEASE (lengthNum);
  RELEASE (offsetNum);      
  [super dealloc];
}

+ (id)entryWithLength:(unsigned long)len
             atOffset:(unsigned long)ofst
{
  return AUTORELEASE ([[DBKBFreeNodeEntry alloc] initWithLength: len 
                                                       atOffset: ofst]);
}

- (id)initWithLength:(unsigned long)len
            atOffset:(unsigned long)ofst
{
  self = [super init];

  if (self) {
    ASSIGN (lengthNum, [NSNumber numberWithUnsignedLong: len]);
    ASSIGN (offsetNum, [NSNumber numberWithUnsignedLong: ofst]);
  }
  
  return self;
}

- (NSNumber *)lengthNum 
{
  return lengthNum;
}

- (unsigned long)length
{
  return [lengthNum unsignedLongValue];
}

- (NSNumber *)offsetNum 
{
  return offsetNum;
}

- (unsigned long)offset
{
  return [offsetNum unsignedLongValue];
}

- (NSUInteger)hash
{
  return ([lengthNum hash] + [offsetNum hash]);
}

- (BOOL)isEqual:(id)other
{
  if (other == self) {
    return YES;
  }
  if ([other isKindOfClass: [DBKBFreeNodeEntry class]]) {
    return ([lengthNum isEqual: [other lengthNum]] 
                      && [offsetNum isEqual: [other offsetNum]]);
  }
  return NO;
}

@end