forked from torifat/iAvro
-
Notifications
You must be signed in to change notification settings - Fork 3
/
AutoCorrect.m
105 lines (87 loc) · 2.76 KB
/
AutoCorrect.m
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
//
// AvroKeyboard
//
// Created by Rifat Nabi on 6/24/12.
// Copyright (c) 2012 OmicronLab. All rights reserved.
//
#import "AutoCorrect.h"
#import "AvroParser.h"
static AutoCorrect* sharedInstance = nil;
@implementation AutoCorrect
@synthesize autoCorrectEntries = _autoCorrectEntries;
+ (AutoCorrect *)sharedInstance {
if (sharedInstance == nil) {
[[self alloc] init]; // assignment not done here, see allocWithZone
}
return sharedInstance;
}
+ (id)allocWithZone:(NSZone *)zone {
if (sharedInstance == nil) {
sharedInstance = [super allocWithZone:zone];
return sharedInstance; // assignment and return on first allocation
}
return sharedInstance; //on subsequent allocation attempts return nil
}
- (id)copyWithZone:(NSZone *)zone {
return self;
}
- (id)retain {
return self;
}
- (oneway void)release {
//do nothing
}
- (id)autorelease {
return self;
}
- (NSUInteger)retainCount {
return NSUIntegerMax; // This is sooo not zero
}
- (id)init {
self = [super init];
if (self) {
// Open the file
NSString *fileName = [[NSBundle mainBundle] pathForResource:@"autodict" ofType:@"dct"];
const char *fn = [fileName UTF8String];
FILE *file = fopen(fn, "r");
// Read from the file
char replaceBuffer[512], withBuffer[512];
_autoCorrectEntries = [[NSMutableArray alloc] init];
while(fscanf(file, "%s %[^\n]\n", replaceBuffer, withBuffer) == 2) {
NSString* replace = [NSString stringWithFormat:@"%s", replaceBuffer];
NSString* with = [NSString stringWithFormat:@"%s", withBuffer];
if ([replace isEqualToString:with] == NO) {
with = [[AvroParser sharedInstance] parse:with];
}
NSMutableDictionary* item = [[NSMutableDictionary alloc] initWithObjectsAndKeys:replace, @"replace", with, @"with", nil];
[_autoCorrectEntries addObject:item];
[item release];
}
fclose(file);
}
return self;
}
- (void)dealloc {
[_autoCorrectEntries release];
[super dealloc];
}
// Instance Methods
- (NSString*)find:(NSString*)term {
term = [[AvroParser sharedInstance] fix:term];
// Binary Search
int left = 0, right = [_autoCorrectEntries count] -1, mid;
while (right >= left) {
mid = (left + right) / 2;
NSDictionary* item = [_autoCorrectEntries objectAtIndex:mid];
NSComparisonResult comp = [term compare:[item objectForKey:@"replace"]];
if (comp == NSOrderedDescending) {
left = mid + 1;
} else if (comp == NSOrderedAscending) {
right = mid - 1;
} else {
return [item objectForKey:@"with"];
}
}
return nil;
}
@end