File: HFController.m

package info (click to toggle)
sameboy 1.0.2%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 10,528 kB
  • sloc: ansic: 29,948; objc: 22,249; asm: 1,424; pascal: 1,373; makefile: 1,065; xml: 111
file content (1905 lines) | stat: -rw-r--r-- 83,672 bytes parent folder | download | duplicates (2)
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
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
//
//  HFController.m
//  HexFiend_2
//
//  Copyright 2007 ridiculous_fish. All rights reserved.
//

#import <HexFiend/HFController.h>
#import <HexFiend/HFRepresenter_Internal.h>
#import <HexFiend/HFByteArray_Internal.h>
#import <HexFiend/HFFullMemoryByteArray.h>
#import <HexFiend/HFBTreeByteArray.h>
#import <HexFiend/HFFullMemoryByteSlice.h>
#import <HexFiend/HFSharedMemoryByteSlice.h>
#import <objc/runtime.h>
#import <objc/message.h>
#import <objc/objc-auto.h>

/* Used for the anchor range and location */
#define NO_SELECTION ULLONG_MAX

#define VALIDATE_SELECTION() [self _ensureSelectionIsValid]

#define BENCHMARK_BYTEARRAYS 0

#define BEGIN_TRANSACTION() NSUInteger token = [self beginPropertyChangeTransaction]
#define END_TRANSACTION() [self endPropertyChangeTransaction:token]

static const CGFloat kScrollMultiplier = (CGFloat)1.5;

static const CFTimeInterval kPulseDuration = .2;

static void *KVOContextChangesAreLocked = &KVOContextChangesAreLocked;

NSString * const HFPrepareForChangeInFileNotification = @"HFPrepareForChangeInFileNotification";
NSString * const HFChangeInFileByteArrayKey = @"HFChangeInFileByteArrayKey";
NSString * const HFChangeInFileModifiedRangesKey = @"HFChangeInFileModifiedRangesKey";
NSString * const HFChangeInFileShouldCancelKey = @"HFChangeInFileShouldCancelKey";
NSString * const HFChangeInFileHintKey = @"HFChangeInFileHintKey";

NSString * const HFControllerDidChangePropertiesNotification = @"HFControllerDidChangePropertiesNotification";
NSString * const HFControllerChangedPropertiesKey = @"HFControllerChangedPropertiesKey";


typedef NS_ENUM(NSInteger, HFControllerSelectAction) {
    eSelectResult,
    eSelectAfterResult,
    ePreserveSelection,
    NUM_SELECTION_ACTIONS
};

@interface HFController (ForwardDeclarations)
- (void)_commandInsertByteArrays:(NSArray *)byteArrays inRanges:(NSArray *)ranges withSelectionAction:(HFControllerSelectAction)selectionAction;
- (void)_removeUndoManagerNotifications;
- (void)_removeAllUndoOperations;
- (void)_registerUndoOperationForInsertingByteArrays:(NSArray *)byteArrays inRanges:(NSArray *)ranges withSelectionAction:(HFControllerSelectAction)selectionAction;

- (void)_updateBytesPerLine;
- (void)_updateDisplayedRange;
@end

@interface NSEvent (HFLionStuff)
- (CGFloat)scrollingDeltaY;
- (BOOL)hasPreciseScrollingDeltas;
- (CGFloat)deviceDeltaY;
@end

static inline Class preferredByteArrayClass(void) {
    return [HFBTreeByteArray class];
}

@implementation HFController

- (void)_sharedInit {
    selectedContentsRanges = [[NSMutableArray alloc] initWithObjects:[HFRangeWrapper withRange:HFRangeMake(0, 0)], nil];
    byteArray = [[preferredByteArrayClass() alloc] init];
    [byteArray addObserver:self forKeyPath:@"changesAreLocked" options:0 context:KVOContextChangesAreLocked];
    selectionAnchor = NO_SELECTION;
    undoOperations = [[NSMutableSet alloc] init];
}

- (instancetype)init {
    self = [super init];
    [self _sharedInit];
    bytesPerLine = 16;
    bytesPerColumn = 1;
    _hfflags.editable = YES;
    _hfflags.antialias = YES;
    _hfflags.showcallouts = YES;
    _hfflags.hideNullBytes = NO;
    _hfflags.selectable = YES;
    representers = [[NSMutableArray alloc] init];
    [self setFont:[NSFont fontWithName:HFDEFAULT_FONT size:HFDEFAULT_FONTSIZE]];
    return self;
}

- (void)dealloc {
    [representers makeObjectsPerformSelector:@selector(_setController:) withObject:nil];
    [representers release];
    [selectedContentsRanges release];
    [self _removeUndoManagerNotifications];
    [self _removeAllUndoOperations];
    [undoOperations release];
    [undoManager release];
    [undoCoalescer release];
    [_font release];
    [byteArray removeObserver:self forKeyPath:@"changesAreLocked"];
    [byteArray release];
    [cachedData release];
    [additionalPendingTransactions release];
    [super dealloc];
}

- (void)encodeWithCoder:(NSCoder *)coder {
    HFASSERT([coder allowsKeyedCoding]);
    [coder encodeObject:representers forKey:@"HFRepresenters"];
    [coder encodeInt64:bytesPerLine forKey:@"HFBytesPerLine"];
    [coder encodeInt64:bytesPerColumn forKey:@"HFBytesPerColumn"];
    [coder encodeObject:_font forKey:@"HFFont"];
    [coder encodeDouble:lineHeight forKey:@"HFLineHeight"];
    [coder encodeBool:_hfflags.antialias forKey:@"HFAntialias"];
    [coder encodeBool:_hfflags.colorbytes forKey:@"HFColorBytes"];
    [coder encodeBool:_hfflags.showcallouts forKey:@"HFShowCallouts"];
    [coder encodeBool:_hfflags.hideNullBytes forKey:@"HFHidesNullBytes"];
    [coder encodeBool:_hfflags.livereload forKey:@"HFLiveReload"];
    [coder encodeInt:_hfflags.editMode forKey:@"HFEditMode"];
    [coder encodeBool:_hfflags.editable forKey:@"HFEditable"];
    [coder encodeBool:_hfflags.selectable forKey:@"HFSelectable"];
}

- (instancetype)initWithCoder:(NSCoder *)coder {
    HFASSERT([coder allowsKeyedCoding]);
    self = [super init];
    [self _sharedInit];
    bytesPerLine = (NSUInteger)[coder decodeInt64ForKey:@"HFBytesPerLine"];
    bytesPerColumn = (NSUInteger)[coder decodeInt64ForKey:@"HFBytesPerColumn"];
    _font = [[coder decodeObjectForKey:@"HFFont"] retain];
    lineHeight = (CGFloat)[coder decodeDoubleForKey:@"HFLineHeight"];
    _hfflags.antialias = [coder decodeBoolForKey:@"HFAntialias"];
    _hfflags.colorbytes = [coder decodeBoolForKey:@"HFColorBytes"];
    _hfflags.livereload = [coder decodeBoolForKey:@"HFLiveReload"];
    
    if ([coder containsValueForKey:@"HFEditMode"])
        _hfflags.editMode = [coder decodeIntForKey:@"HFEditMode"];
    else {
        _hfflags.editMode = ([coder decodeBoolForKey:@"HFOverwriteMode"]
                             ? HFOverwriteMode : HFInsertMode);
    }

    _hfflags.editable = [coder decodeBoolForKey:@"HFEditable"];
    _hfflags.selectable = [coder decodeBoolForKey:@"HFSelectable"];
    _hfflags.hideNullBytes = [coder decodeBoolForKey:@"HFHidesNullBytes"];
    representers = [[coder decodeObjectForKey:@"HFRepresenters"] retain];
    return self;
}

- (NSArray *)representers {
    return [[representers copy] autorelease];
}

- (void)notifyRepresentersOfChanges:(HFControllerPropertyBits)bits {
    FOREACH(HFRepresenter*, rep, representers) {
        [rep controllerDidChange:bits];
    }
    
    /* Post the HFControllerDidChangePropertiesNotification */
    NSNumber *number = [[NSNumber alloc] initWithUnsignedInteger:bits];
    NSDictionary *userInfo = [[NSDictionary alloc] initWithObjects:&number forKeys:(id *)&HFControllerChangedPropertiesKey count:1];
    [number release];
    [[NSNotificationCenter defaultCenter] postNotificationName:HFControllerDidChangePropertiesNotification object:self userInfo:userInfo];
    [userInfo release];
}

- (void)_firePropertyChanges {
    NSMutableArray *pendingTransactions = additionalPendingTransactions;
    NSUInteger pendingTransactionCount = [pendingTransactions count];
    additionalPendingTransactions = nil;
    HFControllerPropertyBits propertiesToUpdate = propertiesToUpdateInCurrentTransaction;
    propertiesToUpdateInCurrentTransaction = 0;
    if (pendingTransactionCount > 0 || propertiesToUpdate != 0) {
        BEGIN_TRANSACTION();
        while (pendingTransactionCount--) {
            HFControllerPropertyBits propertiesInThisTransaction = [pendingTransactions[0] unsignedIntegerValue];
            [pendingTransactions removeObjectAtIndex:0];
            HFASSERT(propertiesInThisTransaction != 0);
            [self notifyRepresentersOfChanges:propertiesInThisTransaction];
        }
        [pendingTransactions release];
        if (propertiesToUpdate) {
            [self notifyRepresentersOfChanges:propertiesToUpdate];
        }
        END_TRANSACTION();
    }
}

/* Inserts a "fence" so that all prior property change bits will be complete before any new ones */
- (void)_insertPropertyChangeFence {
    if (currentPropertyChangeToken == 0) {
        HFASSERT(additionalPendingTransactions == nil);
        /* There can be no prior property changes */
        HFASSERT(propertiesToUpdateInCurrentTransaction == 0);
        return;
    }
    if (propertiesToUpdateInCurrentTransaction == 0) {
        /* Nothing to fence */
        return;
    }
    if (additionalPendingTransactions == nil) additionalPendingTransactions = [[NSMutableArray alloc] init];
    [additionalPendingTransactions addObject:@(propertiesToUpdateInCurrentTransaction)];
    propertiesToUpdateInCurrentTransaction = 0;
}

- (void)_addPropertyChangeBits:(HFControllerPropertyBits)bits {
    propertiesToUpdateInCurrentTransaction |= bits;
    if (currentPropertyChangeToken == 0) {
        [self _firePropertyChanges];
    }
}

- (NSUInteger)beginPropertyChangeTransaction {
    HFASSERT(currentPropertyChangeToken < NSUIntegerMax);
    return ++currentPropertyChangeToken;
}

- (void)endPropertyChangeTransaction:(NSUInteger)token {
    if (currentPropertyChangeToken != token) {
        [NSException raise:NSInvalidArgumentException format:@"endPropertyChangeTransaction passed token %lu, but expected token %lu", (unsigned long)token, (unsigned long)currentPropertyChangeToken];
    }
    HFASSERT(currentPropertyChangeToken > 0);
    if (--currentPropertyChangeToken == 0) [self _firePropertyChanges];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (context == KVOContextChangesAreLocked) {
        HFASSERT([keyPath isEqual:@"changesAreLocked"]);
        [self _addPropertyChangeBits:HFControllerEditable];
    }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

- (void)addRepresenter:(HFRepresenter *)representer {
    REQUIRE_NOT_NULL(representer);
    HFASSERT([representers indexOfObjectIdenticalTo:representer] == NSNotFound);
    HFASSERT([representer controller] == nil);
    [representer _setController:self];
    [representers addObject:representer];
    [representer controllerDidChange: -1];
}

- (void)removeRepresenter:(HFRepresenter *)representer {
    REQUIRE_NOT_NULL(representer);    
    HFASSERT([representers indexOfObjectIdenticalTo:representer] != NSNotFound);
    [representers removeObjectIdenticalTo:representer];
    [representer _setController:nil];
}

- (HFRange)_maximumDisplayedRangeSet {
    unsigned long long contentsLength = [self contentsLength];
    HFRange maximumDisplayedRangeSet = HFRangeMake(0, HFRoundUpToNextMultipleSaturate(contentsLength, bytesPerLine));
    return maximumDisplayedRangeSet;
}

- (unsigned long long)totalLineCount {
    return HFDivideULLRoundingUp(HFRoundUpToNextMultipleSaturate([self contentsLength] - 1, bytesPerLine), bytesPerLine);
}

- (HFFPRange)displayedLineRange {
#if ! NDEBUG
    HFASSERT(displayedLineRange.location >= 0);
    HFASSERT(displayedLineRange.length >= 0);
    HFASSERT(displayedLineRange.location + displayedLineRange.length <= HFULToFP([self totalLineCount]));
#endif
    return displayedLineRange;
}

- (void)setDisplayedLineRange:(HFFPRange)range {
#if ! NDEBUG
    HFASSERT(range.location >= 0);
    HFASSERT(range.length >= 0);
#endif
    if (range.location + range.length > HFULToFP([self totalLineCount])) {
        range.location = [self totalLineCount] - range.length;
        if (range.location < 0) {
            return;
        }
    }
    if (! HFFPRangeEqualsRange(range, displayedLineRange)) {
        displayedLineRange = range;
        [self _addPropertyChangeBits:HFControllerDisplayedLineRange];
    }
}

- (CGFloat)lineHeight {
    return lineHeight;
}

- (void)setFont:(NSFont *)val {
    if (val != _font) {
        CGFloat priorLineHeight = [self lineHeight];
        
        [_font release];
        _font = [val copy];
        
        NSLayoutManager *manager = [[NSLayoutManager alloc] init];
        lineHeight = [manager defaultLineHeightForFont:_font];
        [manager release];
        
        HFControllerPropertyBits bits = HFControllerFont;
        if (lineHeight != priorLineHeight) bits |= HFControllerLineHeight;
        [self _addPropertyChangeBits:bits];
        [self _insertPropertyChangeFence];
        [self _addPropertyChangeBits:HFControllerViewSizeRatios];
        [self _updateDisplayedRange];
    }
}

- (BOOL)shouldAntialias {
    return _hfflags.antialias;
}

- (void)setShouldAntialias:(BOOL)antialias {
    antialias = !! antialias;
    if (antialias != _hfflags.antialias) {
        _hfflags.antialias = antialias;
        [self _addPropertyChangeBits:HFControllerAntialias];
    }
}

- (BOOL)shouldColorBytes {
    return _hfflags.colorbytes;
}

- (void)setShouldColorBytes:(BOOL)colorbytes {
    colorbytes = !! colorbytes;
    if (colorbytes != _hfflags.colorbytes) {
        _hfflags.colorbytes = colorbytes;
        [self _addPropertyChangeBits:HFControllerColorBytes];
    }
}

- (BOOL)shouldShowCallouts {
    return _hfflags.showcallouts;
}

- (void)setShouldShowCallouts:(BOOL)showcallouts {
    showcallouts = !! showcallouts;
    if (showcallouts != _hfflags.showcallouts) {
        _hfflags.showcallouts = showcallouts;
        [self _addPropertyChangeBits:HFControllerShowCallouts];
    }
}

- (BOOL)shouldHideNullBytes {
    return _hfflags.hideNullBytes;
}

- (void)setShouldHideNullBytes:(BOOL)hideNullBytes
{
    hideNullBytes = !! hideNullBytes;
    if (hideNullBytes != _hfflags.hideNullBytes) {
        _hfflags.hideNullBytes = hideNullBytes;
        [self _addPropertyChangeBits:HFControllerHideNullBytes];
    }
}

- (BOOL)shouldLiveReload {
    return _hfflags.livereload;
}

- (void)setShouldLiveReload:(BOOL)livereload {
    _hfflags.livereload = !!livereload;
    
}

- (void)setBytesPerColumn:(NSUInteger)val {
    if (val != bytesPerColumn) {
        bytesPerColumn = val;
        [self _addPropertyChangeBits:HFControllerBytesPerColumn];
    }
}

- (NSUInteger)bytesPerColumn {
    return bytesPerColumn;
}

- (BOOL)_shouldInvertSelectedRangesByAnchorRange {
    return _hfflags.selectionInProgress && _hfflags.commandExtendSelection;
}

- (NSArray *)_invertedSelectedContentsRanges {
    HFASSERT([selectedContentsRanges count] > 0);
    HFASSERT(selectionAnchorRange.location != NO_SELECTION);
    if (selectionAnchorRange.length == 0) return [NSArray arrayWithArray:selectedContentsRanges];
    
    NSArray *cleanedRanges = [HFRangeWrapper organizeAndMergeRanges:selectedContentsRanges];
    NSMutableArray *result = [NSMutableArray array];
    
    /* Our algorithm works as follows - add any ranges outside of the selectionAnchorRange, clipped by the selectionAnchorRange.  Then extract every "index" in our cleaned selected arrays that are within the selectionAnchorArray.  An index is the location where a range starts or stops.  Then use those indexes to create the inverted arrays.  A range parity of 1 means that we are adding the range. */
    
    /* Add all the ranges that are outside of selectionAnchorRange, clipping them if necessary */
    HFASSERT(HFSumDoesNotOverflow(selectionAnchorRange.location, selectionAnchorRange.length));
    FOREACH(HFRangeWrapper*, outsideWrapper, cleanedRanges) {
        HFRange range = [outsideWrapper HFRange];
        if (range.location < selectionAnchorRange.location) {
            HFRange clippedRange;
            clippedRange.location = range.location;
            HFASSERT(MIN(HFMaxRange(range), selectionAnchorRange.location) >= clippedRange.location);
            clippedRange.length = MIN(HFMaxRange(range), selectionAnchorRange.location) - clippedRange.location;
            [result addObject:[HFRangeWrapper withRange:clippedRange]];
        }
        if (HFMaxRange(range) > HFMaxRange(selectionAnchorRange)) {
            HFRange clippedRange;
            clippedRange.location = MAX(range.location, HFMaxRange(selectionAnchorRange));
            HFASSERT(HFMaxRange(range) >= clippedRange.location);
            clippedRange.length = HFMaxRange(range) - clippedRange.location;
            [result addObject:[HFRangeWrapper withRange:clippedRange]];
        }
    }
    
    HFASSERT(HFSumDoesNotOverflow(selectionAnchorRange.location, selectionAnchorRange.length));
    
    NEW_ARRAY(unsigned long long, partitions, 2*[cleanedRanges count] + 2);
    NSUInteger partitionCount, partitionIndex = 0;
    
    partitions[partitionIndex++] = selectionAnchorRange.location;
    FOREACH(HFRangeWrapper*, wrapper, cleanedRanges) {
        HFRange range = [wrapper HFRange];
        if (! HFIntersectsRange(range, selectionAnchorRange)) continue;
        
        partitions[partitionIndex++] = MAX(selectionAnchorRange.location, range.location);
        partitions[partitionIndex++] = MIN(HFMaxRange(selectionAnchorRange), HFMaxRange(range));
    }
    
    // For some reason, using HFMaxRange confuses the static analyzer
    partitions[partitionIndex++] = HFSum(selectionAnchorRange.location, selectionAnchorRange.length);
    
    partitionCount = partitionIndex;
    HFASSERT((partitionCount % 2) == 0);
    
    partitionIndex = 0;
    while (partitionIndex < partitionCount) {
        HFASSERT(partitionIndex + 1 < partitionCount);
        HFASSERT(partitions[partitionIndex] <= partitions[partitionIndex + 1]);
        if (partitions[partitionIndex] < partitions[partitionIndex + 1]) {
            HFRange range = HFRangeMake(partitions[partitionIndex], partitions[partitionIndex + 1] - partitions[partitionIndex]);
            [result addObject:[HFRangeWrapper withRange:range]];
        }
        partitionIndex += 2;
    }
    
    FREE_ARRAY(partitions);
    
    if ([result count] == 0) [result addObject:[HFRangeWrapper withRange:HFRangeMake(selectionAnchor, 0)]];
    
    return [HFRangeWrapper organizeAndMergeRanges:result];
}

- (void)_ensureSelectionIsValid {
    HFASSERT(selectedContentsRanges != nil);
    HFASSERT([selectedContentsRanges count] > 0);
    BOOL onlyOneWrapper = ([selectedContentsRanges count] == 1);
    FOREACH(HFRangeWrapper*, wrapper, selectedContentsRanges) {
        EXPECT_CLASS(wrapper, HFRangeWrapper);
        HFRange range = [wrapper HFRange];
        if (!HFRangeIsSubrangeOfRange(range, HFRangeMake(0, [self contentsLength]))){
            [self setSelectedContentsRanges:@[[HFRangeWrapper withRange:HFRangeMake(0, 0)]]];
            return;
        }
        if (onlyOneWrapper == NO) HFASSERT(range.length > 0); /* If we have more than one wrapper, then none of them should be zero length */
    }
}

- (void)_setSingleSelectedContentsRange:(HFRange)newSelection {
    if (!HFRangeIsSubrangeOfRange(newSelection, HFRangeMake(0, [self contentsLength]))) return;
    BOOL selectionChanged;
    if ([selectedContentsRanges count] == 1) {
        selectionChanged = ! HFRangeEqualsRange([selectedContentsRanges[0] HFRange], newSelection);
    }
    else {
        selectionChanged = YES;
    }
    
    if (selectionChanged) {
        [selectedContentsRanges removeAllObjects];
        [selectedContentsRanges addObject:[HFRangeWrapper withRange:newSelection]];
        [self _addPropertyChangeBits:HFControllerSelectedRanges];
    }
    VALIDATE_SELECTION();
}

- (NSArray *)selectedContentsRanges {
    VALIDATE_SELECTION();
    if ([self _shouldInvertSelectedRangesByAnchorRange]) return [self _invertedSelectedContentsRanges];
    else return [NSArray arrayWithArray:selectedContentsRanges];
}

- (unsigned long long)contentsLength {
    if (! byteArray) return 0;
    else return [byteArray length];
}

- (NSData *)dataForRange:(HFRange)range {
    HFASSERT(range.length <= NSUIntegerMax); // it doesn't make sense to ask for a buffer larger than can be stored in memory
    HFASSERT(HFRangeIsSubrangeOfRange(range, HFRangeMake(0, [self contentsLength])));
    
    if(range.length == 0) {
        // Don't throw out cache for an empty request! Also makes the analyzer happier.
        return [NSData data];
    }
    
    NSUInteger newGenerationIndex = [byteArray changeGenerationCount];
    if (cachedData == nil || newGenerationIndex != cachedGenerationIndex || ! HFRangeIsSubrangeOfRange(range, cachedRange)) {
        [cachedData release];
        cachedGenerationIndex = newGenerationIndex;
        cachedRange = range;
        NSUInteger length = ll2l(range.length);
        unsigned char *data = check_malloc(length);
        [byteArray copyBytes:data range:range];
        cachedData = [[NSData alloc] initWithBytesNoCopy:data length:length freeWhenDone:YES];
    }
    
    if (HFRangeEqualsRange(range, cachedRange)) {
        return cachedData;
    }
    else {
        HFASSERT(cachedRange.location <= range.location);
        NSRange cachedDataSubrange;
        cachedDataSubrange.location = ll2l(range.location - cachedRange.location);
        cachedDataSubrange.length = ll2l(range.length);
        return [cachedData subdataWithRange:cachedDataSubrange];
    }
}

- (void)copyBytes:(unsigned char *)bytes range:(HFRange)range {
    HFASSERT(range.length <= NSUIntegerMax); // it doesn't make sense to ask for a buffer larger than can be stored in memory
    HFASSERT(HFRangeIsSubrangeOfRange(range, HFRangeMake(0, [self contentsLength])));
    [byteArray copyBytes:bytes range:range];
}

- (void)_updateDisplayedRange {
    HFRange proposedNewDisplayRange;
    HFFPRange proposedNewLineRange;
    HFRange maxRangeSet = [self _maximumDisplayedRangeSet];
    NSUInteger maxBytesForViewSize = NSUIntegerMax;
    double maxLines = DBL_MAX;
    FOREACH(HFRepresenter*, rep, representers) {
        NSView *view = [rep view];
        double repMaxLines = [rep maximumAvailableLinesForViewHeight:NSHeight([view frame])];
        if (repMaxLines != DBL_MAX) {
            /* bytesPerLine may be ULONG_MAX.  We want to compute the smaller of maxBytesForViewSize and ceil(repMaxLines) * bytesPerLine.  If the latter expression overflows, the smaller is the former. */
            NSUInteger repMaxLinesUInt = (NSUInteger)ceil(repMaxLines);
            NSUInteger maxLinesTimesBytesPerLine =  repMaxLinesUInt * bytesPerLine;
            /* Check if we overflowed */
            BOOL overflowed = (repMaxLinesUInt != 0 && (maxLinesTimesBytesPerLine / repMaxLinesUInt != bytesPerLine));
            if (! overflowed) {
                maxBytesForViewSize = MIN(maxLinesTimesBytesPerLine, maxBytesForViewSize);
            }
        }
        maxLines = MIN(repMaxLines, maxLines);
    }
    if (maxLines == DBL_MAX) {
        proposedNewDisplayRange = HFRangeMake(0, 0);
        proposedNewLineRange = (HFFPRange){0, 0};
    }
    else {
        unsigned long long maximumDisplayedBytes = MIN(maxRangeSet.length, maxBytesForViewSize);
        HFASSERT(HFMaxRange(maxRangeSet) >= maximumDisplayedBytes);
        
        proposedNewDisplayRange.location = MIN(HFMaxRange(maxRangeSet) - maximumDisplayedBytes, displayedContentsRange.location);
        proposedNewDisplayRange.location -= proposedNewDisplayRange.location % bytesPerLine;
        proposedNewDisplayRange.length = MIN(HFMaxRange(maxRangeSet) - proposedNewDisplayRange.location, maxBytesForViewSize);
        if (maxBytesForViewSize % bytesPerLine != 0) {
            NSLog(@"Bad max bytes: %lu (%lu)", (unsigned long)maxBytesForViewSize, (unsigned long)bytesPerLine);
        }
        if (HFMaxRange(maxRangeSet) != ULLONG_MAX && (HFMaxRange(maxRangeSet) - proposedNewDisplayRange.location) % bytesPerLine != 0) {
            NSLog(@"Bad max range minus: %llu (%lu)", HFMaxRange(maxRangeSet) - proposedNewDisplayRange.location, (unsigned long)bytesPerLine);
        }
        
        long double lastLine = HFULToFP([self totalLineCount]);
        proposedNewLineRange.length = MIN(maxLines, lastLine);
        proposedNewLineRange.location = MIN(displayedLineRange.location, lastLine - proposedNewLineRange.length);
    }
    HFASSERT(HFRangeIsSubrangeOfRange(proposedNewDisplayRange, maxRangeSet));
    HFASSERT(proposedNewDisplayRange.location % bytesPerLine == 0);
    if (! HFRangeEqualsRange(proposedNewDisplayRange, displayedContentsRange) || ! HFFPRangeEqualsRange(proposedNewLineRange, displayedLineRange)) {
        displayedContentsRange = proposedNewDisplayRange;
        displayedLineRange = proposedNewLineRange;
        [self _addPropertyChangeBits:HFControllerDisplayedLineRange];
    }
}

- (void)_ensureVisibilityOfLocation:(unsigned long long)location {
    HFASSERT(location <= [self contentsLength]);
    unsigned long long lineInt = location / bytesPerLine;
    long double line = HFULToFP(lineInt);
    HFASSERT(line >= 0);
    line  = MIN(line, HFULToFP([self totalLineCount]) - 1);
    HFFPRange lineRange = [self displayedLineRange];
    HFFPRange newLineRange = lineRange;
    if (line < lineRange.location) {
        newLineRange.location = line;
    }
    else if (line >= lineRange.location + lineRange.length) {
        HFASSERT(lineRange.location + lineRange.length >= 1);
        newLineRange.location = lineRange.location + (line - (lineRange.location + lineRange.length - 1));
    }
    [self setDisplayedLineRange:newLineRange];
}

- (void)maximizeVisibilityOfContentsRange:(HFRange)range {
    HFASSERT(HFRangeIsSubrangeOfRange(range, HFRangeMake(0, [self contentsLength])));
    
    // Find the minimum move necessary to make range visible
    HFFPRange displayRange = [self displayedLineRange];
    HFFPRange newDisplayRange = displayRange;
    unsigned long long startLine = range.location / bytesPerLine;
    unsigned long long endLine = HFDivideULLRoundingUp(HFRoundUpToNextMultipleSaturate(HFMaxRange(range), bytesPerLine), bytesPerLine);
    HFASSERT(endLine > startLine || endLine == ULLONG_MAX);
    long double linesInRange = HFULToFP(endLine - startLine);
    long double linesToDisplay = MIN(displayRange.length, linesInRange);
    HFASSERT(linesToDisplay <= linesInRange);
    long double linesToMoveDownToMakeLastLineVisible = HFULToFP(endLine) - (displayRange.location + displayRange.length);
    long double linesToMoveUpToMakeFirstLineVisible = displayRange.location - HFULToFP(startLine);
    //HFASSERT(linesToMoveUpToMakeFirstLineVisible <= 0 || linesToMoveDownToMakeLastLineVisible <= 0);
    // in general, we expect either linesToMoveUpToMakeFirstLineVisible to be <= zero, or linesToMoveDownToMakeLastLineVisible to be <= zero.  However, if the available space is smaller than one line, then that won't be true.
    if (linesToMoveDownToMakeLastLineVisible > 0) {
        newDisplayRange.location += linesToMoveDownToMakeLastLineVisible;
    }
    else if (linesToMoveUpToMakeFirstLineVisible > 0 && linesToDisplay >= 1) {
        // the >= 1 check prevents some wacky behavior when we have less than one line's worth of space, that caused bouncing between the top and bottom of the line
        newDisplayRange.location -= linesToMoveUpToMakeFirstLineVisible;
    }
    
    // Use the minimum movement if it would be visually helpful; otherwise just center.
    if (HFFPIntersectsRange(displayRange, newDisplayRange)) {
        [self setDisplayedLineRange:newDisplayRange];
    } else {
        [self centerContentsRange:range];
    }
}

- (void)centerContentsRange:(HFRange)range {
    HFASSERT(HFRangeIsSubrangeOfRange(range, HFRangeMake(0, [self contentsLength])));
    HFFPRange displayRange = [self displayedLineRange];
    const long double numDisplayedLines = displayRange.length;
    HFFPRange newDisplayRange;
    unsigned long long startLine = range.location / bytesPerLine;
    unsigned long long endLine = HFDivideULLRoundingUp(HFRoundUpToNextMultipleSaturate(HFMaxRange(range), bytesPerLine), bytesPerLine);
    HFASSERT(endLine > startLine || endLine == ULLONG_MAX);
    long double linesInRange = HFULToFP(endLine - startLine);
    
    /* Handle the case of a line range bigger than we can display by choosing the top lines. */
    if (numDisplayedLines <= linesInRange) {
        newDisplayRange = (HFFPRange){startLine, numDisplayedLines};
    }
    else {
        /* Construct a newDisplayRange that centers {startLine, endLine} */
        long double center = startLine + (endLine - startLine) / 2.;
        newDisplayRange = (HFFPRange){center - numDisplayedLines / 2., numDisplayedLines};
    }
    
    /* Move the newDisplayRange up or down as necessary */
    newDisplayRange.location = fmaxl(newDisplayRange.location, (long double)0.);
    newDisplayRange.location = fminl(newDisplayRange.location, HFULToFP([self totalLineCount]) - numDisplayedLines);
    [self setDisplayedLineRange:newDisplayRange];
}

/* Clips the selection to a given length.  If this would clip the entire selection, returns a zero length selection at the end.  Indicates HFControllerSelectedRanges if the selection changes. */
- (void)_clipSelectedContentsRangesToLength:(unsigned long long)newLength {
    NSMutableArray *newTempSelection = [selectedContentsRanges mutableCopy];
    NSUInteger i, max = [newTempSelection count];
    for (i=0; i < max; i++) {
        HFRange range = [newTempSelection[i] HFRange];
        if (HFMaxRange(range) > newLength) {
            if (range.location > newLength) {
                /* The range starts past our new max.  Just remove this range entirely */
                [newTempSelection removeObjectAtIndex:i];
                i--;
                max--;
            }
            else {
                /* Need to clip this range */
                range.length = newLength - range.location;
                newTempSelection[i] = [HFRangeWrapper withRange:range];
            }
        }
    }
    [newTempSelection setArray:[HFRangeWrapper organizeAndMergeRanges:newTempSelection]];
    
    /* If there are multiple empty ranges, remove all but the first */
    BOOL foundEmptyRange = NO;
    max = [newTempSelection count];
    for (i=0; i < max; i++) {
        HFRange range = [newTempSelection[i] HFRange];
        HFASSERT(HFMaxRange(range) <= newLength);
        if (range.length == 0) {
            if (foundEmptyRange) {
                [newTempSelection removeObjectAtIndex:i];
                i--;
                max--;
            }
            foundEmptyRange = YES;
        }
    }
    if (max == 0) {
        /* Removed all ranges - insert one at the end */
        [newTempSelection addObject:[HFRangeWrapper withRange:HFRangeMake(newLength, 0)]];
    }
    
    /* If something changed, set the new selection and post the change bit */
    if (! [selectedContentsRanges isEqualToArray:newTempSelection]) {
        [selectedContentsRanges setArray:newTempSelection];
        [self _addPropertyChangeBits:HFControllerSelectedRanges];
    }
    
    [newTempSelection release];
}

- (void)setByteArray:(HFByteArray *)val {
    REQUIRE_NOT_NULL(val);
    BEGIN_TRANSACTION();
    [byteArray removeObserver:self forKeyPath:@"changesAreLocked"];
    [val retain];
    [byteArray release];
    byteArray = val;
    [cachedData release];
    cachedData = nil;
    [byteArray addObserver:self forKeyPath:@"changesAreLocked" options:0 context:KVOContextChangesAreLocked];
    [self _updateDisplayedRange];
    [self _addPropertyChangeBits: HFControllerContentValue | HFControllerContentLength];
    [self _clipSelectedContentsRangesToLength:[byteArray length]];
    END_TRANSACTION();
}

- (HFByteArray *)byteArray {
    return byteArray;
}

- (void)_undoNotification:note {
    USE(note);
}

- (void)_removeUndoManagerNotifications {
    if (undoManager) {
        NSNotificationCenter *noter = [NSNotificationCenter defaultCenter];
        [noter removeObserver:self name:NSUndoManagerWillUndoChangeNotification object:undoManager];
    }
}

- (void)_addUndoManagerNotifications {
    if (undoManager) {
        NSNotificationCenter *noter = [NSNotificationCenter defaultCenter];
        [noter addObserver:self selector:@selector(_undoNotification:) name:NSUndoManagerWillUndoChangeNotification object:undoManager];
    }
}

- (void)_removeAllUndoOperations {
    /* Remove all the undo operations, because some undo operation is unsupported. Note that if we were smarter we would keep a stack of undo operations and only remove ones "up to" a certain point. */
    [undoManager removeAllActionsWithTarget:self];
    [undoOperations makeObjectsPerformSelector:@selector(invalidate)];
    [undoOperations removeAllObjects];
}

- (void)setUndoManager:(NSUndoManager *)manager {
    [self _removeUndoManagerNotifications];
    [self _removeAllUndoOperations];
    [manager retain];
    [undoManager release];
    undoManager = manager;
    [self _addUndoManagerNotifications];
}

- (NSUndoManager *)undoManager {
    return undoManager;
}

- (NSUInteger)bytesPerLine {
    return bytesPerLine;
}

- (BOOL)editable {
    return _hfflags.editable && ! [byteArray changesAreLocked] && _hfflags.editMode != HFReadOnlyMode;
}

- (void)setEditable:(BOOL)flag {
    if (flag != _hfflags.editable) {
        _hfflags.editable = flag;
        [self _addPropertyChangeBits:HFControllerEditable];
    }
}

- (void)_updateBytesPerLine {
    NSUInteger newBytesPerLine = NSUIntegerMax;
    FOREACH(HFRepresenter*, rep, representers) {
        NSView *view = [rep view];
        CGFloat width = [view frame].size.width;
        NSUInteger repMaxBytesPerLine = [rep maximumBytesPerLineForViewWidth:width];
        HFASSERT(repMaxBytesPerLine > 0);
        newBytesPerLine = MIN(repMaxBytesPerLine, newBytesPerLine);
    }
    if (newBytesPerLine != bytesPerLine) {
        HFASSERT(newBytesPerLine > 0);
        bytesPerLine = newBytesPerLine;
        BEGIN_TRANSACTION();
        [self _addPropertyChangeBits:HFControllerBytesPerLine];
        END_TRANSACTION();
    }
}

- (void)representer:(HFRepresenter *)rep changedProperties:(HFControllerPropertyBits)properties {
    USE(rep);
    HFControllerPropertyBits remainingProperties = properties;
    BEGIN_TRANSACTION();
    if (remainingProperties & HFControllerBytesPerLine) {
        [self _updateBytesPerLine];
        remainingProperties &= ~HFControllerBytesPerLine;
    }
    if (remainingProperties & HFControllerDisplayedLineRange) {
        [self _updateDisplayedRange];
        remainingProperties &= ~HFControllerDisplayedLineRange;
    }
    if (remainingProperties & HFControllerByteRangeAttributes) {
        [self _addPropertyChangeBits:HFControllerByteRangeAttributes];
        remainingProperties &= ~HFControllerByteRangeAttributes;
    }
    if (remainingProperties & HFControllerViewSizeRatios) {
        [self _addPropertyChangeBits:HFControllerViewSizeRatios];
        remainingProperties &= ~HFControllerViewSizeRatios;
    }
    if (remainingProperties) {
        NSLog(@"Unknown properties: %lx", (long)remainingProperties);
    }
    END_TRANSACTION();
}

- (HFByteArray *)byteArrayForSelectedContentsRanges {
    HFByteArray *result = nil;
    HFByteArray *bytes = [self byteArray];
    VALIDATE_SELECTION();
    FOREACH(HFRangeWrapper*, wrapper, selectedContentsRanges) {
        HFRange range = [wrapper HFRange];
        HFByteArray *additionalBytes = [bytes subarrayWithRange:range];
        if (! result) {
            result = additionalBytes;
        }
        else {
            [result insertByteArray:additionalBytes inRange:HFRangeMake([result length], 0)];
        }
    }
    return result;
}

/* Flattens the selected range to a single range (the selected range becomes any character within or between the selected ranges).  Modifies the selectedContentsRanges and returns the new single HFRange.  Does not call notifyRepresentersOfChanges: */
- (HFRange)_flattenSelectionRange {
    HFASSERT([selectedContentsRanges count] >= 1);
    
    HFRange resultRange = [selectedContentsRanges[0] HFRange];
    if ([selectedContentsRanges count] == 1) return resultRange; //already flat
    
    FOREACH(HFRangeWrapper*, wrapper, selectedContentsRanges) {
        HFRange selectedRange = [wrapper HFRange];
        if (selectedRange.location < resultRange.location) {
            /* Extend our result range backwards */
            resultRange.length += resultRange.location - selectedRange.location;
            resultRange.location = selectedRange.location;
        }
        if (HFRangeExtendsPastRange(selectedRange, resultRange)) {
            HFASSERT(selectedRange.location >= resultRange.location); //must be true by if statement above
            resultRange.length = HFSum(selectedRange.location - resultRange.location, selectedRange.length);
        }
    }
    [self _setSingleSelectedContentsRange:resultRange];
    return resultRange;
}

- (unsigned long long)_minimumSelectionLocation {
    HFASSERT([selectedContentsRanges count] >= 1);
    unsigned long long minSelection = ULLONG_MAX;
    FOREACH(HFRangeWrapper*, wrapper, selectedContentsRanges) {
        HFRange range = [wrapper HFRange];
        minSelection = MIN(minSelection, range.location);
    }
    return minSelection;
}

- (unsigned long long)_maximumSelectionLocation {
    HFASSERT([selectedContentsRanges count] >= 1);
    unsigned long long maxSelection = 0;
    FOREACH(HFRangeWrapper*, wrapper, selectedContentsRanges) {
        HFRange range = [wrapper HFRange];
        maxSelection = MAX(maxSelection, HFMaxRange(range));
    }
    return maxSelection;
}

- (unsigned long long)minimumSelectionLocation {
    return [self _minimumSelectionLocation];
}

- (unsigned long long)maximumSelectionLocation {
    return [self _maximumSelectionLocation];
}

/* Put the selection at the left or right end of the current selection, with zero length.  Modifies the selectedContentsRanges and returns the new single HFRange.  Does not call notifyRepresentersOfChanges: */
- (HFRange)_telescopeSelectionRangeInDirection:(HFControllerMovementDirection)direction {
    HFRange resultRange;
    HFASSERT(direction == HFControllerDirectionLeft || direction == HFControllerDirectionRight);
    resultRange.location = (direction == HFControllerDirectionLeft ? [self _minimumSelectionLocation] : [self _maximumSelectionLocation]);
    resultRange.length = 0;
    [self _setSingleSelectedContentsRange:resultRange];
    return resultRange;
}

- (void)beginSelectionWithEvent:(NSEvent *)event forByteIndex:(unsigned long long)characterIndex {
    USE(event);
    HFASSERT(characterIndex <= [self contentsLength]);
    
    /* Determine how to perform the selection - normally, with command key, or with shift key.  Command + shift is the same as command. The shift key closes the selection - the selected range becomes the single range containing the first and last selected character. */
    _hfflags.shiftExtendSelection = NO;
    _hfflags.commandExtendSelection = NO;
    NSUInteger flags = [event modifierFlags];
    if (flags & NSCommandKeyMask) _hfflags.commandExtendSelection = YES;
    else if (flags & NSShiftKeyMask) _hfflags.shiftExtendSelection = YES;
    
    selectionAnchor = NO_SELECTION;
    selectionAnchorRange = HFRangeMake(NO_SELECTION, 0);
    
    _hfflags.selectionInProgress = YES;
    if (_hfflags.commandExtendSelection) {
        /* The selection anchor is used to track the "invert" range.  All characters within this range have their selection inverted.  This is tracked by the _shouldInvertSelectedRangesByAnchorRange method. */
        selectionAnchor = characterIndex;
        selectionAnchorRange = HFRangeMake(characterIndex, 0);
    }
    else if (_hfflags.shiftExtendSelection) {
        /* The selection anchor is used to track the single (flattened) selected range. */
        HFRange selectedRange = [self _flattenSelectionRange];
        unsigned long long distanceFromRangeStart = HFAbsoluteDifference(selectedRange.location, characterIndex);
        unsigned long long distanceFromRangeEnd = HFAbsoluteDifference(HFMaxRange(selectedRange), characterIndex);
        if (selectedRange.length == 0) {    
            HFASSERT(distanceFromRangeStart == distanceFromRangeEnd);
            selectionAnchor = selectedRange.location;
            selectedRange.location = MIN(characterIndex, selectedRange.location);
            selectedRange.length = distanceFromRangeStart;
        }
        else if (distanceFromRangeStart >= distanceFromRangeEnd) {
            /* Push the "end forwards" */
            selectedRange.length = distanceFromRangeStart;
            selectionAnchor = selectedRange.location;
        }
        else {
            /* Push the "start back" */
            selectedRange.location = selectedRange.location + selectedRange.length - distanceFromRangeEnd;
            selectedRange.length = distanceFromRangeEnd;
            selectionAnchor = HFSum(selectedRange.length, selectedRange.location);
        }
        HFASSERT(HFRangeIsSubrangeOfRange(selectedRange, HFRangeMake(0, [self contentsLength])));
        selectionAnchorRange = selectedRange;
        [self _setSingleSelectedContentsRange:selectedRange];
    }
    else {
        /* No modifier key selection.  The selection anchor is not used.  */
        [self _setSingleSelectedContentsRange:HFRangeMake(characterIndex, 0)];
        selectionAnchor = characterIndex;
    }
}

- (void)continueSelectionWithEvent:(NSEvent *)event forByteIndex:(unsigned long long)byteIndex {
    USE(event);
    HFASSERT(_hfflags.selectionInProgress);
    HFASSERT(byteIndex <= [self contentsLength]);
    BEGIN_TRANSACTION();
    if (_hfflags.commandExtendSelection) {
        /* Clear any zero-length ranges, unless there's only one */
        NSUInteger rangeCount = [selectedContentsRanges count];
        NSUInteger rangeIndex = rangeCount;
        while (rangeIndex-- > 0) {
            if (rangeCount > 1 && [selectedContentsRanges[rangeIndex] HFRange].length == 0) {
                [selectedContentsRanges removeObjectAtIndex:rangeIndex];
                rangeCount--;
            }
        }
        selectionAnchorRange.location = MIN(byteIndex, selectionAnchor);
        selectionAnchorRange.length = MAX(byteIndex, selectionAnchor) - selectionAnchorRange.location;
        [self _addPropertyChangeBits:HFControllerSelectedRanges];
    }
    else if (_hfflags.shiftExtendSelection) {
        HFASSERT(selectionAnchorRange.location != NO_SELECTION);
        HFASSERT(selectionAnchor != NO_SELECTION);
        HFRange range;
        if (! HFLocationInRange(byteIndex, selectionAnchorRange)) {
            /* The character index is outside of the selection anchor range.  The new range is just the selected anchor range combined with the character index. */
            range.location = MIN(byteIndex, selectionAnchorRange.location);
            unsigned long long rangeEnd = MAX(byteIndex, HFSum(selectionAnchorRange.location, selectionAnchorRange.length));
            HFASSERT(rangeEnd >= range.location);
            range.length = rangeEnd - range.location;
        }
        else {
            /* The character is within the selection anchor range.  We use the selection anchor index to determine which "side" of the range is selected. */
            range.location = MIN(selectionAnchor, byteIndex);
            range.length = HFAbsoluteDifference(selectionAnchor, byteIndex);
        }
        [self _setSingleSelectedContentsRange:range];
    }
    else {
        /* No modifier key selection */
        HFRange range;
        range.location = MIN(byteIndex, selectionAnchor);
        range.length = MAX(byteIndex, selectionAnchor) - range.location;
        [self _setSingleSelectedContentsRange:range];
    }
    END_TRANSACTION();
    VALIDATE_SELECTION();
}

- (void)endSelectionWithEvent:(NSEvent *)event forByteIndex:(unsigned long long)characterIndex {
    USE(event);
    HFASSERT(_hfflags.selectionInProgress);
    HFASSERT(characterIndex <= [self contentsLength]);
    if (_hfflags.commandExtendSelection) {
        selectionAnchorRange.location = MIN(characterIndex, selectionAnchor);
        selectionAnchorRange.length = MAX(characterIndex, selectionAnchor) - selectionAnchorRange.location;
        
        /* "Commit" our selectionAnchorRange */
        NSArray *newSelection = [self _invertedSelectedContentsRanges];
        [selectedContentsRanges setArray:newSelection];
    }
    else if (_hfflags.shiftExtendSelection) {
        HFASSERT(selectionAnchorRange.location != NO_SELECTION);
        HFASSERT(selectionAnchor != NO_SELECTION);
        HFRange range;
        if (! HFLocationInRange(characterIndex, selectionAnchorRange)) {
            /* The character index is outside of the selection anchor range.  The new range is just the selected anchor range combined with the character index. */
            range.location = MIN(characterIndex, selectionAnchorRange.location);
            unsigned long long rangeEnd = MAX(characterIndex, HFSum(selectionAnchorRange.location, selectionAnchorRange.length));
            HFASSERT(rangeEnd >= range.location);
            range.length = rangeEnd - range.location;
        }
        else {
            /* The character is within the selection anchor range.  We use the selection anchor index to determine which "side" of the range is selected. */
            range.location = MIN(selectionAnchor, characterIndex);
            range.length = HFAbsoluteDifference(selectionAnchor, characterIndex);
        }
        [self _setSingleSelectedContentsRange:range];
    }
    else {
        /* No modifier key selection */
        HFRange range;
        range.location = MIN(characterIndex, selectionAnchor);
        range.length = MAX(characterIndex, selectionAnchor) - range.location;
        [self _setSingleSelectedContentsRange:range];
    }
    
    _hfflags.selectionInProgress = NO;    
    _hfflags.shiftExtendSelection = NO;
    _hfflags.commandExtendSelection = NO;
    selectionAnchor = NO_SELECTION;
}

- (double)selectionPulseAmount {
    double result = 0;
    if (pulseSelectionStartTime > 0) {
        CFTimeInterval diff = pulseSelectionCurrentTime - pulseSelectionStartTime;
        if (diff > 0 && diff < kPulseDuration) {
            result = 1. - fabs(diff * 2 - kPulseDuration) / kPulseDuration;
        }
    }
    return result;
}

- (void)firePulseTimer:(NSTimer *)timer {
    USE(timer);
    HFASSERT(pulseSelectionStartTime != 0);
    pulseSelectionCurrentTime = CFAbsoluteTimeGetCurrent();
    [self _addPropertyChangeBits:HFControllerSelectionPulseAmount];
    if (pulseSelectionCurrentTime - pulseSelectionStartTime > kPulseDuration) {
        [pulseSelectionTimer invalidate];
        [pulseSelectionTimer release];
        pulseSelectionTimer = nil;
    }
}

- (void)pulseSelection {
    pulseSelectionStartTime = CFAbsoluteTimeGetCurrent();
    if (pulseSelectionTimer == nil) {
        pulseSelectionTimer = [[NSTimer scheduledTimerWithTimeInterval:(1. / 30.) target:self selector:@selector(firePulseTimer:) userInfo:nil repeats:YES] retain];
    }
}

- (void)scrollByLines:(long double)lines {
    HFFPRange lineRange = [self displayedLineRange];
    HFASSERT(HFULToFP([self totalLineCount]) >= lineRange.length);
    long double maxScroll = HFULToFP([self totalLineCount]) - lineRange.length;
    if (lines < 0) {
        lineRange.location -= MIN(lineRange.location, -lines);
    }
    else {
        lineRange.location = MIN(maxScroll, lineRange.location + lines);
    }
    [self setDisplayedLineRange:lineRange];
}

- (void)scrollWithScrollEvent:(NSEvent *)scrollEvent {
    HFASSERT(scrollEvent != NULL);
    HFASSERT([scrollEvent type] == NSScrollWheel);
    CGFloat preciseScroll = 0;
    BOOL hasPreciseScroll;
    
    /* Prefer precise deltas */
    if ([scrollEvent respondsToSelector:@selector(hasPreciseScrollingDeltas)]) {
        hasPreciseScroll = [scrollEvent hasPreciseScrollingDeltas];
        if (hasPreciseScroll) {
            /* In this case, we're going to scroll by a certain number of points */
            preciseScroll = [scrollEvent scrollingDeltaY];
        }
    } else if ([scrollEvent respondsToSelector:@selector(deviceDeltaY)]) {
        /* Legacy (SnowLeopard) support */
        hasPreciseScroll = ([scrollEvent subtype] == 1);
        if (hasPreciseScroll) {
            preciseScroll = [scrollEvent deviceDeltaY];
        }
    } else {
        hasPreciseScroll = NO;
    }
    
    long double scrollY = 0;
    if (! hasPreciseScroll) {
        scrollY = -kScrollMultiplier * [scrollEvent deltaY];
    } else {
        scrollY = -preciseScroll / [self lineHeight];
    }
    [self scrollByLines:scrollY];
}

- (void)setSelectedContentsRanges:(NSArray *)selectedRanges {
    REQUIRE_NOT_NULL(selectedRanges);
    [selectedContentsRanges setArray:selectedRanges];
    VALIDATE_SELECTION();
    selectionAnchor = NO_SELECTION;
    [self _addPropertyChangeBits:HFControllerSelectedRanges];
}

- (IBAction)selectAll:sender {
    USE(sender);
    if (_hfflags.selectable) {
        [self _setSingleSelectedContentsRange:HFRangeMake(0, [self contentsLength])];
    }
}

- (void)_addRangeToSelection:(HFRange)range {
    [selectedContentsRanges addObject:[HFRangeWrapper withRange:range]];
    [selectedContentsRanges setArray:[HFRangeWrapper organizeAndMergeRanges:selectedContentsRanges]];
    VALIDATE_SELECTION();
}

- (void)_removeRangeFromSelection:(HFRange)inputRange withCursorLocationIfAllSelectionRemoved:(unsigned long long)cursorLocation {
    NSUInteger selectionCount = [selectedContentsRanges count];
    HFASSERT(selectionCount > 0 && selectionCount <= NSUIntegerMax / 2);
    NSUInteger rangeIndex = 0;
    NSArray *wrappers;
    NEW_ARRAY(HFRange, tempRanges, selectionCount * 2);
    FOREACH(HFRangeWrapper*, wrapper, selectedContentsRanges) {
        HFRange range = [wrapper HFRange];
        if (! HFIntersectsRange(range, inputRange)) {
            tempRanges[rangeIndex++] = range;
        }
        else {
            if (range.location < inputRange.location) {
                tempRanges[rangeIndex++] = HFRangeMake(range.location, inputRange.location - range.location);
            }
            if (HFMaxRange(range) > HFMaxRange(inputRange)) {
                tempRanges[rangeIndex++] = HFRangeMake(HFMaxRange(inputRange), HFMaxRange(range) - HFMaxRange(inputRange));
            }
        }
    }
    if (rangeIndex == 0 || (rangeIndex == 1 && tempRanges[0].length == 0)) {
        /* We removed all of our ranges.  Telescope us. */
        HFASSERT(cursorLocation <= [self contentsLength]);
        [self _setSingleSelectedContentsRange:HFRangeMake(cursorLocation, 0)];
    }
    else {
        wrappers = [HFRangeWrapper withRanges:tempRanges count:rangeIndex];
        [selectedContentsRanges setArray:[HFRangeWrapper organizeAndMergeRanges:wrappers]];
    }
    FREE_ARRAY(tempRanges);
    VALIDATE_SELECTION();    
}

- (void)_moveDirectionDiscardingSelection:(HFControllerMovementDirection)direction byAmount:(unsigned long long)amountToMove {
    HFASSERT(direction == HFControllerDirectionLeft || direction == HFControllerDirectionRight);
    BEGIN_TRANSACTION();
    BOOL selectionWasEmpty = ([selectedContentsRanges count] == 1 && [selectedContentsRanges[0] HFRange].length == 0);
    BOOL directionIsForward = (direction == HFControllerDirectionRight);
    HFRange selectedRange = [self _telescopeSelectionRangeInDirection: (directionIsForward ? HFControllerDirectionRight : HFControllerDirectionLeft)];
    HFASSERT(selectedRange.length == 0);
    HFASSERT([self contentsLength] >= selectedRange.location);
    /* A movement of just 1 with a selection only clears the selection; it does not move the cursor */
    if (selectionWasEmpty || amountToMove > 1) {
        if (direction == HFControllerDirectionLeft) {
            selectedRange.location -= MIN(amountToMove, selectedRange.location);
        }
        else {
            selectedRange.location += MIN(amountToMove, [self contentsLength] - selectedRange.location);
        }
    }
    selectionAnchor = NO_SELECTION;
    [self _setSingleSelectedContentsRange:selectedRange];
    [self _ensureVisibilityOfLocation:selectedRange.location];
    END_TRANSACTION();
}

/* In _extendSelectionInDirection:byAmount:, we only allow left/right movement.  up/down is not allowed. */
- (void)_extendSelectionInDirection:(HFControllerMovementDirection)direction byAmount:(unsigned long long)amountToMove {
    HFASSERT(direction == HFControllerDirectionLeft || direction == HFControllerDirectionRight);
    unsigned long long minSelection = [self _minimumSelectionLocation];
    unsigned long long maxSelection = [self _maximumSelectionLocation];
    BOOL selectionChanged = NO;
    unsigned long long locationToMakeVisible = NO_SELECTION;
    unsigned long long contentsLength = [self contentsLength];
    if (selectionAnchor == NO_SELECTION) {
        /* Pick the anchor opposite the choice of direction */
        if (direction == HFControllerDirectionLeft) selectionAnchor = maxSelection;
        else selectionAnchor = minSelection;
    }
    if (direction == HFControllerDirectionLeft) {
        if (minSelection >= selectionAnchor && maxSelection > minSelection) {
            unsigned long long amountToRemove = llmin(maxSelection - selectionAnchor, amountToMove);
            unsigned long long amountToAdd = llmin(amountToMove - amountToRemove, selectionAnchor);
            if (amountToRemove > 0) [self _removeRangeFromSelection:HFRangeMake(maxSelection - amountToRemove, amountToRemove) withCursorLocationIfAllSelectionRemoved:minSelection];
            if (amountToAdd > 0) [self _addRangeToSelection:HFRangeMake(selectionAnchor - amountToAdd, amountToAdd)];
            selectionChanged = YES;
            locationToMakeVisible = (amountToAdd > 0 ? selectionAnchor - amountToAdd : maxSelection - amountToRemove);
        }
        else {
            if (minSelection > 0) {
                NSUInteger amountToAdd = ll2l(llmin(minSelection, amountToMove));
                if (amountToAdd > 0) [self _addRangeToSelection:HFRangeMake(minSelection - amountToAdd, amountToAdd)];
                selectionChanged = YES;
                locationToMakeVisible = minSelection - amountToAdd;
            }
        }
    }
    else if (direction == HFControllerDirectionRight) {
        if (maxSelection <= selectionAnchor && maxSelection > minSelection) {
            HFASSERT(contentsLength >= maxSelection);
            unsigned long long amountToRemove = ll2l(llmin(maxSelection - minSelection, amountToMove));
            unsigned long long amountToAdd = amountToMove - amountToRemove;
            if (amountToRemove > 0) [self _removeRangeFromSelection:HFRangeMake(minSelection, amountToRemove) withCursorLocationIfAllSelectionRemoved:maxSelection];
            if (amountToAdd > 0) [self _addRangeToSelection:HFRangeMake(maxSelection, amountToAdd)];
            selectionChanged = YES;
            locationToMakeVisible = llmin(contentsLength, (amountToAdd > 0 ? maxSelection + amountToAdd : minSelection + amountToRemove));
        }
        else {
            if (maxSelection < contentsLength) {
                NSUInteger amountToAdd = ll2l(llmin(contentsLength - maxSelection, amountToMove));
                [self _addRangeToSelection:HFRangeMake(maxSelection, amountToAdd)];
                selectionChanged = YES;
                locationToMakeVisible = maxSelection + amountToAdd;
            }
        }
    }
    if (selectionChanged) {
        BEGIN_TRANSACTION();
        [self _addPropertyChangeBits:HFControllerSelectedRanges];
        if (locationToMakeVisible != NO_SELECTION) [self _ensureVisibilityOfLocation:locationToMakeVisible];
        END_TRANSACTION();
    }
}

/* Returns the distance to the next "word" (at least 1, unless we are empty).  Here a word is identified as a column.  If there are no columns, a word is a line.  This is used for word movement (e.g. option + right arrow) */
- (unsigned long long)_distanceToWordBoundaryForDirection:(HFControllerMovementDirection)direction {
    unsigned long long result = 0, locationToConsider;
    
    /* Figure out how big a word is.  By default, it's the column width, unless we have no columns, in which case it's the bytes per line. */
    NSUInteger wordGranularity = [self bytesPerColumn];
    if (wordGranularity == 0) wordGranularity = MAX(1u, [self bytesPerLine]);
    if (selectionAnchor == NO_SELECTION) {
        /* Pick the anchor inline with the choice of direction */
        if (direction == HFControllerDirectionLeft) locationToConsider = [self _minimumSelectionLocation];
        else locationToConsider = [self _maximumSelectionLocation];
    } else {
        /* Just use the anchor */
        locationToConsider = selectionAnchor;
    }
    if (direction == HFControllerDirectionRight) {
        result = HFRoundUpToNextMultipleSaturate(locationToConsider, wordGranularity) - locationToConsider;
    } else {
        result = locationToConsider % wordGranularity;
        if (result == 0) result = wordGranularity;
    }
    return result;
    
}

/* Anchored selection is not allowed; neither is up/down movement */
- (void)_shiftSelectionInDirection:(HFControllerMovementDirection)direction byAmount:(unsigned long long)amountToMove {
    HFASSERT(direction == HFControllerDirectionLeft || direction == HFControllerDirectionRight);
    HFASSERT(selectionAnchor == NO_SELECTION);
    NSUInteger i, max = [selectedContentsRanges count];
    const unsigned long long maxLength = [self contentsLength];
    NSMutableArray *newRanges = [NSMutableArray arrayWithCapacity:max];
    BOOL hasAddedNonemptyRange = NO;
    for (i=0; i < max; i++) {
        HFRange range = [selectedContentsRanges[i] HFRange];
        HFASSERT(range.location <= maxLength && HFMaxRange(range) <= maxLength);
        if (direction == HFControllerDirectionRight) {
            unsigned long long offset = MIN(maxLength - range.location, amountToMove);
            unsigned long long lengthToSubtract = MIN(range.length, amountToMove - offset);
            range.location += offset;
            range.length -= lengthToSubtract;
        }
        else { /* direction == HFControllerDirectionLeft */
            unsigned long long negOffset = MIN(amountToMove, range.location);
            unsigned long long lengthToSubtract = MIN(range.length, amountToMove - negOffset);
            range.location -= negOffset;
            range.length -= lengthToSubtract;
        }
        [newRanges addObject:[HFRangeWrapper withRange:range]];
        hasAddedNonemptyRange = hasAddedNonemptyRange || (range.length > 0);
    }
    
    newRanges = [[[HFRangeWrapper organizeAndMergeRanges:newRanges] mutableCopy] autorelease];
    
    BOOL hasFoundEmptyRange = NO;
    max = [newRanges count];
    for (i=0; i < max; i++) {
        HFRange range = [newRanges[i] HFRange];
        if (range.length == 0) {
            if (hasFoundEmptyRange || hasAddedNonemptyRange) {
                [newRanges removeObjectAtIndex:i];
                i--;
                max--;
            }
            hasFoundEmptyRange = YES;
        }
    }
    [selectedContentsRanges setArray:newRanges];
    VALIDATE_SELECTION();
    [self _addPropertyChangeBits:HFControllerSelectedRanges];
}

__attribute__((unused))
static BOOL rangesAreInAscendingOrder(NSEnumerator *rangeEnumerator) {
    unsigned long long index = 0;
    HFRangeWrapper *rangeWrapper;
    while ((rangeWrapper = [rangeEnumerator nextObject])) {
        HFRange range = [rangeWrapper HFRange];
        if (range.location < index) return NO;
        index = HFSum(range.location, range.length);
    }
    return YES;
}

- (BOOL)_registerCondemnedRangesForUndo:(NSArray *)ranges selectingRangesAfterUndo:(BOOL)selectAfterUndo {
    HFASSERT(ranges != NULL);
    HFASSERT(ranges != selectedContentsRanges); //selectedContentsRanges is mutable - we really don't want to stash it away with undo
    BOOL result = NO;
    NSUndoManager *manager = [self undoManager];
    NSUInteger rangeCount = [ranges count];
    if (! manager || ! rangeCount) return NO;
    
    HFASSERT(rangesAreInAscendingOrder([ranges objectEnumerator]));
    
    NSMutableArray *rangesToRestore = [NSMutableArray arrayWithCapacity:rangeCount];
    NSMutableArray *correspondingByteArrays = [NSMutableArray arrayWithCapacity:rangeCount];
    HFByteArray *bytes = [self byteArray];
    
    /* Enumerate the ranges in forward order so when we insert them, we insert later ranges before earlier ones, so we don't have to worry about shifting indexes */
    FOREACH(HFRangeWrapper *, rangeWrapper, ranges) {
        HFRange range = [rangeWrapper HFRange];
        if (range.length > 0) {
            [rangesToRestore addObject:[HFRangeWrapper withRange:HFRangeMake(range.location, 0)]];
            [correspondingByteArrays addObject:[bytes subarrayWithRange:range]];
            result = YES;
        }
    }
    
    if (result) [self _registerUndoOperationForInsertingByteArrays:correspondingByteArrays inRanges:rangesToRestore withSelectionAction:(selectAfterUndo ? eSelectResult : eSelectAfterResult)];    
    return result;
}

- (void)_commandDeleteRanges:(NSArray *)rangesToDelete {
    HFASSERT(rangesToDelete != selectedContentsRanges); //selectedContentsRanges is mutable - we really don't want to stash it away with undo
    HFASSERT(rangesAreInAscendingOrder([rangesToDelete objectEnumerator]));
    
    /* Delete all the selection - in reverse order */
    unsigned long long minSelection = ULLONG_MAX;
    BOOL somethingWasDeleted = NO;
    [self _registerCondemnedRangesForUndo:rangesToDelete selectingRangesAfterUndo:YES];
    NSUInteger rangeIndex = [rangesToDelete count];
    HFASSERT(rangeIndex > 0);
    while (rangeIndex--) {
        HFRange range = [rangesToDelete[rangeIndex] HFRange];
        minSelection = llmin(range.location, minSelection);
        if (range.length > 0) {
            [byteArray deleteBytesInRange:range];
            somethingWasDeleted = YES;
        }
    }
    
    HFASSERT(minSelection != ULLONG_MAX);
    if (somethingWasDeleted) {
        BEGIN_TRANSACTION();
        [self _addPropertyChangeBits:HFControllerContentValue | HFControllerContentLength];
        [self _setSingleSelectedContentsRange:HFRangeMake(minSelection, 0)];
        [self _updateDisplayedRange];
        END_TRANSACTION();
    }
    else {
        NSBeep();
    }
}

- (void)_commandInsertByteArrays:(NSArray *)byteArrays inRanges:(NSArray *)ranges withSelectionAction:(HFControllerSelectAction)selectionAction {
    HFASSERT(selectionAction < NUM_SELECTION_ACTIONS);
    REQUIRE_NOT_NULL(byteArrays);
    REQUIRE_NOT_NULL(ranges);
    HFASSERT([ranges count] == [byteArrays count]);
    NSUInteger index, max = [ranges count];
    HFByteArray *bytes = [self byteArray];
    HFASSERT(rangesAreInAscendingOrder([ranges objectEnumerator]));

    NSMutableArray *byteArraysToInsertOnUndo = [NSMutableArray arrayWithCapacity:max];
    NSMutableArray *rangesToInsertOnUndo = [NSMutableArray arrayWithCapacity:max];
    
    BEGIN_TRANSACTION();
    if (selectionAction == eSelectResult || selectionAction == eSelectAfterResult) {
        [selectedContentsRanges removeAllObjects];
    }
    unsigned long long endOfInsertedRanges = ULLONG_MAX;
    for (index = 0; index < max; index++) {
        HFRange range = [ranges[index] HFRange];
        HFByteArray *oldBytes = [bytes subarrayWithRange:range];
        [byteArraysToInsertOnUndo addObject:oldBytes];
        HFByteArray *newBytes = byteArrays[index];
        EXPECT_CLASS(newBytes, [HFByteArray class]);
        [bytes insertByteArray:newBytes inRange:range];
        HFRange insertedRange = HFRangeMake(range.location, [newBytes length]);
        HFRangeWrapper *insertedRangeWrapper = [HFRangeWrapper withRange:insertedRange];
        [rangesToInsertOnUndo addObject:insertedRangeWrapper];
        if (selectionAction == eSelectResult) {
            [selectedContentsRanges addObject:insertedRangeWrapper];
        }
        else {
            endOfInsertedRanges = HFMaxRange(insertedRange);
        }
    }
    if (selectionAction == eSelectAfterResult) {
        HFASSERT([ranges count] > 0);
        [selectedContentsRanges addObject:[HFRangeWrapper withRange:HFRangeMake(endOfInsertedRanges, 0)]];
    }
    
    if (selectionAction == ePreserveSelection) {
        HFASSERT([selectedContentsRanges count] > 0);
        [self _clipSelectedContentsRangesToLength:[self contentsLength]];
    }
    
    VALIDATE_SELECTION();
    HFASSERT([byteArraysToInsertOnUndo count] == [rangesToInsertOnUndo count]);
    [self _registerUndoOperationForInsertingByteArrays:byteArraysToInsertOnUndo inRanges:rangesToInsertOnUndo withSelectionAction:(selectionAction == ePreserveSelection ? ePreserveSelection : eSelectAfterResult)];
    [self _updateDisplayedRange];
    [self maximizeVisibilityOfContentsRange:[selectedContentsRanges[0] HFRange]];
    [self _addPropertyChangeBits:HFControllerContentValue | HFControllerContentLength | HFControllerSelectedRanges];
    END_TRANSACTION();
}

/* The user has hit undo after typing a string. */
- (void)_commandReplaceBytesAfterBytesFromBeginning:(unsigned long long)leftOffset upToBytesFromEnd:(unsigned long long)rightOffset withByteArray:(HFByteArray *)bytesToReinsert {
    HFASSERT(bytesToReinsert != NULL);
    
    BEGIN_TRANSACTION();
    HFByteArray *bytes = [self byteArray];
    unsigned long long contentsLength = [self contentsLength];
    HFASSERT(leftOffset <= contentsLength);
    HFASSERT(rightOffset <= contentsLength);
    HFASSERT(contentsLength - rightOffset >= leftOffset);
    HFRange rangeToReplace = HFRangeMake(leftOffset, contentsLength - rightOffset - leftOffset);
    [self _registerCondemnedRangesForUndo:[HFRangeWrapper withRanges:&rangeToReplace count:1] selectingRangesAfterUndo:NO];
    [bytes insertByteArray:bytesToReinsert inRange:rangeToReplace];
    [self _updateDisplayedRange];
    [self _setSingleSelectedContentsRange:HFRangeMake(rangeToReplace.location, [bytesToReinsert length])];
    [self _addPropertyChangeBits:HFControllerContentValue | HFControllerContentLength | HFControllerSelectedRanges];
    END_TRANSACTION();
}

/* We use NSNumbers instead of long longs here because Tiger/PPC NSInvocation had trouble with long longs */
- (void)_commandValueObjectsReplaceBytesAfterBytesFromBeginning:(NSNumber *)leftOffset upToBytesFromEnd:(NSNumber *)rightOffset withByteArray:(HFByteArray *)bytesToReinsert {
    HFASSERT(leftOffset != NULL);
    HFASSERT(rightOffset != NULL);
    EXPECT_CLASS(leftOffset, NSNumber);
    EXPECT_CLASS(rightOffset, NSNumber);
    [self _commandReplaceBytesAfterBytesFromBeginning:[leftOffset unsignedLongLongValue] upToBytesFromEnd:[rightOffset unsignedLongLongValue] withByteArray:bytesToReinsert];
}

- (void)moveInDirection:(HFControllerMovementDirection)direction byByteCount:(unsigned long long)amountToMove withSelectionTransformation:(HFControllerSelectionTransformation)transformation usingAnchor:(BOOL)useAnchor {
    if (! useAnchor) selectionAnchor = NO_SELECTION;
    switch (transformation) {
        case HFControllerDiscardSelection:
            [self _moveDirectionDiscardingSelection:direction byAmount:amountToMove];
            break;
            
        case HFControllerShiftSelection:
            [self _shiftSelectionInDirection:direction byAmount:amountToMove];
            break;
            
        case HFControllerExtendSelection:
            [self _extendSelectionInDirection:direction byAmount:amountToMove];
            break;
            
        default:
            [NSException raise:NSInvalidArgumentException format:@"Invalid transformation %ld", (long)transformation];
            break;
    }
    if (! useAnchor) selectionAnchor = NO_SELECTION;
}

- (void)moveInDirection:(HFControllerMovementDirection)direction withGranularity:(HFControllerMovementGranularity)granularity andModifySelection:(BOOL)extendSelection {
    HFASSERT(granularity == HFControllerMovementByte || granularity == HFControllerMovementColumn || granularity == HFControllerMovementLine || granularity == HFControllerMovementPage || granularity == HFControllerMovementDocument);
    HFASSERT(direction == HFControllerDirectionLeft || direction == HFControllerDirectionRight);
    unsigned long long bytesToMove = 0;
    switch (granularity) {
        case HFControllerMovementByte:
            bytesToMove = 1;
            break;
        case HFControllerMovementColumn:
            /* This is a tricky case because the amount we have to move depends on our position in the column. */
            bytesToMove = [self _distanceToWordBoundaryForDirection:direction];
            break;
        case HFControllerMovementLine:
            bytesToMove = [self bytesPerLine];
            break;
        case HFControllerMovementPage:
            bytesToMove = HFProductULL([self bytesPerLine], HFFPToUL(MIN(floorl([self displayedLineRange].length), 1.)));
            break;
        case HFControllerMovementDocument:
            bytesToMove = [self contentsLength];
            break;
    }
    HFControllerSelectionTransformation transformation = (extendSelection ? HFControllerExtendSelection : HFControllerDiscardSelection);
    [self moveInDirection:direction byByteCount:bytesToMove withSelectionTransformation:transformation usingAnchor:YES];
}

- (void)moveToLineBoundaryInDirection:(HFControllerMovementDirection)direction andModifySelection:(BOOL)modifySelection {
    HFASSERT(direction == HFControllerDirectionLeft || direction == HFControllerDirectionRight);
    BEGIN_TRANSACTION();
    unsigned long long locationToMakeVisible;
    HFRange additionalSelection;
    
    if (direction == HFControllerDirectionLeft) {
        /* If we are at the beginning of a line, this should be a no-op */
        unsigned long long minLocation = [self _minimumSelectionLocation];
        unsigned long long newMinLocation = (minLocation / bytesPerLine) * bytesPerLine;
        locationToMakeVisible = newMinLocation;
        additionalSelection = HFRangeMake(newMinLocation, minLocation - newMinLocation);
    }
    else {
        /* This always advances to the next line */
        unsigned long long maxLocation = [self _maximumSelectionLocation];
        unsigned long long proposedNewMaxLocation = HFRoundUpToNextMultipleSaturate(maxLocation, bytesPerLine);
        unsigned long long newMaxLocation = MIN([self contentsLength], proposedNewMaxLocation);
        HFASSERT(newMaxLocation >= maxLocation);
        locationToMakeVisible = newMaxLocation;
        additionalSelection = HFRangeMake(maxLocation, newMaxLocation - maxLocation);
    }
    
    if (modifySelection) {
        if (additionalSelection.length > 0) {
            [self _addRangeToSelection:additionalSelection];
            [self _addPropertyChangeBits:HFControllerSelectedRanges];
        }
    }
    else {
        [self _setSingleSelectedContentsRange:HFRangeMake(locationToMakeVisible, 0)];
    }
    [self _ensureVisibilityOfLocation:locationToMakeVisible];
    END_TRANSACTION();
}

- (void)deleteSelection {
    if ([self editMode] == HFOverwriteMode || ! [self editable]) {
        NSBeep();
    }
    else {
        [self _commandDeleteRanges:[HFRangeWrapper organizeAndMergeRanges:selectedContentsRanges]];
    }
}

// Called after Replace All is finished. 
- (void)replaceByteArray:(HFByteArray *)newArray {
    REQUIRE_NOT_NULL(newArray);
    EXPECT_CLASS(newArray, HFByteArray);
    HFRange entireRange = HFRangeMake(0, [self contentsLength]);
    if ([self editMode] == HFOverwriteMode && [newArray length] != entireRange.length) {
        NSBeep();
    }
    else {
        [self _commandInsertByteArrays:@[newArray] inRanges:[HFRangeWrapper withRanges:&entireRange count:1] withSelectionAction:ePreserveSelection];
    }
}

- (BOOL)insertData:(NSData *)data replacingPreviousBytes:(unsigned long long)previousBytes allowUndoCoalescing:(BOOL)allowUndoCoalescing {
    REQUIRE_NOT_NULL(data);
    BOOL result;
#if ! NDEBUG
    const unsigned long long startLength = [byteArray length];
    unsigned long long expectedNewLength;
    if ([self editMode] == HFOverwriteMode) {
        expectedNewLength = startLength;
    }    
    else {
        expectedNewLength = startLength + [data length] - previousBytes;
        FOREACH(HFRangeWrapper*, wrapper, [self selectedContentsRanges]) expectedNewLength -= [wrapper HFRange].length;
    }
#endif
    HFByteSlice *slice = [[HFSharedMemoryByteSlice alloc] initWithUnsharedData:data];
    HFASSERT([slice length] == [data length]);
    HFByteArray *array = [[preferredByteArrayClass() alloc] init];
    [array insertByteSlice:slice inRange:HFRangeMake(0, 0)];
    HFASSERT([array length] == [data length]);
    result = [self insertByteArray:array replacingPreviousBytes:previousBytes allowUndoCoalescing:allowUndoCoalescing];
    [slice release];
    [array release];
#if ! NDEBUG
    HFASSERT((result && [byteArray length] == expectedNewLength) || (! result && [byteArray length] == startLength));
#endif
    return result;
}

- (BOOL)_insertionModeCoreInsertByteArray:(HFByteArray *)bytesToInsert replacingPreviousBytes:(unsigned long long)previousBytes allowUndoCoalescing:(BOOL)allowUndoCoalescing outNewSingleSelectedRange:(HFRange *)outSelectedRange {
    HFASSERT([self editMode] == HFInsertMode);
    REQUIRE_NOT_NULL(bytesToInsert);
    
    /* Guard against overflow.  If [bytesToInsert length] + [self contentsLength] - previousBytes overflows, then we can't do it */
    HFASSERT([self contentsLength] >= previousBytes);
    if (! HFSumDoesNotOverflow([bytesToInsert length], [self contentsLength] - previousBytes)) {
        return NO; //don't do anything
    }
    
    
    unsigned long long amountDeleted = 0, amountAdded = [bytesToInsert length];
    HFByteArray *bytes = [self byteArray];
    
    /* Delete all the selection - in reverse order - except the last (really first) one, which we will overwrite. */
    NSArray *allRangesToRemove = [HFRangeWrapper organizeAndMergeRanges:[self selectedContentsRanges]];
    HFRange rangeToReplace = [allRangesToRemove[0] HFRange];
    HFASSERT(rangeToReplace.location == [self _minimumSelectionLocation]);
    NSUInteger rangeIndex, rangeCount = [allRangesToRemove count];
    HFASSERT(rangeCount > 0);
    NSMutableArray *rangesToDelete = [NSMutableArray arrayWithCapacity:rangeCount - 1];
    for (rangeIndex = rangeCount - 1; rangeIndex > 0; rangeIndex--) {
        HFRangeWrapper *rangeWrapper = allRangesToRemove[rangeIndex];
        HFRange range = [rangeWrapper HFRange];
        if (range.length > 0) {
            amountDeleted = HFSum(amountDeleted, range.length);
            [rangesToDelete insertObject:rangeWrapper atIndex:0];
        }
    }
    
    if ([rangesToDelete count] > 0) {
        HFASSERT(rangesAreInAscendingOrder([rangesToDelete objectEnumerator]));
        /* TODO: This is problematic because it overwrites the selection that gets set by _activateTypingUndoCoalescingForReplacingRange:, so we lose the first selection in a multiple selection scenario. */
        [self _registerCondemnedRangesForUndo:rangesToDelete selectingRangesAfterUndo:YES];
        NSEnumerator *enumer = [rangesToDelete reverseObjectEnumerator];
        HFRangeWrapper *rangeWrapper;
        while ((rangeWrapper = [enumer nextObject])) {
            [bytes deleteBytesInRange:[rangeWrapper HFRange]];
        }
    }
    
    rangeToReplace.length = HFSum(rangeToReplace.length, previousBytes);
    
    /* Insert data */
#if ! NDEBUG
    unsigned long long expectedLength = [byteArray length] + [bytesToInsert length] - rangeToReplace.length;
#endif
    [byteArray insertByteArray:bytesToInsert inRange:rangeToReplace];
#if ! NDEBUG
    HFASSERT(expectedLength == [byteArray length]);
#endif
    
    /* return the new selected range */
    *outSelectedRange = HFRangeMake(HFSum(rangeToReplace.location, amountAdded), 0);
    return YES;
}


- (BOOL)_overwriteModeCoreInsertByteArray:(HFByteArray *)bytesToInsert replacingPreviousBytes:(unsigned long long)previousBytes allowUndoCoalescing:(BOOL)allowUndoCoalescing outRangeToRemoveFromSelection:(HFRange *)outRangeToRemove {
    REQUIRE_NOT_NULL(bytesToInsert);
    const unsigned long long byteArrayLength = [byteArray length];
    const unsigned long long bytesToInsertLength = [bytesToInsert length];
    HFRange firstSelectedRange = [selectedContentsRanges[0] HFRange];
    HFRange proposedRangeToOverwrite = HFRangeMake(firstSelectedRange.location, bytesToInsertLength);
    HFASSERT(proposedRangeToOverwrite.location >= previousBytes);
    proposedRangeToOverwrite.location -= previousBytes;
    if (! HFRangeIsSubrangeOfRange(proposedRangeToOverwrite, HFRangeMake(0, byteArrayLength))) {
        /* The user tried to overwrite past the end */
        NSBeep();
        return NO;
    }
    
    [byteArray insertByteArray:bytesToInsert inRange:proposedRangeToOverwrite];
    
    *outRangeToRemove = proposedRangeToOverwrite;
    return YES;
}

- (BOOL)insertByteArray:(HFByteArray *)bytesToInsert replacingPreviousBytes:(unsigned long long)previousBytes allowUndoCoalescing:(BOOL)allowUndoCoalescing {
#if ! NDEBUG
    if (previousBytes > 0) {
        NSArray *selectedRanges = [self selectedContentsRanges];
        HFASSERT([selectedRanges count] == 1);
        HFRange selectedRange = [selectedRanges[0] HFRange];
        HFASSERT(selectedRange.location >= previousBytes); //don't try to delete more trailing bytes than we actually have!
    }
#endif
    REQUIRE_NOT_NULL(bytesToInsert);
    
    
    BEGIN_TRANSACTION();
    unsigned long long beforeLength = [byteArray length];
    BOOL inOverwriteMode = [self editMode] == HFOverwriteMode;
    HFRange modificationRange; //either range to remove from selection if in overwrite mode, or range to select if not
    BOOL success;
    if (inOverwriteMode) {
        success = [self _overwriteModeCoreInsertByteArray:bytesToInsert replacingPreviousBytes:previousBytes allowUndoCoalescing:allowUndoCoalescing outRangeToRemoveFromSelection:&modificationRange];
    }
    else {
        success = [self _insertionModeCoreInsertByteArray:bytesToInsert replacingPreviousBytes:previousBytes allowUndoCoalescing:allowUndoCoalescing outNewSingleSelectedRange:&modificationRange];
    }
    
    if (success) {
        /* Update our selection */
        [self _addPropertyChangeBits:HFControllerContentValue];
        [self _updateDisplayedRange];
        [self _addPropertyChangeBits:HFControllerContentValue];
        if (inOverwriteMode) {
            [self _removeRangeFromSelection:modificationRange withCursorLocationIfAllSelectionRemoved:HFMaxRange(modificationRange)];
            [self maximizeVisibilityOfContentsRange:[selectedContentsRanges[0] HFRange]];
        }
        else {
            [self _setSingleSelectedContentsRange:modificationRange];
            [self maximizeVisibilityOfContentsRange:modificationRange];
        }
        if (beforeLength != [byteArray length]) [self _addPropertyChangeBits:HFControllerContentLength];
    }
    END_TRANSACTION();
    return success;
}

- (void)deleteDirection:(HFControllerMovementDirection)direction {
    HFASSERT(direction == HFControllerDirectionLeft || direction == HFControllerDirectionRight);
    if ([self editMode] != HFInsertMode || ! [self editable]) {
        NSBeep();
        return;
    }
    unsigned long long minSelection = [self _minimumSelectionLocation];
    unsigned long long maxSelection = [self _maximumSelectionLocation];
    if (maxSelection != minSelection) {
        [self deleteSelection];
    }
    else {
        HFRange rangeToDelete = HFRangeMake(minSelection, 1);
        BOOL rangeIsValid;
        if (direction == HFControllerDirectionLeft) {
            rangeIsValid = (rangeToDelete.location > 0);
            rangeToDelete.location--;
        }
        else {
            rangeIsValid = (rangeToDelete.location < [self contentsLength]);
        }
        if (rangeIsValid) {
            BEGIN_TRANSACTION();
            [byteArray deleteBytesInRange:rangeToDelete];
            [self _setSingleSelectedContentsRange:HFRangeMake(rangeToDelete.location, 0)];
            [self _updateDisplayedRange];
            [self _addPropertyChangeBits:HFControllerSelectedRanges | HFControllerContentValue | HFControllerContentLength];
            END_TRANSACTION();
        }
    }
}

- (HFEditMode)editMode {
    return _hfflags.editMode;
}

- (void)setEditMode:(HFEditMode)val
{
    if (val != _hfflags.editMode) {
        _hfflags.editMode = val;
        // don't allow undo coalescing when switching modes
        [self _addPropertyChangeBits:HFControllerEditable];        
    }
}

- (void)reloadData {
    BEGIN_TRANSACTION();
    [cachedData release];
    cachedData = nil;
    [self _updateDisplayedRange];
    [self _addPropertyChangeBits: HFControllerContentValue | HFControllerContentLength];
    END_TRANSACTION();
}

#if BENCHMARK_BYTEARRAYS

+ (void)_testByteArray {
    HFByteArray* first = [[[HFFullMemoryByteArray alloc] init] autorelease];
    HFBTreeByteArray* second = [[[HFBTreeByteArray alloc] init] autorelease];    
    first = nil;
    //    second = nil;
    
    //srandom(time(NULL));
    
    unsigned opCount = 4096 * 512;
    unsigned long long expectedLength = 0;
    unsigned i;
    for (i=1; i <= opCount; i++) {
        @autoreleasepool {
        NSUInteger op;
        const unsigned long long length = [first length];
        unsigned long long offset;
        unsigned long long number;
        switch ((op = (random()%2))) {
            case 0: { //insert
                offset = random() % (1 + length);
                HFByteSlice* slice = [[HFRandomDataByteSlice alloc] initWithRandomDataLength: 1 + random() % 1000];
                [first insertByteSlice:slice inRange:HFRangeMake(offset, 0)];
                [second insertByteSlice:slice inRange:HFRangeMake(offset, 0)];
                expectedLength += [slice length];
                [slice release];
                break;
            }
            case 1: { //delete
                if (length > 0) {
                    offset = random() % length;
                    number = 1 + random() % (length - offset);
                    [first deleteBytesInRange:HFRangeMake(offset, number)];
                    [second deleteBytesInRange:HFRangeMake(offset, number)];
                    expectedLength -= number;
                }
                break;
            }
        }
        } // @autoreleasepool
    }
}

+ (void)_testAttributeArrays {
    HFByteRangeAttributeArray *naiveTree = [[HFNaiveByteRangeAttributeArray alloc] init];
    HFAnnotatedTreeByteRangeAttributeArray *smartTree = [[HFAnnotatedTreeByteRangeAttributeArray alloc] init];
    naiveTree = nil;
    //    smartTree = nil;
    
    NSString * const attributes[3] = {@"Alpha", @"Beta", @"Gamma"};
    
    const NSUInteger supportedIndexEnd = NSNotFound;
    NSUInteger round;
    for (round = 0; round < 4096 * 256; round++) {
        NSString *attribute = attributes[random() % (sizeof attributes / sizeof *attributes)];
        BOOL insert = ([smartTree isEmpty] || [naiveTree isEmpty] || (random() % 2));
        
        unsigned long long end = random();
        unsigned long long start = random();
        if (end < start) {
            unsigned long long temp = end;
            end = start;
            start = temp;
        }
        HFRange range = HFRangeMake(start, end - start);
        
        if (insert) {
            [naiveTree addAttribute:attribute range:range];
            [smartTree addAttribute:attribute range:range];
        }
        else {
            [naiveTree removeAttribute:attribute range:range];
            [smartTree removeAttribute:attribute range:range];
        }
    }
    
    [naiveTree release];
    [smartTree release];
}


+ (void)initialize {
    CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();
    srandom(0);
    [self _testByteArray];
    CFAbsoluteTime end = CFAbsoluteTimeGetCurrent();
    printf("Byte array time: %f\n", end - start);
    
    srandom(0);
    start = CFAbsoluteTimeGetCurrent();
    [self _testAttributeArrays];
    end = CFAbsoluteTimeGetCurrent();
    printf("Attribute array time: %f\n", end - start);
    
    exit(0);
}

#endif

@end