summaryrefslogtreecommitdiff
path: root/src-worddic/texttrie.c
blob: 9497a029538b0222fba04af1b2219ba95aa3b661 (plain)
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
/*
 * DEPRECATED, it is too hard to debug.
 * you may use textdict instead
 *
 * Trie in Text
 *
 * *issues
 *  +correct API
 *   -iterator vs callback
 *  +robustness
 *   -error detection
 *   -auto correction
 *   -concurrent access
 *  +efficiency
 *   -lower memory consumption
 *   -disk space?
 *
 * on some file system like jffs2 on linux, writable mmap
 * is not allowed, though you can write it.
 *
 */
/*
 * API
 *  anthy_trie_open()
 *  anthy_trie_close()
 *  anthy_trie_add()
 *  anthy_trie_find()
 *  anthy_trie_delete()
 *  anthy_trie_find_next_key()
 *  anthy_trie_find_prefix()
 *  anthy_trie_print_array()
 *
 * Copyright (C) 2005-2006 TABATA Yusuke
 *
 */
/*
  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 */
/* open & mmap */
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
/**/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <anthy/texttrie.h>
#include <anthy/filemap.h>
#include "dic_main.h"

/* configs */
#define OBJ_LEN 20
#define LINE_LEN 32
#define EXPAND_COUNT 16

/* cell type */
#define TT_SUPER 0
#define TT_UNUSED 1
#define TT_ALLOCED 2
#define TT_NODE 3
#define TT_BODY 4
#define TT_TAIL 5

/* cell structure */
struct cell {
  /* (common) type */
  int type;
  /* union */
  union {
    /* unused */
    int next_unused;
    /* super */
    struct {
      int first_unused;
      int root_cell;
      int size;
      int serial;
    } super;
    /* node */
    struct {
      int key;
      int next;
      int child;
      int body;
      int parent;
    } node;
    /* body */
    struct {
      int owner;
      char *obj;
    } body;
    /* tail */
    struct {
      char *obj;
      int prev;
    } tail;
  } u;
  /* body & tail */
  int next_tail;
};

struct text_trie {
  /**/
  int fatal;
  /**/
  char *fn;
  FILE *wfp;
  struct filemapping *mapping;
  char *ptr;
  /**/
  struct cell super;
  int valid_super;
};

struct path {
  /**/
  const char *key_str;
  /**/
  int max_len;
  int *path;
  int len;
  int cur;
};

static void
print_super_cell(struct cell *c)
{
  printf("super first_unused=%d, root_cell=%d, size=%d, serial=%d\n",
	 c->u.super.first_unused, c->u.super.root_cell,
	 c->u.super.size, c->u.super.serial);
}

static void
print_alloced_cell(void)
{
  printf("alloc-ed\n");
}

static void
print_node_cell(struct cell *c)
{
  printf("node key=%d", c->u.node.key);
  if (c->u.node.key > 0 && isprint(c->u.node.key)) {
    printf("(%c)", c->u.node.key);
  }
  printf(" parent=%d next=%d child=%d body=%d\n",
	 c->u.node.parent, c->u.node.next, c->u.node.child, c->u.node.body);
}

static void
print_unused_cell(struct cell *c)
{
  printf("unused next_unused=%d\n",
	 c->u.next_unused);
}

static void
print_body_cell(struct cell *c)
{
  printf("body object=(%s), owner=%d, next_tail=%d\n",
	 c->u.body.obj, c->u.body.owner, c->next_tail);
}

static void
print_tail_cell(struct cell *c)
{
  printf("tail object=(%s), prev=%d, next_tail=%d\n",
	 c->u.tail.obj, c->u.tail.prev, c->next_tail);
}

static void
print_cell(int idx, struct cell *c)
{
  if (!c) {
    printf("idx =%d(null cell):\n", idx);
    return ;
  }
  printf("idx=%d:", idx);
  switch (c->type) {
  case TT_SUPER:
    print_super_cell(c);
    break;
  case TT_ALLOCED:
    print_alloced_cell();
    break;
  case TT_NODE:
    print_node_cell(c);
    break;
  case TT_UNUSED:
    print_unused_cell(c);
    break;
  case TT_BODY:
    print_body_cell(c);
    break;
  case TT_TAIL:
    print_tail_cell(c);
    break;
  default:
    printf("unknown\n");
  }
}

static void
path_setup(struct path *path, const char *key, int len, int *buf)
{
  unsigned char *p = (unsigned char *)key;
  path->key_str = key;
  path->max_len = len;
  path->path = buf;
  path->len = 0;
  path->cur = 0;
  /**/
  while (*p) {
    path->path[path->len] = p[0] * 256 + p[1];
    path->len ++;
    p++;
    if (p[0]) {
      p++;
    }
  }
}

static void
path_copy_to_str(struct path *path, char *str, int buf_len)
{
  unsigned char *p = (unsigned char *)str;
  int i, o;
  for (i = 0, o = 0; i < path->cur && o < buf_len - 2; i++) {
    p[o] = (path->path[i]>>8)&255;
    p[o+1] = path->path[i]&255;
    o += 2;
  }
  p[o] = 0;
}

static int
sput_int(char *buf, int num)
{
  unsigned char *tmp = (unsigned char *)buf;
  tmp[0] = (num>>24)&255;
  tmp[1] = (num>>16)&255;
  tmp[2] = (num>>8)&255;
  tmp[3] = num&255;
  return 4;
}

static char *
sget_int(char *buf, int *num)
{
  unsigned int res;
  unsigned char *tmp = (unsigned char *)buf;
  res = 0;
  res += tmp[0] << 24;
  res += tmp[1] << 16;
  res += tmp[2] << 8;
  res += tmp[3];
  *num = res;
  buf += 4;
  return buf;
}

static char *
pass_str(char *buf, const char *str)
{
  buf += strlen(str);
  return buf;
}

static void
encode_super(struct cell *c, char *buf)
{
  buf += sprintf(buf, "S ");
  buf += sput_int(buf, c->u.super.size);
  buf += sput_int(buf, c->u.super.root_cell);
  buf += sput_int(buf, c->u.super.first_unused);
  buf += sput_int(buf, c->u.super.serial);
  buf += sput_int(buf, LINE_LEN);
}

static void
encode_node(struct cell *c, char *buf)
{
  buf += sprintf(buf, "N ");
  buf += sput_int(buf, c->u.node.key);
  buf += sput_int(buf, c->u.node.parent);
  buf += sput_int(buf, c->u.node.next);
  buf += sput_int(buf, c->u.node.child);
  buf += sput_int(buf, c->u.node.body);
}

static void
encode_body(struct cell *c, char *buf)
{
  buf += sprintf(buf, "B");
  buf += sput_int(buf, c->next_tail);
  buf += sput_int(buf, c->u.body.owner);
  sprintf(buf, "\"%s\"",
	  c->u.body.obj);
}

static void
encode_unused(struct cell *c, char *buf)
{
  buf += sprintf(buf, "-next=");
  buf += sput_int(buf, c->u.next_unused);
}

static void
encode_tail(struct cell *c, char *buf)
{
  buf += sprintf(buf, "T");
  buf += sput_int(buf, c->u.tail.prev);
  buf += sput_int(buf, c->next_tail);
  sprintf(buf, "\"%s\"",
	  c->u.tail.obj);
}

static void
encode_unknown(char *buf)
{
  sprintf(buf, "?");
}

static void
encode_cell(struct cell *c, char *buf)
{
  switch (c->type) {
  case TT_SUPER:
    encode_super(c, buf);
    break;
  case TT_NODE:
    encode_node(c, buf);
    break;
  case TT_UNUSED:
    encode_unused(c, buf);
    break;
  case TT_BODY:
    encode_body(c, buf);
    break;
  case TT_TAIL:
    encode_tail(c, buf);
    break;
  default:
    encode_unknown(buf);
    break;
  }
}

static void
write_back_cell(struct text_trie *tt, struct cell *c, int idx)
{
  int i;
  char buf[LINE_LEN+1];
  /* sanity check */
  if (((anthy_mmap_size(tt->mapping) / LINE_LEN) < (idx + 1)) ||
      idx < 0) {
    return ;
  }
  for (i = 0; i < LINE_LEN; i++) {
    buf[i] = ' ';
  }
  encode_cell(c, buf);
  buf[LINE_LEN-1] = '\n';
  if (anthy_mmap_is_writable(tt->mapping)) {
    memcpy(&tt->ptr[idx*LINE_LEN], buf, LINE_LEN);
  } else {
    fseek(tt->wfp, idx*LINE_LEN, SEEK_SET);
    fwrite(buf, LINE_LEN, 1, tt->wfp);
    fflush(tt->wfp);
  }
}

static char *
decode_str(char *raw_buf, int off)
{
  char *head;
  char copy_buf[LINE_LEN + 1];
  char *buf;
  int i;
  /* from off to before last '\n' */
  for (i = 0; i < LINE_LEN - off - 1; i++) {
    copy_buf[i] = raw_buf[i];
  }
  copy_buf[i] = 0;
  buf = copy_buf;
  /* find first double quote */
  while (*buf && *buf != '\"') {
    buf ++;
  }
  if (!*buf) {
    /* cant find double quote */
    return strdup("");
  }
  buf ++;
  head = buf;
  /* go to the end of string */
  while (*buf) {
    buf ++;
  }
  /* find last double quote */
  while (*buf != '\"') {
    buf--;
  }
  *buf = 0;
  /**/
  return strdup(head);
}

static void
release_cell_str(struct cell *c)
{
  if (!c) {
    return ;
  }
  if (c->type == TT_BODY) {
    free(c->u.body.obj);
  }
  if (c->type == TT_TAIL) {
    free(c->u.tail.obj);
  }
}

static int
decode_super(struct cell *c, char *buf)
{
  c->type = TT_SUPER;
  buf = pass_str(buf, "S ");
  buf = sget_int(buf, &c->u.super.size);
  buf = sget_int(buf, &c->u.super.root_cell);
  buf = sget_int(buf, &c->u.super.first_unused);
  buf = sget_int(buf, &c->u.super.serial);
  return 0;
}

static int
decode_unuse(struct cell *c, char *buf)
{
  c->type = TT_UNUSED;
  buf = pass_str(buf, "-next=");
  buf = sget_int(buf, &c->u.next_unused);
  return 0;
}

static int
decode_node(struct cell *c, char *buf)
{
  c->type = TT_NODE;
  buf = pass_str(buf, "N ");
  buf = sget_int(buf, &c->u.node.key);
  buf = sget_int(buf, &c->u.node.parent);
  buf = sget_int(buf, &c->u.node.next);
  buf = sget_int(buf, &c->u.node.child);
  buf = sget_int(buf, &c->u.node.body);
  return 0;
}

static int
decode_body(struct cell *c, char *buf)
{
  c->type = TT_BODY;
  buf = pass_str(buf, "B");
  buf = sget_int(buf, &c->next_tail);
  buf = sget_int(buf, &c->u.body.owner);
  c->u.body.obj = decode_str(buf, 9);
  return 0;
}

static int
decode_tail(struct cell *c, char *buf)
{
  c->type = TT_TAIL;
  buf = pass_str(buf, "T");
  buf = sget_int(buf, &c->u.tail.prev);
  buf = sget_int(buf, &c->next_tail);
  c->u.tail.obj = decode_str(buf, 9);
  return 0;
}

static int
decode_alloced(struct cell *c)
{
  c->type = TT_ALLOCED;
  return 0;
}

static struct cell *
decode_nth_cell(struct text_trie *tt, struct cell *c, int nth)
{
  int res;
  char *buf;
  if (nth < 0 ||
      (anthy_mmap_size(tt->mapping) / LINE_LEN) <
      (nth + 1)) {
    return NULL;
  }
  buf = &tt->ptr[nth*LINE_LEN];

  res = -1;
  switch (buf[0]) {
  case 'S':
    res = decode_super(c, buf);
    break;
  case '-':
    res = decode_unuse(c, buf);
    break;
  case 'N':
    res = decode_node(c, buf);
    break;
  case 'B':
    res = decode_body(c, buf);
    break;
  case 'T':
    res = decode_tail(c, buf);
    break;
  case '?':
    res =  decode_alloced(c);
    break;
  default:
    /*printf("decode fail (nth=%d::%s).\n", nth, buf);*/
    ;
  }
  if (res) {
    c->type = TT_UNUSED;
  }
  return c;
}

static struct cell *
decode_nth_node(struct text_trie *tt, struct cell *c, int nth)
{
  if (!decode_nth_cell(tt, c, nth)) {
    return NULL;
  }
  if (c->type != TT_NODE) {
    return NULL;
  }
  return c;
}

static int
update_mapping(struct text_trie *tt)
{
  if (tt->mapping) {
    anthy_munmap(tt->mapping);
  }
  tt->mapping = anthy_mmap(tt->fn, 1);
  if (!tt->mapping) {
    /* try to fall back read-only mmap */
    tt->mapping = anthy_mmap(tt->fn, 0);
  }
  if (!tt->mapping) {
    tt->ptr = NULL;
    return 1;
  }
  tt->ptr = anthy_mmap_address(tt->mapping);
  return 0;
}

static int
expand_file(struct text_trie *tt, int count)
{
  char buf[LINE_LEN+1];
  int i;
  for (i = 0; i < LINE_LEN; i++) {
    buf[i] = ' ';
  }
  buf[LINE_LEN-1] = '\n';
  /**/
  for (i = 0; i < count; i++) {
    int res;
    res = fwrite(buf, LINE_LEN, 1, tt->wfp);
    if (res != 1) {
      return 1;
    }
    if (fflush(tt->wfp)) {
      return 1;
    }
  }
  return 0;
}

static int
set_file_size(struct text_trie *tt, int len)
{
  int size = LINE_LEN * len;
  int cur_size;
  int err = 0;

  fseek(tt->wfp, 0, SEEK_END);
  cur_size = ftell(tt->wfp);
  if (cur_size == size) {
    return 0;
  }
  if (cur_size > size) {
    truncate(tt->fn, size);
  } else {
    err = expand_file(tt, (size - cur_size) / LINE_LEN);
    if (!err) {
      update_mapping(tt);
    } else {
      tt->fatal = 1;
    }
  }

  return err;
}

static struct cell *
get_super_cell(struct text_trie *tt)
{
  /* cached? */
  if (tt->valid_super) {
    return &tt->super;
  }
  /* read */
  if (decode_nth_cell(tt, &tt->super, 0)) {
    tt->valid_super = 1;
    return &tt->super;
  }
  /* create now */
  tt->super.type = TT_SUPER;
  tt->super.u.super.first_unused = 0;
  tt->super.u.super.root_cell = 0;
  tt->super.u.super.size = 1;
  tt->super.u.super.serial = 1;
  if (set_file_size(tt, 1) != 0) {
    return NULL;
  }
  write_back_cell(tt, &tt->super, 0);
  tt->valid_super = 1;
  return &tt->super;
}

/* convenience function */
static int
get_array_size(struct text_trie *a)
{
  struct cell *super = get_super_cell(a);
  int size = super->u.super.size;
  return size;
}

/* convenience function */
static int
get_root_idx(struct text_trie *tt)
{
  struct cell *super = get_super_cell(tt);
  if (!super) {
    return 0;
  }
  return super->u.super.root_cell;
}

static int
expand_array(struct text_trie *tt, int len)
{
  int i;
  struct cell *super;
  int res;
  int size = get_array_size(tt);
  if (size >= len) {
    return 0;
  }
  /* expand file */
  res = set_file_size(tt, len);
  if (res) {
    return 1;
  }
  /* fill unused */
  super = get_super_cell(tt);
  for (i = super->u.super.size; i < len; i++) {
    struct cell ex_cell;
    ex_cell.type = TT_UNUSED;
    ex_cell.u.next_unused = super->u.super.first_unused;
    write_back_cell(tt, &ex_cell, i);
    super->u.super.first_unused = i;
  }
  super->u.super.size = len;
  write_back_cell(tt, super, 0);
  return 0;
}

void
anthy_trie_print_array(struct text_trie *tt)
{
  int i;
  int size = get_array_size(tt);
  print_cell(0, get_super_cell(tt));
  for (i = 1; i < size; i++) {
    struct cell c;
    decode_nth_cell(tt, &c, i);
    print_cell(i, &c);
    release_cell_str(&c);
  }
}

/* get unused cell */
static int
get_unused_index(struct text_trie *tt)
{
  struct cell *super;
  int unuse;
  struct cell new_cell;

  super = get_super_cell(tt);
  unuse = super->u.super.first_unused;
  if (!unuse) {
    /* expand array */
    expand_array(tt, super->u.super.size + EXPAND_COUNT);
    unuse = super->u.super.first_unused;
    if (!unuse) {
      return 0;
    }
  }
  if (!decode_nth_cell(tt, &new_cell, unuse)) {
    tt->fatal = 1;
    return 0;
  }
  super->u.super.first_unused = new_cell.u.next_unused;
  new_cell.type = TT_ALLOCED;
  write_back_cell(tt, &new_cell, unuse);
  write_back_cell(tt, super, 0);
  return unuse;
}

static void
free_cell(struct text_trie *tt, int idx)
{
  struct cell *super = get_super_cell(tt);
  struct cell c;
  if (!decode_nth_cell(tt, &c, idx)) {
    tt->fatal = 1;
  } else {
    c.type = TT_UNUSED;
    c.u.next_unused = super->u.super.first_unused;
    write_back_cell(tt, &c, idx);
  }
  super->u.super.first_unused = idx;
  write_back_cell(tt, super, 0);
}

static void
load_super(struct text_trie *tt)
{
  struct cell root, *super;
  int root_idx;
  super = get_super_cell(tt);
  if (!super) {
    tt->fatal = 1;
    return ;
  }
  /**/
  if (super->u.super.root_cell) {
    return ;
  }
  /**/
  root_idx = get_unused_index(tt);
  if (root_idx == 0) {
    tt->fatal = 1;
    return ;
  }
  root.u.node.key = 0;
  root.type = TT_NODE;
  root.u.node.parent = 0;
  root.u.node.next = 0;
  root.u.node.child = 0;
  root.u.node.body = 0;
  write_back_cell(tt, &root, root_idx);
  /**/
  tt->super.u.super.root_cell = root_idx;
  write_back_cell(tt, super, 0);
}

static void
purge_cache(struct text_trie *tt)
{
  if (tt) {
    tt->valid_super = 0;
  }
}

static FILE *
do_fopen(const char *fn, int create)
{
  int fd;
  if (!create) {
    /* check file existance */
    FILE *fp;
    fp = fopen(fn, "r");
    if (!fp) {
      return NULL;
    }
    fclose(fp);
  }
  fd = open(fn, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
  if (fd == -1) {
    return NULL;
  }
  return fdopen(fd, "w");
}

static struct text_trie *
alloc_tt(const char *fn, FILE *wfp)
{
  struct text_trie *tt;
  tt = malloc(sizeof(struct text_trie));
  tt->fatal = 0;
  tt->wfp = wfp;
  tt->valid_super = 0;
  tt->fn = strdup(fn);
  tt->mapping = NULL;
  return tt;
}

static void
clear_file(const char *fn)
{
  FILE *fp = fopen(fn, "w");
  if (fp) {
    fclose(fp);
  }
}

static struct text_trie *
trie_open(const char *fn, int create, int do_retry)
{
  struct text_trie *tt;
  FILE *fp;
  /**/
  fp = do_fopen(fn, create);
  if (!fp) {
    return NULL;
  }
  /**/
  tt = alloc_tt(fn, fp);
  if (!tt) {
    fclose(fp);
    return NULL;
  }
  /**/
  update_mapping(tt);
  load_super(tt);
  /**/
  if (tt->fatal) {
    anthy_trie_close(tt);
    if (!do_retry) {
      return NULL;
    }
    clear_file(fn);
    return trie_open(fn, create, 0);
  }
  /**/
  return tt;
}


/* API */
struct text_trie *
anthy_trie_open(const char *fn, int create)
{
  struct text_trie *tt;
  anthy_priv_dic_lock();
  tt = trie_open(fn, create, 1);
  anthy_priv_dic_unlock();
  purge_cache(tt);
  return tt;
}

/* API */
void
anthy_trie_close(struct text_trie *tt)
{
  if (!tt) {
    return ;
  }
  fclose(tt->wfp);
  anthy_munmap(tt->mapping);
  free(tt->fn);
  free(tt);
}

/* API */
void
anthy_trie_update_mapping(struct text_trie *tt)
{
  if (!tt) {
    return ;
  }
  anthy_priv_dic_lock();
  update_mapping(tt);
  anthy_priv_dic_unlock();
}

static void
graft_child(struct text_trie *tt, int parent_idx, int new_idx)
{
  struct cell parent_cell;
  struct cell new_cell;
  struct cell cur_youngest_cell;
  int cur_idx;
  /**/
  if (!decode_nth_node(tt, &parent_cell, parent_idx)) {
    return ;
  }
  /**/
  if (parent_cell.u.node.child == 0) {
    /* 1st child */
    parent_cell.u.node.child = new_idx;
    write_back_cell(tt, &parent_cell, parent_idx);
    return ;
  }

  if (!decode_nth_node(tt, &cur_youngest_cell, parent_cell.u.node.child)) {
    return ;
  }
  if (!decode_nth_node(tt, &new_cell, new_idx)) {
    return ;
  }
  if (new_cell.u.node.key < cur_youngest_cell.u.node.key) {
    /* newly added younger child */
    new_cell.u.node.next = parent_cell.u.node.child;
    parent_cell.u.node.child = new_idx;
    write_back_cell(tt, &new_cell, new_idx);
    write_back_cell(tt, &parent_cell, parent_idx);
    return;
  }

  /* insert some order */
  cur_idx = parent_cell.u.node.child;
  while (cur_idx) {
    int next_idx;
    struct cell cur_cell, tmp_cell;
    struct cell *next_cell = NULL;
    if (!decode_nth_node(tt, &cur_cell, cur_idx)) {
      return ;
    }
    next_idx = cur_cell.u.node.next;
    /**/
    if (next_idx) {
      next_cell = decode_nth_node(tt, &tmp_cell, next_idx);
    }
    if (!next_cell) {
      /* append */
      new_cell.u.node.next = 0;
      cur_cell.u.node.next = new_idx;
      write_back_cell(tt, &cur_cell, cur_idx);
      break;
    } else {
      if (cur_cell.u.node.key < new_cell.u.node.key &&
	  new_cell.u.node.key < next_cell->u.node.key) {
	cur_cell.u.node.next = new_idx;
	new_cell.u.node.next = next_idx;
	write_back_cell(tt, &cur_cell, cur_idx);
	break;
      }
    }
    cur_idx = next_idx;
  }
  write_back_cell(tt, &new_cell, new_idx);
}

static int
find_child(struct text_trie *tt, int parent_idx, int key, int exact)
{
  int child_idx;
  int prev_key;
  struct cell parent_cell;

  if (!decode_nth_node(tt, &parent_cell, parent_idx)) {
    return 0;
  }

  /**/
  prev_key = 0;
  child_idx = parent_cell.u.node.child;

  /**/
  while (child_idx) {
    struct cell child_cell;
    int this_key;
    /**/
    if (!decode_nth_node(tt, &child_cell, child_idx)) {
      return 0;
    }
    this_key = child_cell.u.node.key;
    if (this_key <= prev_key) {
      return 0;
    }
    /**/
    if (exact && this_key == key) {
      return child_idx;
    }
    if (!exact && (this_key & 0xff00) == (key & 0xff00)) {
      return child_idx;
    }
    child_idx = child_cell.u.node.next;
    prev_key = this_key;
  }
  return 0;
}

static int
trie_search_rec(struct text_trie *tt, struct path *p,
		int parent_idx, int create)
{
  int child_idx;
  int key = p->path[p->cur];
  /* special case */
  if (p->cur == p->len) {
    return parent_idx;
  }
  /* scan child */
  child_idx = find_child(tt, parent_idx, key, 1);
  if (!child_idx) {
    struct cell child_cell;
    if (!create) {
      return 0;
    }
    /* add child */
    child_idx = get_unused_index(tt);
    if (!child_idx) {
      return 0;
    }
    if (!decode_nth_cell(tt, &child_cell, child_idx)) {
      return 0;
    }
    child_cell.type = TT_NODE;
    child_cell.u.node.parent = parent_idx;
    child_cell.u.node.key = key;
    child_cell.u.node.next = 0;
    child_cell.u.node.child = 0;
    child_cell.u.node.body = 0;
    write_back_cell(tt, &child_cell, child_idx);
    /* graft */
    graft_child(tt, parent_idx, child_idx);
  }
  p->cur ++;
  key ++;
  if (!key) {
    return child_idx;
  }
  return trie_search_rec(tt, p, child_idx, create);
}

static char *
get_str_part(const char *str, int from)
{
  char buf[OBJ_LEN+1];
  int i;
  for (i = 0; i < OBJ_LEN; i++) {
    buf[i] = str[from+i];
  }
  buf[i] = 0;
  return strdup(buf);
}

static void
release_body(struct text_trie *tt, int idx)
{
  struct cell c;
  int tail_idx;
  if (!decode_nth_cell(tt, &c, idx) ||
      c.type != TT_BODY) {
    return ;
  }
  tail_idx = c.next_tail;
  while (tail_idx) {
    struct cell tail_cell;
    int tmp;
    if (!decode_nth_cell(tt, &tail_cell, tail_idx)) {
      break;
    }
    tmp = tail_cell.next_tail;
    free_cell(tt, tail_idx);
    tail_idx = tmp;
  }
  free_cell(tt, idx);
}

static void
set_body(struct text_trie *tt, int idx, const char *body_str)
{
  int body_idx = get_unused_index(tt);
  int len;
  int i;
  struct cell node_cell;
  struct cell body_cell;
  struct cell prev_cell;
  struct cell tail_cell;
  int prev_idx;
  /**/
  if (!decode_nth_cell(tt, &node_cell, idx)) {
    return ;
  }
  if (node_cell.u.node.body) {
    release_body(tt, node_cell.u.node.body);
  }
  len = strlen(body_str);
  /**/
  node_cell.u.node.body = body_idx;
  write_back_cell(tt, &node_cell, idx);
  /**/
  if (!decode_nth_cell(tt, &body_cell, body_idx)) {
    return ;
  }
  body_cell.type = TT_BODY;
  body_cell.u.body.obj = get_str_part(body_str, 0);
  body_cell.u.body.owner = idx;
  body_cell.next_tail = 0;
  write_back_cell(tt, &body_cell, body_idx);
  release_cell_str(&body_cell);
  /**/
  if (!decode_nth_cell(tt, &body_cell, body_idx)) {
    return ;
  }
  /**/
  prev_idx = body_idx;
  prev_cell = body_cell;
  for (i = OBJ_LEN; i < len; i += OBJ_LEN) {
    int tail_idx = get_unused_index(tt);
    if (!decode_nth_cell(tt, &tail_cell, tail_idx)) {
      return ;
    }
    tail_cell.type = TT_TAIL;
    tail_cell.u.tail.obj = get_str_part(body_str, i);
    tail_cell.u.tail.prev = prev_idx;
    tail_cell.next_tail = 0;
    prev_cell.next_tail = tail_idx;
    write_back_cell(tt, &tail_cell, tail_idx);
    write_back_cell(tt, &prev_cell, prev_idx);
    release_cell_str(&prev_cell);
    /**/
    prev_idx = tail_idx;
    prev_cell = tail_cell;
  }
  if (i != OBJ_LEN) {
    release_cell_str(&tail_cell);
  }
}

static int
trie_add(struct text_trie *tt, struct path *p, const char *body)
{
  int root_idx = get_root_idx(tt);
  int target_idx;
  /**/
  if (root_idx == 0) {
    return -1;
  }
  target_idx = trie_search_rec(tt, p, root_idx, 1);
  if (target_idx) {
    set_body(tt, target_idx, body);
  }
  return 0;
}

/* API */
int
anthy_trie_add(struct text_trie *tt, const char *key, const char *body)
{
  int res;
  int len;
  struct path p;
  if (!tt || tt->fatal) {
    return -1;
  }
  len = strlen(key);
  path_setup(&p, key, len, alloca(sizeof(int)*len));
  anthy_priv_dic_lock();
  res = trie_add(tt, &p, body);
  anthy_priv_dic_unlock();
  purge_cache(tt);
  return res;
}

static int
get_object_length(struct text_trie *tt, int body_idx)
{
  int len = 0;
  int idx = body_idx;
  while (idx) {
    struct cell c;
    if (!decode_nth_cell(tt, &c, idx)) {
      return 0;
    }
    idx = c.next_tail;
    len += OBJ_LEN;
    release_cell_str(&c);
  }
  return len;
}

static char *
gather_str(struct text_trie *tt, int body_idx)
{
  int idx;
  char *buf;
  int len;
  /* count length */
  len = get_object_length(tt, body_idx);
  if (len == 0) {
    return NULL;
  }
  /**/
  buf = malloc(len + 1);
  idx = body_idx;
  len = 0;
  while (idx) {
    struct cell c;
    if (!decode_nth_cell(tt, &c, idx)) {
      free(buf);
      return NULL;
    }
    if (len == 0) {
      sprintf(&buf[len], "%s", c.u.body.obj);
    } else {
      sprintf(&buf[len], "%s", c.u.tail.obj);
    }
    idx = c.next_tail;
    len += OBJ_LEN;
    release_cell_str(&c);
  }
  return buf;
}

static char *
trie_find(struct text_trie *tt, struct path *p)
{
  int root_idx;
  int target_idx;
  root_idx = get_root_idx(tt);
  if (!root_idx) {
    return NULL;
  }
  target_idx = trie_search_rec(tt, p, root_idx, 0);
  if (target_idx) {
    struct cell target_cell;
    int body_idx;
    if (!decode_nth_node(tt, &target_cell, target_idx)) {
      return NULL;
    }
    body_idx = target_cell.u.node.body;
    if (body_idx) {
      return gather_str(tt, body_idx);
    }
  }
  return NULL;
}

/* API */
char *
anthy_trie_find(struct text_trie *tt, char *key)
{
  char *res;
  struct path p;
  int len;
  if (!tt || tt->fatal) {
    return NULL;
  }
  len = strlen(key);
  path_setup(&p, key, len, alloca(sizeof(int)*len));
  anthy_priv_dic_lock();
  res = trie_find(tt, &p);
  anthy_priv_dic_unlock();
  purge_cache(tt);
  return res;
}

static int
do_find_next_key(struct text_trie *tt, struct path *p,
		 int root_idx, int target_idx)
{
  struct cell *target_cell, tmp_cell;
  int prev_is_up = 0;
  target_cell = decode_nth_node(tt, &tmp_cell, target_idx);
  /**/
  do {
    /* one step */
    if (!target_cell) {
      return -1;
    }
    if (!prev_is_up && target_cell->u.node.child) {
      prev_is_up = 0;
      target_idx = target_cell->u.node.child;
      p->cur++;
    } else if (target_cell->u.node.next) {
      prev_is_up = 0;
      target_idx = target_cell->u.node.next;
    } else if (target_cell->u.node.parent) {
      prev_is_up = 1;
      target_idx = target_cell->u.node.parent;
      p->cur--;
    } else {
      return -1;
    }
    target_cell = decode_nth_node(tt, &tmp_cell, target_idx);
    if (!target_cell) {
      return -1;
    }
    if (p->cur >= p->max_len) {
      continue;
    }
    if (p->cur == 0) {
      return -1;
    }
    p->path[p->cur-1] = target_cell->u.node.key;
    if (!prev_is_up && target_cell->u.node.body) {
      return 0;
    }
  } while (target_idx != root_idx);
  return -1;
}

static int
find_partial_key(struct text_trie *tt, struct path *p, int idx)
{
  struct cell c;
  if (!decode_nth_node(tt, &c, idx)) {
    return -1;
  }
  if (c.type != TT_NODE) {
    return -1;
  }
  p->len ++;
  p->path[p->cur] = c.u.node.key;
  p->cur ++;
  return 0;
}

static int
trie_find_next_key(struct text_trie *tt, struct path *p)
{
  int root_idx = get_root_idx(tt);
  int target_idx;
  int tmp_idx;
  /**/
  target_idx = trie_search_rec(tt, p, root_idx, 0);
  if (target_idx > 0) {
    /* easy case */
    return do_find_next_key(tt, p, root_idx, target_idx);
  }
  if ((p->path[p->len-1] & 0xff) != 0) {
    /* simply not exist in tree */
    return -1;
  }
  /* special case */
  p->len --;
  p->cur = 0;
  target_idx = trie_search_rec(tt, p, root_idx, 0);
  tmp_idx = find_child(tt, target_idx, p->path[p->len], 0);
  if (tmp_idx) {
    return find_partial_key(tt, p, tmp_idx);
  }
  return do_find_next_key(tt, p, root_idx, target_idx);
}


/* API */
char *
anthy_trie_find_next_key(struct text_trie *tt, char *buf, int buf_len)
{
  int res;
  struct path p;
  if (!tt || tt->fatal) {
    return NULL;
  }
  path_setup(&p, buf, buf_len, alloca(sizeof(int)*buf_len));
  anthy_priv_dic_lock();
  res = trie_find_next_key(tt, &p);
  anthy_priv_dic_unlock();
  purge_cache(tt);
  if (res) {
    return NULL;
  }
  path_copy_to_str(&p, buf, buf_len);
  return buf;
}

static void
trie_find_prefix(struct text_trie *tt, const char *str,
		       char *buf, int buf_len,
		       int (*cb)(const char *key, const char *str))
{
  int idx = get_root_idx(tt);
  int i, len = strlen(str);
  for (i = 0; i < len && i < buf_len; i++) {
    struct cell c;
    idx = find_child(tt, idx, str[i], 1);
    if (!idx) {
      return ;
    }
    if (!decode_nth_node(tt, &c, idx)) {
      return ;
    }
    buf[i] = idx;
    buf[i+1] = 0;
    if (c.u.node.body) {
      char *s = gather_str(tt, c.u.node.body);
      if (cb) {
	cb(buf, s);
      }
      free(s);
    }
  }
}

void
anthy_trie_find_prefix(struct text_trie *tt, const char *str,
		       char *buf, int buf_len,
		       int (*cb)(const char *key, const char *str))
{
  if (!tt || tt->fatal) {
    return ;
  }
  anthy_priv_dic_lock();
  trie_find_prefix(tt, str, buf, buf_len, cb);
  anthy_priv_dic_unlock();
  purge_cache(tt);
}

static void
disconnect(struct text_trie *tt, int parent_idx, int target_idx)
{
  struct cell parent_cell;
  struct cell target_cell;

  if (!decode_nth_node(tt, &parent_cell, parent_idx) ||
      !decode_nth_node(tt, &target_cell, target_idx)) {
    return ;
  }

  if (parent_cell.u.node.child == target_idx) {
    /* 1st child */
    parent_cell.u.node.child = target_cell.u.node.next;
    write_back_cell(tt, &parent_cell, parent_idx);
    if (!target_cell.u.node.next &&
	!parent_cell.u.node.body) {
      /* only child and parent does not have body, so traverse upward */
      disconnect(tt, parent_cell.u.node.parent, parent_idx);
      free_cell(tt, target_idx);
      return ;
    }
    free_cell(tt, target_idx);
  } else {
    /* not 1st child */
    int child_idx = parent_cell.u.node.child;
    while (child_idx) {
      struct cell cur;
      if (!decode_nth_cell(tt, &cur, child_idx)) {
	return ;
      }
      if (cur.u.node.next == target_idx) {
	/**/
	cur.u.node.next = target_cell.u.node.next;
	write_back_cell(tt, &cur, child_idx);
	free_cell(tt, target_idx);
	return ;
      }
      child_idx = cur.u.node.next;
    }
  }
}

static void
trie_delete(struct text_trie *tt, struct path *p)
{
  struct cell target_cell;
  int root_idx = get_root_idx(tt);
  int target_idx, parent_idx;
  target_idx = trie_search_rec(tt, p, root_idx, 0);
  if (!target_idx) {
    return ;
  }
  if (!decode_nth_node(tt, &target_cell, target_idx)) {
    return ;
  }
  release_body(tt, target_cell.u.node.body);
  target_cell.u.node.body = 0;
  write_back_cell(tt, &target_cell, target_idx);
  if (target_cell.u.node.child) {
    return ;
  }
  parent_idx = target_cell.u.node.parent;
  disconnect(tt, parent_idx, target_idx);
}

/* API */
void
anthy_trie_delete(struct text_trie *tt, const char *key)
{
  struct path p;
  int len;
  if (!tt || tt->fatal) {
    return ;
  }
  len = strlen(key);
  path_setup(&p, key, len, alloca(sizeof(int)*len));
  anthy_priv_dic_lock();
  trie_delete(tt, &p);
  anthy_priv_dic_unlock();
  purge_cache(tt);
}