/
Index.cs
71 lines (67 loc) · 2.33 KB
/
Index.cs
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.IsolatedStorage;
using System.Text;
using System.Threading;
namespace CC_CEDICT.WindowsPhone
{
public class Index : StreamLineArray<IndexRecord>
{
bool loaded = false;
Dictionary<string, int> lookup = new Dictionary<string, int>();
public Index(string path)
{
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (store.FileExists(path))
{
Debug.WriteLine(String.Format("Loading index file: {0}", path));
Stream stream = new IsolatedStorageFileStream(path, FileMode.Open, store);
if (!stream.CanRead)
return;
loaded = Read(stream);
}
}
}
public IndexRecord this[string key]
{
get
{
if (!loaded)
return null;
key = key.ToLower();
if (!lookup.ContainsKey(key))
lookup[key] = BinarySearch(key);
return lookup[key] < 0 ? null : this[lookup[key]];
}
}
int BinarySearch(string key)
{
CompareInfo ci = new CultureInfo("en-US").CompareInfo;
int min = 0, pos, max = this.Count - 1;
while (min <= max)
{
pos = (min + max) / 2;
switch (ci.Compare(key, this[pos].Key, CompareOptions.StringSort))
{
case -1:
max = pos - 1;
Debug.WriteLine("BinarySearch: compare {0} to {1} (down)", key, this[pos].Key);
break;
case 0:
Debug.WriteLine("BinarySearch: compare {0} to {1} (MATCH)", key, this[pos].Key);
return pos;
case 1:
min = pos + 1;
Debug.WriteLine("BinarySearch: compare {0} to {1} (up)", key, this[pos].Key);
break;
}
}
Debug.WriteLine("BinarySearch: not found.");
return -1;
}
}
}