Source

Immutabase / immutabase.py

   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
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: eph

# 111003: version 0.01 实现 DictIndex 、MiscEntry 和 SingleFileStore
# 111004: version 0.02 实现 DiskHashIndex 、BinarySearchIndex 、MultiFileStore 等
# 111005: version 0.03 新的 BinarySearchIndex2
# 111005: version 0.04 实现 SeekPosIndex 、StringEntry 和 IntegerEntry ,性能提升
# 111006: version 0.05 初步实现 ModelEntry
# 111006: version 0.06 实现 SelfReferenceProperty 和 ListProperty ,ModelEntry 较完善
# 111007: version 0.07 完善基本数据类型的 Entry 和 Property
# 111007: version 0.08 实现 ListEntry 、LazyListEntry 和 LazyListProperty
# 111007: version 0.09 实现 MultiModel 和 Model.registerClass
# 111007: version 0.10 数据库支持附加模式(a)和 iter over
# 111008: version 0.11 修正零字节字符串引起的一些 bug 和 ModelEntry.id2pos 引起的 bug
# 111008: version 0.12 Store 加入 membuf 选项,默认写入时采用 cStringIO 代替文件
# 111008: version 0.13 Store 转写时使用 buffer 以修正文件过大时内存不足的 bug
# 120131: version 0.14 修正写入时不调用 close() 文件会出错的 bug
# 120309: version 0.15 修正 Immutabase 的 cache 或 caches 参数为 None 时出错的 bug
# 120312: version 0.16 去掉 Immutabase.__del__
# 120324: version 0.17 增加了 __len__ 接口,但只有某些索引能用
# 120327: version 0.18 ReferenceEntry.serialtype 改为 int
# 120328: version 0.19 修正 DiskHashIndex 在 entry.serialtype 为 int 时出错的 bug
# 120402: version 0.20 实现 SingleBlobStore
# 120423: version 0.21 增加 DeltaListEntry
# 120423: version 0.22 增加 LazyDeltaListEntry
# 120424: version 0.23 SingleBlobStore 增加 buffer_size 参数
# 120427: version 0.24 DeltaListEntry 改为输出 iterable


"""Immutabase - lightweight read-only key-value database.

# build database
>>> db = Immutabase('example.db', 'w')
>>> db['hello'] = 'world'
>>> db.close()

# query database
>>> db = Immutabase('example.db')
>>> db['hello']
'world'


Immutabase can be created with following options:

    Indexes:
        1. DictIndex (default) : fast in-memory hash table
        2. DiskHashIndex : in-disk hash table
        3. BinarySearchIndex : in-disk binary search
        4. BinarySearchIndex2 : in-disk binary search, unidirectionally
        5. ListIndex : consider database as an array
        6. SeekPosIndex : index of no index

    Entries:
        1. MiscEntry (default) : for any (pickle-dumpable) object
        2. StringEntry : for fixed or variable length string
        3. IntegerEntry : for 32 bit integer, entry of no entry
           UnsignedIntegerEntry : similar to IntegerEntry
           FloatEntry : similar to IntegerEntry
        4. InstanceEntry : for objects of same class/struct
        5. ReferenceEntry : for reference to foreign DB
        6. ListEntry : for lists of entry
           LazyListEntry : similar to ListEntry, but faster for large lists
        7. DeltaListEntry : for list of increasing nonnegative integers
           LazyDeltaListEntry : similar to DeltaListEntry, but with lazy evaluation
        8. ModelEntry : for GAE-like data modeling

    Stores:
        1. SingleFileStore (default) : whole DB in a file
        2. MultiFileStore : DB in multiple files
        3. SingleBlobStore : for GAE BlobStore

    Caches:
        1. None (default) : no cache
        2. DBGetCache : cache output object
        3. IndexQueryCache : cache index.query()
        4. EntryLoadCache : cache entry.load()

ModelEntry support a GAE-like data modeling, with following properties:

        1. MiscProperty : for any (pickle-dumpable) object
        2. IntegerProperty : for 32 bit integer
           (similarly: FloatProperty, DoubleProperty, ByteProperty,
            UnsignedByteProperty, UnsignedShortProperty, ShortProperty,
            LongProperty, UnsignedLongProperty, UnsignedIntegerProperty,
            Int64Property, UnsignedInt64Property)
        3. StringProperty : for fixed or variable length string
        4. ReferenceProperty : for reference to other Model
        5. ListProperty : for a list of properties
           LazyListProperty : similar to ListProperty, faster for large lists




Comparison of indexes:

        Disk Space         DiskHashIndex(x8)
            ^
            |                DiskHashIndex(x4)
            |       shelve
            |                    DiskHashIndex(x2)
            |
            | DictIndex[1]               DiskHashIndex(x1)[4]
            |                                          BinarySearchIndex2
            |                                            BinarySearchIndex
            |
            |       ListIndex[2]
            |
            + SeekPosIndex[3] ---------------------------------> Query Time

    [1] but use huge memory
    [2] but only accept small int as key
        for N < ~15000, shelve is faster than ListIndex
        for N > ~15000, shelve is slower than ListIndex
    [3] but key is picked by database
    [4] but extremely slow in failed query (KeyError)

"""


import os, struct, re
from functools import partial
from itertools import count, chain
from weakref import WeakKeyDictionary, WeakValueDictionary
from shutil import copyfileobj

try:
    import cPickle as pickle
except ImportError:
    import pickle

try:
    from cStringIO import StringIO
except ImportError:
    pass  # StringIO.StringIO is very slow, don't use it


BUFFER_SIZE = 1048576


#################
##             ##
##    Index    ##
##             ##
#################


class IndexBase(object):

    def init(self, store, mode, serialtype=str):
        if not isinstance(store, StoreBase):
            raise TypeError("store must be instance of StoreBase")
        if mode != 'r' and mode != 'w' and mode != 'a':
            raise ValueError("mode must be 'r', 'w' or 'a', not %r" % mode)
        if mode == 'r':
            def forbidden_method(*args, **kwargs):
                raise IOError('file not open for writing')
            self.insert = forbidden_method
        if serialtype != str and serialtype != int:
            raise TypeError("serialtype must be str or int")
        self.store = store
        self.mode = mode
        self.serialtype = serialtype

    def query(self, key):
        """Return file position by key."""
        raise NotImplementedError('must be implemented by subclass')

    def getsize(self):
        """Return entry count."""
        raise NotImplementedError('must be implemented by subclass')

    def positer(self):
        """Return an iterator yielding all file position in database."""
        raise NotImplementedError('must be implemented by subclass')

    def insert(self, data, key=None):
        """Insert data to store.
        If data is string, write to file, get written position.
        If data is integer, take it as position."""
        if self.mode == 'r': raise IOError('file not open for writing')
        raise NotImplementedError('must be implemented by subclass')

    def close(self):
        del self.store
        del self.mode
        del self.serialtype
        def forbidden_method(*args, **kwargs):
            raise IOError('file already closed')
        self.query = forbidden_method
        self.positer = forbidden_method
        self.insert = forbidden_method
        self.close = forbidden_method


class DictIndex(IndexBase):
    """DictIndex uses in-memory Python dict as index.
    This index is fastest while least memory efficient.

    This is the default Index of Immutabase.

    Key type limitaion: any pickle-dumpable hashable structure.

    >>> db = Immutabase('dict.db', 'w', index=DictIndex())
    >>> db['hello'] = 'world'
    >>> db.close()

    >>> db = Immutabase('dict.db', index=DictIndex())
    >>> db['hello']
    'world'
    """

    def init(self, store, mode, serialtype=str):
        IndexBase.init(self, store, mode, serialtype)
        if mode == 'r' or mode =='a':
            self.mappings = self.store.read(0, True)
        else:
            self.mappings = {}

    def query(self, key):
        return self.mappings[key]

    def getsize(self):
        return len(self.mappings)
    
    def positer(self):
        return self.mappings.itervalues()

    def insert(self, data, key):
        if self.mode == 'r': raise IOError('file not open for writing')
        if key in self.mappings: raise KeyError(key)  # key exists
        if self.serialtype == str: data = self.store.write(data)
        self.mappings[key] = data

    def close(self):
        if self.mode == 'w' or self.mode =='a':
            data = pickle.dumps(self.mappings, pickle.HIGHEST_PROTOCOL)
            self.store.write(data, 0, True)
        del self.mappings
        IndexBase.close(self)


class DiskHashIndex(IndexBase):
    """DiskHashIndex uses on-disk Hash table as index.
    Because Python built-in hash() function is not consistent in machines,
    CRC32 (zlib.crc32) is used as default. It can be replaced by any hash
    function that returns 32-bit integer.

    Key type limitaion: <type 'str'> .

    Size limitaion: database file size < ~4G  ( pos < 0xFFFFFFFF )
                    number of entries <= 134217728  ( 1 << 27 )
                    length of key str <= 0xFFFFFFFF

    >>> db = Immutabase('diskhash.db', 'w', index=DiskHashIndex())
    >>> db['hello'] = 'world'
    >>> db.close()

    >>> db = Immutabase('diskhash.db', index=DiskHashIndex())
    >>> db['hello']
    'world'
    """

    def __init__(self, hashfunc=None, sizefactor=4):

        if hashfunc is None:
            from zlib import crc32
            self._hash = crc32
        else:
            self._hash = hashfunc

        self._sizefactor = sizefactor

    def init(self, store, mode, serialtype=str):
        IndexBase.init(self, store, mode, serialtype)

        START_OFFSET = 4  # an integer representing table size
        BLOCK_SIZE = 8    # an integer of hash, an integer of position

        if mode == 'r':
            table_size, = struct.unpack('I', store.read(0, True, 4))
            
            def query(key):
                h = self._hash(key) & 0xFFFFFFFF
                ipos = START_OFFSET + (h % table_size) * BLOCK_SIZE
                while True:
                    h2, epos = struct.unpack('II',
                                        store.read(ipos, True, BLOCK_SIZE))
                    if epos == 0xFFFFFFFF: return -1
                    if h2 == h:
                        kl, = struct.unpack('I', store.read(epos, False, 4))
                        key2 = store.read(None, False, kl) if kl else ''
                        if key2 == key:
                            return epos + 4 + kl if serialtype == str else \
                                   struct.unpack('I',
                                                 store.read(None, False, 4))[0]
                    ipos += BLOCK_SIZE
    
            def positer():
                for i in xrange(table_size):
                    ipos = START_OFFSET + i * BLOCK_SIZE
                    h2, epos = struct.unpack('II',
                                        store.read(ipos, True, BLOCK_SIZE))
                    if epos == 0xFFFFFFFF: continue
                    kl, = struct.unpack('I', store.read(epos, False, 4))
                    key = store.read(None, False, kl) if kl else ''
                    yield epos + 4 + kl if serialtype == str else \
                               struct.unpack('I',
                                             store.read(None, False, 4))[0]

            def insert(*args, **kwargs):
                raise IOError('file not open for writing')

            def close():
                IndexBase.close(self)

        else:

            mappings = {}

            if mode == 'a':
                table_size, = struct.unpack('I', store.read(0, True, 4))
                for i in xrange(table_size):
                    ipos = START_OFFSET + i * BLOCK_SIZE
                    h2, epos = struct.unpack('II',
                                        store.read(ipos, True, BLOCK_SIZE))
                    if epos == 0xFFFFFFFF: continue
                    kl, = struct.unpack('I', store.read(epos, False, 4))
                    key = store.read(None, False, kl) if kl else ''
                    mappings[key] = epos

            def query(key):
                epos = mappings[key]
                epos = epos + 4 + len(key)
                if serialtype == int:
                    epos, = struct.unpack('I', store.read(epos, True, 4))
                return epos

            def getsize():
                return len(mappings)

            def positer():
                for epos in mappings.itervalues():
                    epos = epos + 4 + len(key)
                    if serialtype == int:
                        epos, = struct.unpack('I', store.read(epos, True, 4))
                    yield epos

            def insert(data, key):
                if key in mappings: raise KeyError(key)  # key exists
                # note that key and entry are read separately
                if serialtype == int:
                    epos = store.write(struct.pack('I', len(key)) + key +
                                       struct.pack('I', data))
                else:
                    epos = store.write(struct.pack('I', len(key)) + key)
                    store.write(data)
                mappings[key] = epos

            def close():

                # calculate table size
                if self._sizefactor:
                    table_size = int(len(mappings) * self._sizefactor)
                else:
                    table_sizes = [ 17, 37, 79, 163, 331, 673, 1361, 2729, 5471,
                                    10949, 21911, 43853, 87719, 175447, 350899,
                                    701819, 1403641, 2807303, 5614657, 11229331,
                                    22458671, 44917381, 89834777, 179669557,
                                    359339171, 718678369, 1437356741, 2147483647 ]
                    for i, table_size in enumerate(table_sizes):
                        if len(mappings) <= 1 << i:
                            break

                # save table size
                store.write(struct.pack('I', table_size), 0, True)

                # save hash blocks
                max_ipos = 0
                exists = set()
                for key, epos in mappings.iteritems():
                    h = self._hash(key) & 0xFFFFFFFF
                    tpos = h % table_size
                    ipos = START_OFFSET + tpos * BLOCK_SIZE
                    while tpos in exists:
                        tpos += 1
                        ipos += BLOCK_SIZE
                    exists.add(tpos)
                    if max_ipos < ipos: max_ipos = ipos
                    store.write(struct.pack('II', h, epos), ipos, True)

                # mark empty blocks
                tpos = 0
                ipos = START_OFFSET
                data = '\xFF'*BLOCK_SIZE
                while tpos < table_size:
                    if tpos not in exists: store.write(data, ipos, True)
                    tpos += 1
                    ipos += BLOCK_SIZE
                store.write(data, max_ipos+BLOCK_SIZE, True)

                IndexBase.close(self)

            self.getsize = getsize
        self.query = query
        self.positer = positer
        self.insert = insert
        self.close = close


class BinarySearchIndex(IndexBase):
    r"""BinarySearchIndex scan index file with binary search algorithm.

    'a' and 'a\0' are equal. If strlen is 4, 'abcde' is trimmed to 'abcd'.
    
    >>> db = Immutabase('binsearch.db', 'w', index=BinarySearchIndex())
    >>> db['hello'] = 'world'
    >>> db.close()

    >>> db = Immutabase('binsearch.db', index=BinarySearchIndex())
    >>> db['hello']
    'world'
    """

    def __init__(self, strlen=16):
        if strlen <= 0: raise ValueError('strlen must be > 0')
        self._strlen = strlen

    def init(self, store, mode, serialtype=str):
        IndexBase.init(self, store, mode, serialtype)

        START_OFFSET = 4               # an integer representing table size
        BLOCK_SIZE = self._strlen + 4  # key, an integer of position
        BLOCK_FMT = '%dsI' % self._strlen

        fillkey = partial(struct.pack, '%ds' % self._strlen)

        if mode == 'r':
            table_size, = struct.unpack('I', store.read(0, True, 4))

            def query(key):
                fkey = fillkey(key)
                start = 0
                end = table_size-1
                while start <= end:
                    mid = (start + end) >> 1
                    ipos = START_OFFSET + mid * BLOCK_SIZE
                    fkey2 = store.read(ipos, True, self._strlen)
                    if   fkey2 < fkey: start = mid + 1
                    elif fkey2 > fkey: end = mid - 1
                    else:
                        epos, = struct.unpack('I', store.read(None, True, 4))
                        return epos
                return -1

            def getsize():
                return table_size

            def positer():
                for i in xrange(table_size):
                    ipos = START_OFFSET + i * BLOCK_SIZE
                    fkey = store.read(ipos, True, self._strlen)
                    epos, = struct.unpack('I', store.read(None, True, 4))
                    yield epos

            def insert(*args, **kwargs):
                raise IOError('file not open for writing')

            def close():
                IndexBase.close(self)

        else:

            mappings = {}

            if mode == 'a':
                table_size, = struct.unpack('I', store.read(0, True, 4))
                for i in xrange(table_size):
                    ipos = START_OFFSET + i * BLOCK_SIZE
                    fkey = store.read(ipos, True, self._strlen)
                    epos, = struct.unpack('I', store.read(None, True, 4))
                    mappings[fkey] = epos

            def query(key):
                fkey = fillkey(key)
                return mappings[fkey]

            def getsize():
                return len(mappings)

            def positer():
                return mappings.itervalues()

            def insert(data, key):
                fkey = fillkey(key)
                if fkey in mappings: raise KeyError(key)  # key exists
                if serialtype == str: data = store.write(data)
                mappings[fkey] = data

            def close():
                # save table size
                store.write(struct.pack('I', len(mappings)), 0, True)

                # save blocks
                ipos = START_OFFSET
                for item in sorted(mappings.items()):
                    store.write(struct.pack(BLOCK_FMT, *item), ipos, True)
                    ipos += BLOCK_SIZE

                IndexBase.close(self)

        self.getsize = getsize
        self.query = query
        self.positer = positer
        self.insert = insert
        self.close = close


class BinarySearchIndex2(IndexBase):
    r"""BinarySearchIndex2 is similar to BinarySearchIndex, except the file
    reading is unidirectional during each single query. It takes a little
    bit more space (~150% index) but a little bit less time (~96%).
    
    'a' and 'a\0' are equal. If strlen is 4, 'abcde' is trimmed to 'abcd'.
    
    >>> db = Immutabase('binsearch2.db', 'w', index=BinarySearchIndex2())
    >>> db['hello'] = 'world'
    >>> db.close()

    >>> db = Immutabase('binsearch2.db', index=BinarySearchIndex2())
    >>> db['hello']
    'world'
    """

    def __init__(self, strlen=16):
        if strlen <= 0: raise ValueError('strlen must be > 0')
        self._strlen = strlen

    def init(self, store, mode, serialtype=str):
        IndexBase.init(self, store, mode, serialtype)

        START_OFFSET = 4               # an integer representing table size
        BLOCK_SIZE = self._strlen + 4  # key, an integer of position
        BLOCK_FMT = '%dsI' % self._strlen

        fillkey = partial(struct.pack, '%ds' % self._strlen)

        if mode == 'r':

            table_size, = struct.unpack('I', store.read(0, True, 4))

            # cache an offset list to speed up
            goffsets = []
            s = table_size
            while s:
                s //= 2
                goffsets.append(BLOCK_SIZE * (1 + s))

            def query(key):
                fkey = fillkey(key)
                ipos = START_OFFSET
                for goffset in goffsets:
                    fkey2 = store.read(ipos, True, self._strlen)
                    if   fkey2 > fkey: ipos += BLOCK_SIZE
                    elif fkey2 < fkey: ipos += goffset
                    else:
                        epos, = struct.unpack('I', store.read(None, True, 4))
                        return -1 if epos == 0xFFFFFFFF else epos
                return -1

            def positer():
                for i in xrange(table_size):
                    ipos = START_OFFSET + i * BLOCK_SIZE
                    fkey = store.read(ipos, True, self._strlen)
                    epos, = struct.unpack('I', store.read(None, True, 4))
                    if epos == 0xFFFFFFFF: continue
                    yield epos

            def insert(*args, **kwargs):
                raise IOError('file not open for writing')

            def close():
                IndexBase.close(self)

        else:

            mappings = {}

            if mode == 'a':
                table_size, = struct.unpack('I', store.read(0, True, 4))
                for i in xrange(table_size):
                    ipos = START_OFFSET + i * BLOCK_SIZE
                    fkey = store.read(ipos, True, self._strlen)
                    epos, = struct.unpack('I', store.read(None, True, 4))
                    if epos == 0xFFFFFFFF: continue
                    mappings[fkey] = epos

            def query(key):
                fkey = fillkey(key)
                return mappings[fkey]

            def getsize():
                return len(mappings)

            def positer():
                return mappings.itervalues()

            def insert(data, key):
                fkey = fillkey(key)
                if fkey in mappings: raise KeyError(key)  # key exists
                if serialtype == str: data = store.write(data)
                mappings[fkey] = data

            def close():

                # calculate table size
                table_size = 1
                while table_size < len(mappings):
                    table_size = table_size * 2 + 1

                # save table size
                store.write(struct.pack('I', table_size), 0, True)

                # save blocks
                def saveblocks(blocks, ipos, s):
                    if not blocks:
                        assert s == 1
                        store.write('\xFF'*BLOCK_SIZE, ipos, True)
                    else:
                        m = len(blocks) // 2
                        fkey, epos = blocks[m]
                        lblocks = blocks[:m]
                        gblocks = blocks[m+1:]
                        store.write(struct.pack(BLOCK_FMT, fkey, epos),
                                    ipos, True)
                        s //= 2
                        if s:
                            saveblocks(lblocks, ipos + BLOCK_SIZE, s)
                            saveblocks(gblocks, ipos + BLOCK_SIZE * (1 + s), s)
                        else:
                            assert not lblocks
                            assert not gblocks
                saveblocks(sorted(mappings.items()), START_OFFSET, table_size)

                IndexBase.close(self)

            self.getsize = getsize
        self.query = query
        self.positer = positer
        self.insert = insert
        self.close = close


class ListIndex(IndexBase):
    """ListIndex considers the database as a list by using integer key.

    Size limitaion: database file size < ~4G  ( pos < 0xFFFFFFFF )

    >>> db = Immutabase('list.db', 'w', index=ListIndex())
    >>> db[7] = 'hello'
    >>> db[3] = 'world'
    >>> db.close()

    >>> db = Immutabase('list.db', index=ListIndex())
    >>> db[7]
    'hello'
    >>> list(db)
    ['world', 'hello']
    """

    def init(self, store, mode, serialtype=str):
        IndexBase.init(self, store, mode, serialtype)

        START_OFFSET = 4  # an integer representing table size

        if mode == 'r':

            table_size, = struct.unpack('I', store.read(0, True, 4))
            
            def query(key):
                if key < 0 or key >= table_size: return -1
                epos, = struct.unpack('I',
                        store.read(START_OFFSET + key*4, True, 4))
                return -1 if epos == 0xFFFFFFFF else epos

            def getsize():
                return table_size

            def positer():
                for key in xrange(table_size):
                    epos, = struct.unpack('I',
                            store.read(START_OFFSET + key*4, True, 4))
                    if epos != 0xFFFFFFFF: yield epos

            def insert(*args, **kwargs):
                raise IOError('file not open for writing')

            def close():
                IndexBase.close(self)

        else:

            mappings = []

            if mode == 'a':
                table_size, = struct.unpack('I', store.read(0, True, 4))
                for i in xrange(table_size):
                    ipos = START_OFFSET + i * 4
                    epos, = struct.unpack('I', store.read(ipos, True, 4))
                    mappings.append(epos)

            def query(key):
                if key < 0 or key >= len(mappings): return -1
                epos = mappings[key]
                return -1 if epos == 0xFFFFFFFF else epos

            def getsize():
                return len(mappings)

            def positer():
                for epos in mappings:
                    if epos != 0xFFFFFFFF: yield epos

            def insert(data, key):
                if not isinstance(key, (int, long)) or key < 0:
                    raise TypeError('only accept positive integer as key')
                elif key >= len(mappings):
                    mappings.extend([0xFFFFFFFF] * (1 + key - len(mappings)))
                elif mappings[key] != 0xFFFFFFFF:
                    raise KeyError(key)  # key exists
                if serialtype == str: data = store.write(data)
                mappings[key] = data

            def close():

                # save table size
                table_size = len(mappings)
                store.write(struct.pack('I', table_size), 0, True)

                # save blocks
                for key, epos in enumerate(mappings):
                    store.write(struct.pack('I', epos),
                                START_OFFSET + key * 4, True)

                IndexBase.close(self)

        self.getsize = getsize
        self.query = query
        self.positer = positer
        self.insert = insert
        self.close = close


class SeekPosIndex(IndexBase):
    r"""SeekPosIndex is a type of index that has no index data.

    The "key", given by SeekPosIndex instead of user, is the file position.
    SeekPosIndex does not need to "query", so it is fastest index in this
    module. On the other hand, SeekPosIndex has no mechanism to check if a
    key is valid, neither would it raise a KeyError. It is NOT SAFE if you
    can not completely control the query key.

    Key type limitaion: keys are provided by SeekPosIndex.

    >>> db = Immutabase('seekkey.db', 'w', index=SeekPosIndex('base64'))
    >>> key1 = db.insert('hello')
    >>> key2 = db.insert('world')
    >>> db.close()
    >>> key1, key2
    ('A', 'M')

    >>> db = Immutabase('seekkey.db', index=SeekPosIndex('base64'))
    >>> db[key1], db[key2]
    ('hello', 'world')

    Available encodings: struct, base64, base64urlsafe, base128

    >>> index = SeekPosIndex()
    >>> index.encode(12345)
    12345
    >>> index.decode(54321)
    54321

    >>> index = SeekPosIndex('struct')
    >>> index.encode(0x90ABCDEF)
    '\xef\xcd\xab\x90'
    >>> index.decode('\xef\xcd\xab\x90')
    2427178479L

    >>> index = SeekPosIndex('base64')
    >>> map(index.encode, [0, 64, 65536])
    ['A', 'BA', 'QAA']
    >>> map(index.decode, ['A', 'BA', 'QAA'])
    [0, 64, 65536]

    >>> index = SeekPosIndex('base128')
    >>> map(index.encode, [0, 1024])
    ['\x80', '\x88\x80']
    >>> map(index.decode, ['\x80', '\x88\x80'])
    [0, 1024]
    """

    def __init__(self, encoding=None):

        if encoding is None:

            def decode(key):
                return key

            def encode(pos):
                return pos

        elif encoding == 'struct':

            def decode(key):
                return struct.unpack('I', key)[0]

            def encode(pos):
                return struct.pack('I', pos)

        elif encoding == 'base64' or \
             encoding == 'base64urlsafe':
            if encoding == 'base64':
                alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef' \
                           'ghijklmnopqrstuvwxyz0123456789+/'
            else:
                alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef' \
                           'ghijklmnopqrstuvwxyz0123456789-_'
            alphabet_d = dict(zip(alphabet, xrange(64)))

            def decode(key):
                pos = 0
                for c in key:
                    pos <<= 6
                    pos |= alphabet_d[c] & 0x3F
                return pos

            def encode(pos):
                key = []
                while pos > 0:
                    key.append(alphabet[pos & 0x3F])
                    pos >>= 6
                return ''.join(reversed(key)) if key else alphabet[0]

        elif encoding == 'base128':

            def decode(key):
                pos = 0
                for c in key:
                    pos <<= 7
                    pos |= ord(c) & 0x7F
                return pos

            def encode(pos):
                key = []
                while pos > 0:
                    key.append(chr(0x80 | (pos & 0x7F)))
                    pos >>= 7
                return ''.join(reversed(key)) if key else '\x80'

        self.encode = encode
        self.decode = decode

    def init(self, store, mode, serialtype=str):
        IndexBase.init(self, store, mode, serialtype)

        if mode == 'r':
            def insert(*args, **kwargs):
                raise IOError('file not open for writing')
        else:
            def insert(data, key=None):
                if key is not None: raise KeyError(key)  # key is not supported
                if serialtype == str: data = store.write(data)
                return self.encode(data)

        def positer():
            raise Exception('database with SeekPosIndex is not iterable')

        def close():
            IndexBase.close(self)

        self.query = self.decode
        self.positer = positer
        self.insert = insert
        self.close = close




#################
##             ##
##    Entry    ##
##             ##
#################


class EntryBase(object):

    serialtype = str

    def init(self, store):
        self.store = store

    def load(self, pos=None):
        """Load value with given position.
        If position is not given, load from current position."""
        raise NotImplementedError('must be implemented by subclass')

    def serialize(self, data):
        """Return an string that represents data."""
        raise NotImplementedError('must be implemented by subclass')

    def close(self):
        del self.store
        def forbidden_method(*args, **kwargs):
            raise IOError('file already closed')
        self.load = forbidden_method
        self.serialize = forbidden_method


class MiscEntry(EntryBase):
    """MiscEntry is used to store any pickle-dumpable object.
    This is the default Entry of Immutabase.

    Value type limitaion: any pickle-dumpable object.

    >>> db = Immutabase('misc.db', 'w', entry=MiscEntry())
    >>> db['hello'] = 'world'
    >>> db.close()

    >>> db = Immutabase('misc.db', entry=MiscEntry())
    >>> db['hello']
    'world'
    """

    def load(self, pos=None):
        return self.store.read(pos)

    def serialize(self, value):
        return pickle.dumps(value, pickle.HIGHEST_PROTOCOL)


class StringEntry(EntryBase):
    """StringEntry is used to store strings.

    Value type limitaion: <type 'str'> .

    Size limitaion: length of string <= 0xFFFFFFFF

    >>> db = Immutabase('string.db', 'w', entry=StringEntry())
    >>> db['hello'] = 'world'
    >>> db.close()

    >>> db = Immutabase('string.db', entry=StringEntry())
    >>> db['hello']
    'world'
    """

    def __init__(self, length=None):
        self.length = length

    def load(self, pos=None):
        if self.length:
            return self.store.read(pos, False, self.length)
        else:
            length, = struct.unpack('I', self.store.read(pos, False, 4))
            return self.store.read(None, False, length) if length else ''

    def serialize(self, value):
        if self.length:
            return struct.pack('%ds' % self.length, value)
        else:
            return struct.pack('I', len(value)) + value


class IntegerEntry(EntryBase):
    """IntegerEntry is used to store 32 bit integers.
    In fact, nothing is saved, just index.

    Value type limitaion: signed 32 bit integers.

    >>> db = Immutabase('string.db', 'w', entry=IntegerEntry())
    >>> db['hello'] = -1
    >>> db.close()

    >>> db = Immutabase('string.db', entry=IntegerEntry())
    >>> db['hello']
    -1
    """

    serialtype = int

    def load(self, pos=None):
        if pos & 0x80000000: return int(pos - 0x100000000)
        return pos

    def serialize(self, value):
        if not isinstance(value, (int, long)) or \
            value < -0x80000000 or value > 0x7FFFFFFF:
            raise TypeError('UnsignedIntegerEntry must be 32-bit integers')
        if value < 0: return value + 0x100000000
        return value


class UnsignedIntegerEntry(EntryBase):
    """UnsignedIntegerEntry is used to store unsigned 32 bit integers.
    In fact, nothing is saved, just index.

    Value type limitaion: unsigned 32 bit integers.

    >>> db = Immutabase('string.db', 'w', entry=UnsignedIntegerEntry())
    >>> db['hello'] = 0xFFFFFFFF
    >>> db.close()

    >>> db = Immutabase('string.db', entry=UnsignedIntegerEntry())
    >>> db['hello']
    4294967295L
    """

    serialtype = int

    def load(self, pos=None):
        return pos

    def serialize(self, value):
        if not isinstance(value, (int, long)) or \
            value < 0 or value > 0xFFFFFFFF:
            raise TypeError('UnsignedIntegerEntry must be '
                            'unsigned 32-bit integers')
        return value


class FloatEntry(EntryBase):
    """FloatEntry is used to store 32 bit floats.
    In fact, nothing is saved, just index.

    Value type limitaion: 32 bit floats.

    >>> db = Immutabase('string.db', 'w', entry=FloatEntry())
    >>> db['pi'] = 3.14159265358979323846264
    >>> db.close()

    >>> db = Immutabase('string.db', entry=FloatEntry())
    >>> db['pi']
    3.1415927410125732
    """

    serialtype = int

    def load(self, pos=None):
        return struct.unpack('f', struct.pack('I', pos))[0]

    def serialize(self, value):
        return struct.unpack('I', struct.pack('f', value))[0]


class InstanceEntry(EntryBase):
    """InstanceEntry is used to store objects of the same structure for
    disk usage efficiency.

    If cls is given, object is dumped with cls.__getstate__ and built with
    cls.__setstate__, just as in pickle, except class information is not
    saved. If cls is omitted, value is considered as tuple (even if given
    list).

    If fmt is given, data is serialized by struct module, otherwise pickle.

    Value type limitaion: objects of the same struct.

    >>> class Point(object):
    ...     def __init__(self, x, y):
    ...         self.x = x
    ...         self.y = y
    ...     def __repr__(self):
    ...         return 'Point(%r, %r)' % (self.x, self.y)
    ...     def __getstate__(self):
    ...         return self.x, self.y
    ...     def __setstate__(self, data):
    ...         self.x, self.y = data

    >>> db = Immutabase('instance1.db', 'w',
    ...                 entry=InstanceEntry(cls=Point))
    >>> db['a'] = Point(123, 456)
    >>> db.close()
    >>> db = Immutabase('instance1.db',
    ...                 entry=InstanceEntry(cls=Point))
    >>> db['a']
    Point(123, 456)

    >>> db = Immutabase('instance2.db', 'w',
    ...                 entry=InstanceEntry(fmt='I3s'))
    >>> db['China'] = (86, 'CHN')
    >>> db.close()
    >>> db = Immutabase('instance2.db',
    ...                 entry=InstanceEntry(fmt='I3s'))
    >>> db['China']
    (86, 'CHN')

    >>> db = Immutabase('instance3.db', 'w',
    ...                 entry=InstanceEntry(cls=Point, fmt='ii'))
    >>> db['a'] = Point(123, 456)
    >>> db.close()
    >>> db = Immutabase('instance3.db',
    ...                 entry=InstanceEntry(cls=Point, fmt='ii'))
    >>> db['a']
    Point(123, 456)

    """

    def __init__(self, **kwargs):
        self.cls = kwargs.get('cls', None)
        self.fmt = kwargs.get('fmt', '')
        self.size = struct.calcsize(self.fmt)

    def load(self, pos=None):

        if self.size:
            state = struct.unpack(self.fmt,
                                  self.store.read(pos, False, self.size))
        else:
            state = self.store.read(pos)

        if self.cls:
            value = object.__new__(self.cls)
            self.cls.__setstate__(value, state)
            return value
        else:
            return state

    def serialize(self, value):

        if self.cls:
            value = self.cls.__getstate__(value)

        if self.fmt:
            return struct.pack(self.fmt, *value)
        else:
            return pickle.dumps(value, pickle.HIGHEST_PROTOCOL)

    def close(self):
        del self.cls
        del self.fmt
        del self.size
        EntryBase.close(self)


class ReferenceEntry(EntryBase):
    """ReferenceEntry is used to store references.

    Value type limitaion: key of reference database.

    Size limitaion: database file size < ~4G  ( pos < 0xFFFFFFFF )

    >>> db0 = Immutabase('ref_target.db', 'w')
    >>> db0['hello'] = 'world'
    >>> db0.close()

    >>> db0 = Immutabase('ref_target.db')

    >>> db = Immutabase('ref.db', 'w', entry=ReferenceEntry(db0))
    >>> db.insert('hello', 'new key')
    >>> db.close()

    >>> db = Immutabase('ref.db', entry=ReferenceEntry(db0))
    >>> db['new key']
    'world'
    """

    serialtype = int

    def __init__(self, refdb):
        if not isinstance(refdb, Immutabase):
            raise TypeError("refdb must be instance of Immutabase")
        self.refdb = refdb

    def load(self, pos=None):
        return self.refdb.load(pos)

    def serialize(self, value):
        return self.refdb.query(value)

    def close(self):
        del self.refdb
        EntryBase.close(self)


class ListEntry(EntryBase):
    """ListEntry is used to store lists of entry.

    Size limitaion: list size <= 0xFFFFFFFF

    >>> db = Immutabase('list.db', 'w', entry=ListEntry(StringEntry()))
    >>> db['hello'] = ['hello', 'world']
    >>> db.close()

    >>> db = Immutabase('list.db', entry=ListEntry(StringEntry()))
    >>> db['hello']
    ['hello', 'world']

    >>> db = Immutabase('list.db', 'w', entry=ListEntry(IntegerEntry()))
    >>> db['hello'] = [123, 456, 789]
    >>> db.close()

    >>> db = Immutabase('list.db', entry=ListEntry(IntegerEntry()))
    >>> db['hello']
    [123, 456, 789]
    """

    def __init__(self, entry):
        if not isinstance(entry, EntryBase):
            raise TypeError("entry must be instance of EntryBase")
        self.entry = entry

    def init(self, store):
        EntryBase.init(self, store)
        self.entry.init(store)

    def load(self, pos=None):
        num, = struct.unpack('I', self.store.read(pos, False, 4))
        if num == 0:
            return []
        elif self.entry.serialtype == int:
            return map(self.entry.load,
                       struct.unpack('I' * num,
                                     self.store.read(None, False, 4 * num)))
        else:
            return [ self.entry.load() for i in xrange(num) ]

    def serialize(self, value):
        num = len(value)
        if self.entry.serialtype == int:
            return struct.pack('I', num) + \
                   struct.pack('I' * num, *map(self.entry.serialize, value))
        else:
            return struct.pack('I', num) + \
                   ''.join(map(self.entry.serialize, value))


class LazyListEntry(EntryBase):
    """LazyListEntry is ListEntry that optimized for large lists.

    Size limitaion: list size <= 0xFFFFFFFF

    >>> db = Immutabase('list.db', 'w', entry=LazyListEntry(StringEntry()))
    >>> db['hello'] = ['hello', 'world']
    >>> db.close()

    >>> db = Immutabase('list.db', entry=LazyListEntry(StringEntry()))
    >>> db['hello'][1]
    'world'

    >>> db = Immutabase('list.db', 'w', entry=LazyListEntry(IntegerEntry()))
    >>> db['hello'] = [123, 456, 789]
    >>> db.close()

    >>> db = Immutabase('list.db', entry=LazyListEntry(IntegerEntry()))
    >>> db['hello'][1]
    456
    """

    class _LazyList(object):
        def __init__(self, store, entry, poses):
            self.store = store
            self.entry = entry
            self.poses = poses
            self.array = {}
        def __len__(self):
            return len(self.poses)
        def __getitem__(self, key):
            if key in self.array:
                return self.array[key]
            else:
                self.array[key] = value = self.entry.load(self.poses[key])
                return value
        def __iter__(self):
            for i in xrange(len(self)):
                yield self[i]
        def __str__(self):
            return 'LazyList([%s])' % ', '.join(map(repr, self))
        def __repr__(self):
            return str(self)

    def __init__(self, entry):
        if not isinstance(entry, EntryBase):
            raise TypeError("entry must be instance of EntryBase")
        self.entry = entry

    def init(self, store):
        EntryBase.init(self, store)
        self.entry.init(store)

    def load(self, pos=None):
        num, = struct.unpack('I', self.store.read(pos, False, 4))
        poses = () if num == 0 else \
                struct.unpack('I' * num, self.store.read(None, False, 4 * num))
        return LazyListEntry._LazyList(self.store, self.entry, poses)

    def serialize(self, value):
        num = len(value)
        if self.entry.serialtype == int:
            return struct.pack('I', num) + \
                   struct.pack('I' * num, *map(self.entry.serialize, value))
        else:
            return struct.pack('I', num) + \
                   struct.pack('I' * num, *map(self.store.write,
                                           map(self.entry.serialize, value)))


class DeltaListEntry(EntryBase):
    """List of increasing nonnegative integers.

    >>> db = Immutabase('delta.db', 'w', entry=DeltaListEntry())
    >>> db[0] = [1, 3, 5, 10, 1000, 10000, 10001]
    >>> db.close()

    >>> db = Immutabase('delta.db', entry=DeltaListEntry())
    >>> list(db[0])
    [1, 3, 5, 10, 1000, 10000, 10001]
    """

    def load(self, pos=None):
        num, = struct.unpack('I', self.store.read(pos, False, 4))
        d = p = 0
        for c in self.store.read(None, False, num):
            c = ord(c)
            if c & 0x80:
                p += d | (c & 0x7F)
                yield p
                d = 0
            else:
                d = (d | c) << 7

    def serialize(self, value):
        data = []
        p = 0
        for i in value:
            if not i >= p: raise ValueError('must be list of increasing nonnegative integers')
            d = i - p ; p = i
            part = [ chr(0x80 | (d & 0x7F)) ]
            while d > 0x7F:
                d >>= 7
                part.append(chr(d & 0x7F))
            data.extend(reversed(part))
        return struct.pack('I', len(data)) + ''.join(data)


class LazyDeltaListEntry(EntryBase):
    """List of increasing nonnegative integers.

    >>> db = Immutabase('delta.db', 'w', entry=LazyDeltaListEntry())
    >>> db[0] = [1, 3, 5, 10, 1000, 10000, 10001]
    >>> db.close()

    >>> db = Immutabase('delta.db', entry=LazyDeltaListEntry())
    >>> list(db[0])
    [1, 3, 5, 10, 1000, 10000, 10001]
    """

    def load(self, pos=None):
        pos, = struct.unpack('I', self.store.read(pos, False, 4))
        d = p = 0
        for pos in xrange(pos + 4, pos + 4 + struct.unpack('I', self.store.read(pos, False, 4))[0]):
            c = ord(self.store.read(pos, False, 1))
            if c & 0x80:
                p += d | (c & 0x7F)
                yield p
                d = 0
            else:
                d = (d | c) << 7

    def serialize(self, value):
        data = []
        p = 0
        for i in value:
            if not i >= p: raise ValueError('must be list of increasing nonnegative integers')
            d = i - p ; p = i
            part = [ chr(0x80 | (d & 0x7F)) ]
            while d > 0x7F:
                d >>= 7
                part.append(chr(d & 0x7F))
            data.extend(reversed(part))
        return struct.pack('I', self.store.write(struct.pack('I', len(data)) + ''.join(data)))


class ModelEntry(EntryBase):
    """ModelEntry is used to implement GAE-like data modeling.

    >>> class Country(Model):
    ...     name = StringProperty()
    ...     abbr = StringProperty(3)
    ...     code = IntegerProperty()

    >>> class City(Model):
    ...     name = StringProperty()
    ...     country = ReferenceProperty(Country)

    >>> china = Country(name='China', abbr='CHN', code=86)
    >>> beijing = City(name='Beijing', country=china)
    >>> wuhan = City(name='Wuhan', country=china)

    >>> db = Immutabase('cities.db', 'w', entry=ModelEntry(City))
    >>> db['Beijing'] = beijing
    >>> db['Wuhan'] = wuhan
    >>> db.close()

    >>> db = Immutabase('cities.db', entry=ModelEntry(City))
    >>> db['Beijing']
    City(country=Country(abbr='CHN', code=86, name='China'), name='Beijing')
    >>> db['Wuhan']
    City(country=Country(abbr='CHN', code=86, name='China'), name='Wuhan')
    """

    serialtype = int

    def __init__(self, model):

        if not issubclass(model, ModelBase):
            raise TypeError("model must be subclass of ModelBase")

        self.model = model
        self.pos2obj = WeakValueDictionary()
        self.obj2pos = WeakKeyDictionary()

    def load(self, pos=None):
        return self.model._load(pos, self.store, self.pos2obj)

    def serialize(self, value):
        data = self.model._save(value, self.store, self.obj2pos)
        return data




#################
##             ##
##    Store    ##
##             ##
#################


class StoreBase(object):

    def open(self, filename, mode):
        """Called when the database is opening."""
        if not isinstance(filename, basestring):
            raise TypeError("filename must be instance of basestring")
        if mode != 'r' and mode != 'w' and mode != 'a':
            raise ValueError("mode must be 'r', 'w' or 'a', not %r" % mode)
        self.filename = filename
        self.mode = mode

    def read(self, pos=None, fromindex=False, length=0):
        """Read an object from database with given begin position.
        When length is given, a string is return.
        Otherwise, the object is unpacked by pickle.
        The given position is a remapped position for index or entry."""
        raise NotImplementedError('must be implemented by subclass')

    def write(self, value, pos=None, fromindex=False):
        """Write a string into database, return begin position.
        The string is usually a pickle-dumped object,
        The return position is a remapped position for index or entry."""
        if self.mode == 'r': raise IOError('file not open for writing')
        raise NotImplementedError('must be implemented by subclass')

    def close(self):
        """Called when the database is closing."""
        del self.filename
        del self.mode
        def forbidden_method(*args, **kwargs):
            raise IOError('file already closed')
        self.read = forbidden_method
        self.write = forbidden_method
        self.close = forbidden_method


class SingleFileStore(StoreBase):
    """SingleFileStore maintains whole database in a single file.

    This is the default Store of Immutabase.

    >>> db = Immutabase('single.db', 'w', store=SingleFileStore())
    >>> db['hello'] = 'world'
    >>> db.close()

    >>> db = Immutabase('single.db', 'a', store=SingleFileStore())
    >>> db['world'] = 'hello'
    >>> db.close()

    >>> db = Immutabase('single.db', store=SingleFileStore())
    >>> db['hello']
    'world'
    >>> db['world']
    'hello'
    """

    def __init__(self, membuf=True):
        """The membuf flag specifies whether in-memory buffer (cStringIO)
        instead of temp file is used. When on, store will use a lot of
        memory and gain over 3 times speed. It is meaningless in 'r' mode.
        Default value is True."""
        self.membuf = membuf

    def open(self, filename, mode):
        StoreBase.open(self, filename, mode)
        if self.mode == 'r':
            fin = open(filename, 'rb')
            index_length = pickle.load(fin)
            entry_length = pickle.load(fin)
            index_offset = fin.tell()
            entry_offset = index_offset + index_length

            def read(pos=None, fromindex=False, length=0):
                if pos is None: pass
                elif fromindex: fin.seek(pos + index_offset)
                else:           fin.seek(pos + entry_offset)
                if length: return fin.read(length)
                else: return pickle.load(fin)

            def write(value, pos=None, fromindex=False):
                raise IOError('file not open for writing')

            def close():
                fin.close()
                StoreBase.close(self)

        else:

            if self.membuf and 'StringIO' in globals():
                fout_index = StringIO()
                fout_entry = StringIO()
            else:
                from tempfile import TemporaryFile
                fout_index = TemporaryFile()
                fout_entry = TemporaryFile()

            self.fpos_index = None
            self.fpos_entry = None

            if self.mode == 'a':
                fin = open(filename, 'rb')
                index_length = pickle.load(fin)
                entry_length = pickle.load(fin)
                fout_index.write(fin.read(index_length))
                fout_entry.write(fin.read(entry_length))
                fin.close()

            def read(pos=None, fromindex=False, length=0):
                if fromindex:
                    if pos is not None:
                        if self.fpos_index is None:
                            self.fpos_index = fout_index.tell()
                        fout_index.seek(pos)
                    if length: return fout_index.read(length)
                    else: return pickle.load(fout_index)
                else:
                    if pos is not None:
                        if self.fpos_entry is None:
                            self.fpos_entry = fout_entry.tell()
                        fout_entry.seek(pos)
                    if length: return fout_entry.read(length)
                    else: return pickle.load(fout_entry)

            def write(value, pos=None, fromindex=False):
                if fromindex:
                    if pos is not None:
                        if self.fpos_index is None:
                            self.fpos_index = fout_index.tell()
                        fout_index.seek(pos)
                        fout_index.write(value)
                        return pos
                    elif self.fpos_index is not None:
                        fout_index.seek(self.fpos_index)
                    pos = fout_index.tell()
                    fout_index.write(value)
                    self.fpos_index = None
                else:
                    if pos is not None:
                        if self.fpos_entry is None:
                            self.fpos_entry = fout_entry.tell()
                        fout_entry.seek(pos)
                        fout_entry.write(value)
                        return pos
                    elif self.fpos_entry is not None:
                        fout_entry.seek(self.fpos_entry)
                    pos = fout_entry.tell()
                    fout_entry.write(value)
                    self.fpos_entry = None
                return pos

            def close():
                fout = open(self.filename, 'wb')

                fout_index.flush() ; fout_index.seek(0, os.SEEK_END)
                pickle.dump(fout_index.tell(), fout, pickle.HIGHEST_PROTOCOL)

                fout_entry.flush() ; fout_index.seek(0, os.SEEK_END)
                pickle.dump(fout_entry.tell(), fout, pickle.HIGHEST_PROTOCOL)

                fout_index.seek(0) ; copyfileobj(fout_index, fout, BUFFER_SIZE)
                fout_entry.seek(0) ; copyfileobj(fout_entry, fout, BUFFER_SIZE)

                fout.close()

                StoreBase.close(self)
        self.read = read
        self.write = write
        self.close = close


class SingleBlobStore(StoreBase):
    '''SingleBlobStore is similar to SingleFileStore except it is read-only
    and stored in Blobstore of Google App Engine.
    '''

    def __init__(self, buffer_size=1048576):
        self.buffer_size = buffer_size

    def open(self, filename, mode):
        StoreBase.open(self, filename, mode)
        if self.mode == 'r':
            from google.appengine.ext import blobstore
            fin = blobstore.BlobInfo.all().filter('filename =', filename).get().open(buffer_size=self.buffer_size)
            index_length = pickle.load(fin)
            entry_length = pickle.load(fin)
            index_offset = fin.tell()
            entry_offset = index_offset + index_length

            def read(pos=None, fromindex=False, length=0):
                if pos is None: pass
                elif fromindex: fin.seek(pos + index_offset)
                else:           fin.seek(pos + entry_offset)
                if length: return fin.read(length)
                else: return pickle.load(fin)

            def write(value, pos=None, fromindex=False):
                raise IOError('file not open for writing')

            def close():
                fin.close()
                StoreBase.close(self)

        else: raise ValueError('unsupported mode %r' % self.mode)

        self.read = read
        self.write = write
        self.close = close


class MultiFileStore(StoreBase):
    """MultiFileStore organize database in multiple files.
    The purpose is mainly for systems that have file size limitation, such
    as Google App Engine.

    For efficiency, MultiFileStore does NOT guarantee that the file size is
    less than a threshold. Even a data block (e.g. the hash table in
    DictIndex) could be larger than file size threshold. Instead,
    MultiFileStore manages the database so that it does not glow too large
    in most cases.

    If pos is given to write(), the store ensure that the data block can be
    accessed by given the same pos to read(). Otherwise, the store ensure
    that the data block can be accessed by return value of write().

    If pos is not given to read(), MultiFileStore assumes that it's reading
    the same data block (written with single write call) as previous call.

    >>> db = Immutabase('multi.db', 'w', store=MultiFileStore())
    >>> db['hello'] = 'world'
    >>> db.close()

    >>> db = Immutabase('multi.db', 'a', store=MultiFileStore())
    >>> db['world'] = 'hello'
    >>> db.close()

    >>> db = Immutabase('multi.db', store=MultiFileStore())
    >>> db['hello']
    'world'
    >>> db['world']
    'hello'
    """

    def __init__(self, size=8388608, membuf=True):
        """The membuf flag specifies whether in-memory buffer (cStringIO)
        instead of temp file is used. When on, store will use a lot of
        memory and gain over 3 times speed. It is meaningless in 'r' mode.
        Default value is True."""
        self.size = size
        self.membuf = membuf

    def open(self, filename, mode):
        StoreBase.open(self, filename, mode)

        if self.mode == 'r':

            fins_index = []
            for i in count():
                fn = filename + '.i%02d' % i
                if os.path.exists(fn):
                    fins_index.append(open(fn, 'rb'))
                else:
                    break

            fins_entry = []
            for fid in count():
                fn = filename + '.e%02d' % fid
                if os.path.exists(fn):
                    fins_entry.append(open(fn, 'rb'))
                else:
                    break

            fins = {True: fins_index, False: fins_entry}
            cfid = {True: 0, False: 0}
            cfin = {True: None, False: None}

            def read(pos=None, fromindex=False, length=0):
                if pos is not None:
                    fid, fpos = divmod(pos, self.size)
                    cfid[fromindex] = fid
                    fin = cfin[fromindex] = fins[fromindex][fid]
                    fin.seek(fpos)
                else:
                    fin = cfin[fromindex]
                if length: return fin.read(length)
                else: return pickle.load(fin)

            def write(value, pos=None, fromindex=False):
                raise IOError('file not open for writing')

            def close():
                for fin in fins_index: fin.close()
                for fin in fins_entry: fin.close()
                StoreBase.close(self)

        else:

            if self.mode == 'w':
                # remove exist db files
                path = os.path.dirname(filename)
                base = os.path.basename(filename)
                pattern = re.compile(re.escape(base) + r'.[ie]\d+$')
                for fn in os.listdir(path):
                    if pattern.match(fn):
                        os.remove(os.path.join(path, fn))

            fouts_index = []
            fouts_entry = []

            fouts = {True: fouts_index, False: fouts_entry}
            cfid = {True: 0, False: 0}
            cfpos = {True: 0, False: 0}
            cfout = {True: None, False: None}

            if self.mode == 'a':
                for fid in count():
                    fn = filename + '.i%02d' % fid
                    if os.path.exists(fn):
                        fin = open(fn, 'rb') ; data = fin.read() ; fin.close()
                        if self.membuf and 'StringIO' in globals():
                            fout = StringIO()
                        else:
                            fout = open(fn, 'w+b')
                        fout.write(data)
                        fouts_index.append(fout)
                        cfid[True] = fid
                        cfpos[True] = None
                        cfout[True] = fout
                    else:
                        break
                for fid in count():
                    fn = filename + '.e%02d' % fid
                    if os.path.exists(fn):
                        fin = open(fn, 'rb') ; data = fin.read() ; fin.close()
                        if self.membuf and 'StringIO' in globals():
                            fout = StringIO()
                        else:
                            fout = open(fn, 'w+b')
                        fout.write(data)
                        fouts_entry.append(fout)
                        cfid[False] = fid
                        cfpos[False] = None
                        cfout[False] = fout
                    else:
                        break

            def getf(fid, fromindex=False):
                while fid >= len(fouts[fromindex]):
                    if self.membuf and 'StringIO' in globals():
                        fout = StringIO()
                    else:
                        fout = open(filename + '.%s%02d' % (
                                        'i' if fromindex else 'e',
                                        len(fouts[fromindex])), 'w+b')
                    fouts[fromindex].append(fout)
                cfid[fromindex] = fid
                cfout[fromindex] = fouts[fromindex][fid]
                return cfout[fromindex]

            def read(pos=None, fromindex=False, length=0):
                if pos is not None:
                    if cfpos[fromindex] is None:
                        cfpos[fromindex] = cfout[fromindex].tell() + \
                                           cfid[fromindex] * self.size
                    fid, fpos = divmod(pos, self.size)
                    getf(fid, fromindex).seek(fpos)
                if length: return cfout[fromindex].read(length)
                else: return pickle.load(cfout[fromindex])

            def write(value, pos=None, fromindex=False):
                if pos is not None:
                    if cfpos[fromindex] is None:
                        cfpos[fromindex] = cfout[fromindex].tell() + \
                                           cfid[fromindex] * self.size
                    fid, fpos = divmod(pos, self.size)
                    getf(fid, fromindex).seek(fpos)
                    cfout[fromindex].write(value)
                    return pos
                elif cfpos[fromindex] is not None:
                    pos = cfpos[fromindex]
                    fid, fpos = divmod(pos, self.size)
                    getf(fid, fromindex).seek(fpos)
                else:
                    if cfout[fromindex] is None:
                        cfout[fromindex] = getf(cfid[fromindex], fromindex)
                    fpos = cfout[fromindex].tell()
                    pos = fpos + cfid[fromindex] * self.size
                    if fpos >= self.size:
                        fid, fpos = divmod(pos, self.size)
                        getf(fid, fromindex).seek(fpos)
                cfout[fromindex].write(value)
                cfpos[fromindex] = None
                return pos

            def close():
                if self.membuf and 'StringIO' in globals():
                    for fid, fin in enumerate(fouts_index):
                        fout = open(filename + '.i%02d' % fid, 'wb')
                        fin.flush() ; fin.seek(0)
                        copyfileobj(fin, fout, BUFFER_SIZE)
                        fin.close() ; fout.close()
                    for fid, fin in enumerate(fouts_entry):
                        fout = open(filename + '.e%02d' % fid, 'wb')
                        fin.flush() ; fin.seek(0)
                        copyfileobj(fin, fout, BUFFER_SIZE)
                        fin.close() ; fout.close()
                else:
                    for fout in fouts_index: fout.close()
                    for fout in fouts_entry: fout.close()
                StoreBase.close(self)
        self.read = read
        self.write = write
        self.close = close




#################
##             ##
##    Model    ##
##             ##
#################


class Property(object):

    def _load(self, data, store, pos2obj, cls):
        raise NotImplementedError('must be implemented by subclass')

    def _save(self, buf, store, obj2pos, cls):
        raise NotImplementedError('must be implemented by subclass')


class MiscProperty(Property):

    def __init__(self):
        self.fmt = 'I'  # position
        self.default = None

    def _load(self, buf, store, pos2obj, cls):
        pos = buf.next()
        return store.read(pos)

    def _save(self, value, store, obj2pos, cls):
        return store.write(pickle.dumps(value, pickle.HIGHEST_PROTOCOL)),


class IntegerProperty(Property):
    fmt = 'i'

    def __init__(self):
        self.fmt = self.__class__.fmt
        self.default = 0

    def _load(self, buf, store, pos2obj, cls):
        return buf.next()

    def _save(self, value, store, obj2pos, cls):
        return value,


class UnsignedIntegerProperty(IntegerProperty):
    fmt = 'I'


class ByteProperty(IntegerProperty):
    fmt = 'b'


class UnsignedByteProperty(IntegerProperty):
    fmt = 'B'


class ShortProperty(IntegerProperty):
    fmt = 'h'


class UnsignedShortProperty(IntegerProperty):
    fmt = 'H'


class LongProperty(IntegerProperty):
    fmt = 'l'


class UnsignedLongProperty(IntegerProperty):
    fmt = 'L'


class Int64Property(IntegerProperty):
    fmt = 'q'


class UnsignedInt64Property(IntegerProperty):
    fmt = 'Q'


class FloatProperty(IntegerProperty):
    fmt = 'f'


class DoubleProperty(IntegerProperty):
    fmt = 'd'


class StringProperty(Property):

    def __init__(self, length=None):

        self.default = ''

        if length:
            self.fmt = '%ds' % length

            def _load(buf, store, pos2obj, cls):
                return buf.next().rstrip('\0')

            def _save(value, store, obj2pos, cls):
                if not isinstance(value, str):
                    raise TypeError('StringProperty must be instance of str')
                if len(value) > length:
                    raise ValueError('string length must <= %d' % length)
                return value,

        else:
            self.fmt = 'II'  # length , pos of string

            def _load(buf, store, pos2obj, cls):
                length = buf.next()
                pos = buf.next()
                return store.read(pos, False, length) if length else ''

            def _save(value, store, obj2pos, cls):
                if not isinstance(value, str):
                    raise TypeError('StringProperty must be instance of str')
                return len(value), store.write(value)

        self._load = _load
        self._save = _save


class ReferenceProperty(Property):

    def __init__(self, model):

        if not (isinstance(model, type) and issubclass(model, ModelBase)) and \
           not isinstance(model, str):
            raise TypeError("model must be subclass of ModelBase")

        self.fmt = 'I'  # pos of reference model
        self.default = None
        self.model = model

    def _load(self, buf, store, pos2obj, cls):
        if isinstance(self.model, str):
            self.model = ModelBase._registered_cls[self.model]
        pos = buf.next()
        if pos == 0xFFFFFFFF: return None
        return self.model._load(pos, store, pos2obj)

    def _save(self, value, store, obj2pos, cls):
        if isinstance(self.model, str):
            self.model = ModelBase._registered_cls[self.model]
        if value is None: return 0xFFFFFFFF,
        return self.model._save(value, store, obj2pos),


class ListProperty(Property):
    """ListProperty is for a list of Property.

    >>> class Country(Model):
    ...     name = StringProperty()
    ...     cities = ListProperty(StringProperty())

    >>> db = Immutabase('model.db', 'w', entry=ModelEntry(Country))
    >>> db['China'] = Country(name='China', cities=['Beijing', 'Shanghai'])
    >>> db.close()

    >>> db = Immutabase('model.db', entry=ModelEntry(Country))
    >>> db['China']
    Country(cities=['Beijing', 'Shanghai'], name='China')
    """

    def __init__(self, prop=None):

        if prop is None: prop = MiscProperty()
        elif not isinstance(prop, Property):
            raise TypeError('ListProperty prop must be instance of Property')

        self.fmt = 'II'  # length , pos of array

        def _load(buf, store, pos2obj, cls):
            length = buf.next()
            pos = buf.next()
            if length == 0: return []
            fmt = prop.fmt * length
            size = struct.calcsize(fmt)
            assert size > 0
            buf = iter(struct.unpack(fmt, store.read(pos, False, size)))
            return [ prop._load(buf, store, pos2obj, cls)
                     for i in xrange(length) ]

        def _save(value, store, obj2pos, cls):
            length = len(value)
            fmt = prop.fmt * length
            size = struct.calcsize(fmt)
            # keep file direction to speed up query
            pos = store.write('\0' * size)
            data = struct.pack(fmt, *chain.from_iterable(
                        prop._save(item, store, obj2pos, cls)
                        for item in value))
            assert len(data) == size
            store.write(data, pos)
            return length, pos

        self._load = _load
        self._save = _save

    @property
    def default(self):
        return []


class LazyListProperty(Property):
    """LazyListProperty is ListProperty that optimized for large lists.

    >>> class Country(Model):
    ...     name = StringProperty()
    ...     cities = LazyListProperty(StringProperty())

    >>> db = Immutabase('model.db', 'w', entry=ModelEntry(Country))
    >>> db['China'] = Country(name='China', cities=['Beijing', 'Shanghai'])
    >>> db.close()

    >>> db = Immutabase('model.db', entry=ModelEntry(Country))
    >>> db['China'].cities[0]
    'Beijing'
    """

    class _LazyList(object):
        def __init__(self, store, pos2obj, cls, prop, poses):
            self.store = store
            self.pos2obj = pos2obj
            self.cls = cls
            self.prop = prop
            self.size = struct.calcsize(prop.fmt)
            self.poses = poses
            self.array = {}
            assert self.size > 0
        def __len__(self):
            return len(self.poses)
        def __getitem__(self, key):
            if key in self.array:
                return self.array[key]
            else:
                pos = self.poses[key]
                buf = iter(struct.unpack(self.prop.fmt,
                        self.store.read(pos, False, self.size)))
                self.array[key] = value = self.prop._load(buf,
                        self.store, self.pos2obj, self.cls)
                return value
        def __iter__(self):
            for i in xrange(len(self)):
                yield self[i]
        def __str__(self):
            return 'LazyList([%s])' % ', '.join(map(repr, self))
        def __repr__(self):
            return str(self)

    def __init__(self, prop=None):

        if prop is None: prop = MiscProperty()
        elif not isinstance(prop, Property):
            raise TypeError('ListProperty prop must be instance of Property')

        self.fmt = 'II'  # length , pos of array

        def _load(buf, store, pos2obj, cls):
            length = buf.next()
            pos = buf.next()
            poses = () if length == 0 else \
                    struct.unpack('I' * length,
                                  store.read(pos, False, 4 * length))
            return LazyListProperty._LazyList(store, pos2obj, cls, prop, poses)

        def _save(value, store, obj2pos, cls):
            length = len(value)
            # keep file direction to speed up query
            pos = store.write('\0' * (4 * length))
            poses = [ store.write(
                            struct.pack(prop.fmt,
                                   *prop._save(item, store, obj2pos, cls)))
                      for item in value ]
            store.write(struct.pack('I' * length, *poses), pos)
            return length, pos

        self._load = _load
        self._save = _save

    @property
    def default(self):
        return []


class PropertiedClass(type):
    def __init__(cls, clsname, basecls, clsdict):

        # dealing with multiple inheritance
        # name duplication is solved by Python
        # name in alphabetical order just as dir()
        _properties = []
        for name in dir(cls):
            prop = getattr(cls, name)
            if isinstance(prop, Property):
                _properties.append((name, prop))

        cls._properties = _properties
        cls._struct_fmt = ''.join(prop.fmt
                                  for name, prop in cls._properties)
        cls._struct_len = struct.calcsize(cls._struct_fmt)


class ModelBase(object):

    @classmethod
    def _load(cls, pos, store, pos2obj):
        raise NotImplementedError('must be implemented by subclass')

    @classmethod
    def _save(cls, obj, store, obj2pos):
        raise NotImplementedError('must be implemented by subclass')
    
    _registered_cls = {}

    @staticmethod
    def registerClass(name, cls):
        if not isinstance(name, str):
            raise ValueError('name must be instance of str')
        if not issubclass(cls, ModelBase):
            raise ValueError('cls must be subclass of ModelBase')
        ModelBase._registered_cls[name] = cls


class Model(ModelBase):

    __metaclass__ = PropertiedClass

    def __new__(cls, **kwargs):
        obj = super(Model, cls).__new__(cls)
        for name, prop in cls._properties:
            setattr(obj, name, kwargs.get(name, prop.default))
        return obj

    @classmethod
    def _load(cls, pos, store, pos2obj):
        if pos in pos2obj: return pos2obj[pos]
        pos2obj[pos] = obj = object.__new__(cls)
        assert cls._struct_len > 0
        buf = iter(struct.unpack(cls._struct_fmt,
                                 store.read(pos, False, cls._struct_len)))
        for name, prop in cls._properties:
            setattr(obj, name, prop._load(buf, store, pos2obj, cls))
        return obj

    @classmethod
    def _save(cls, obj, store, obj2pos):
        if obj in obj2pos: return obj2pos[obj]
        assert cls._struct_len > 0
        obj2pos[obj] = pos = store.write('\xFF'*cls._struct_len)
        data = struct.pack(cls._struct_fmt, *chain.from_iterable(
                        prop._save(getattr(obj, name), store, obj2pos, cls)
                        for name, prop in cls._properties))
        assert len(data) == cls._struct_len
        store.write(data, pos)
        return pos

    @classmethod
    def _to_str(cls, obj):
        if obj in Model._to_str_ellipsis:
            return '...'
        else:
            Model._to_str_ellipsis.add(obj)
            return '%s(%s)' % (cls.__name__, ', '.join('%s=%r' % (name,
                        getattr(obj, name)) for name, prop in cls._properties))

    def __str__(self):
        if not hasattr(Model, '_to_str_ellipsis'):
            Model._to_str_ellipsis = set()
            value = self.__class__._to_str(self)
            del Model._to_str_ellipsis
        else:
            value = self.__class__._to_str(self)
        return value

    def __repr__(self):
        return self.__str__()


def MultiModel(*models):
    """Implement one of defined models.

    >>> class Country(Model):
    ...     name = StringProperty()
    ...     abbr = StringProperty(3)
    ...     code = IntegerProperty()

    >>> class City(Model):
    ...     name = StringProperty()
    ...     country = ReferenceProperty(Country)

    >>> china = Country(name='China', abbr='CHN', code=86)
    >>> beijing = City(name='Beijing', country=china)
    >>> wuhan = City(name='Wuhan', country=china)

    >>> db = Immutabase('multi.db', 'w',
    ...                 entry=ModelEntry(MultiModel(Country, City)))
    >>> db['China'] = china
    >>> db['Beijing'] = beijing
    >>> db.close()

    >>> db = Immutabase('multi.db',
    ...                 entry=ModelEntry(MultiModel(Country, City)))
    >>> db['China']
    Country(abbr='CHN', code=86, name='China')
    >>> db['Beijing']
    City(country=Country(abbr='CHN', code=86, name='China'), name='Beijing')
    """
    models = list(models)
    if len(models) > 256:
        raise ValueError('number of models must be <= 256')
    if not all((isinstance(model, type) and issubclass(model, ModelBase)) or
               isinstance(model, str) for model in models):
        raise TypeError('model must be subclass of ModelBase')

    class MultiModel(ModelBase):

        @classmethod
        def _load(cls, pos, store, pos2obj):
            pos, mid = struct.unpack('IB', store.read(pos, False, 5))
            model = models[mid]
            if isinstance(model, str):
                models[mid] = model = ModelBase._registered_cls[model]
            return model._load(pos, store, pos2obj)

        @classmethod
        def _save(cls, obj, store, obj2pos):
            if not hasattr(cls, 'cls2mid'):
                cls.cls2mid = dict((ModelBase._registered_cls[model]
                                       if isinstance(model, str) else model, i)
                                   for i, model in enumerate(models))
            mid = cls.cls2mid[obj.__class__]

            # keep file direction to speed up query
            pos = store.write('\0'*5)
            mpos = obj.__class__._save(obj, store, obj2pos)
            store.write(struct.pack('IB', mpos, mid), pos)
            return pos

    return MultiModel




#################
##             ##
##    Cache    ##
##             ##
#################


class CacheBase(object):
    
    def __init__(self):
        pass

    def decorate(self, func):
        mappings = {}
        failures = set()
        def new_func(key):
            if key in failures:
                raise KeyError(key)
            else:
                try:
                    return mappings[key]
                except KeyError:
                    try:
                        value = func(key)
                    except KeyError:
                        failures.add(key)
                        raise
                    mappings[key] = value
                    return value
        return new_func

    def init(self, db, index, entry, store):
        raise NotImplementedError('must be implemented by subclass')


class DBGetCache(CacheBase):
    """DBGetCache cache the result of Immutabase.get.

    >>> db = Immutabase('example.db', 'w')
    >>> db['key'] = [1, 2, 3]
    >>> db.close()

    >>> db = Immutabase('example.db', cache=DBGetCache())
    >>> a = db['key']
    >>> b = db['key']
    >>> a
    [1, 2, 3]
    >>> b
    [1, 2, 3]
    >>> id(a) == id(b)
    True
    """
    def init(self, db, index, entry, store):
        db.get = self.decorate(db.get)


class IndexQueryCache(CacheBase):
    """IndexQueryCache cache the result of index.query.
    Useful for indexes except DictIndex.

    >>> db = Immutabase('example.db', 'w')
    >>> db['hello'] = 'world'
    >>> db.close()

    >>> db = Immutabase('example.db', cache=IndexQueryCache())
    >>> db['hello']
    'world'
    """
    def init(self, db, index, entry, store):
        index.query = self.decorate(index.query)


class EntryLoadCache(CacheBase):
    """EntryLoadCache cache the result of entry.load.

    >>> db = Immutabase('example.db', 'w')
    >>> db['hello'] = 'world'
    >>> db.close()

    >>> db = Immutabase('example.db', cache=EntryLoadCache())
    >>> db['hello']
    'world'
    """
    def init(self, db, index, entry, store):
        entry.load = self.decorate(entry.load)




####################
##                ##
##    Database    ##
##                ##
####################


class Immutabase(object):

    def __init__(self, filename, mode='r', **kwargs):

        self.closed = False

        if mode != 'r' and mode != 'w' and mode != 'a':
            raise ValueError("mode must be 'r', 'w' or 'a', not %r" % mode)

        self.index = kwargs.get('index') or DictIndex()
        self.entry = kwargs.get('entry') or MiscEntry()
        self.store = kwargs.get('store') or SingleFileStore()

        if not isinstance(self.index, IndexBase):
            raise TypeError("index must be instance of IndexBase")
        if not isinstance(self.entry, EntryBase):
            raise TypeError("entry must be instance of EntryBase")
        if not isinstance(self.store, StoreBase):
            raise TypeError("store must be instance of StoreBase")

        self.store.open(filename, mode)
        self.index.init(self.store, mode, self.entry.serialtype)
        self.entry.init(self.store)
        self.query = self.index.query
        self.load = self.entry.load

        if mode == 'r':
            if 'caches' in kwargs and kwargs['caches'] is not None:
                for cache in kwargs['caches']:
                    if not isinstance(cache, CacheBase):
                        raise TypeError("cache must be instance of CacheBase")
                    cache.init(self, self.index, self.entry, self.store)
            elif 'cache' in kwargs and kwargs['cache'] is not None:
                if not isinstance(kwargs['cache'], CacheBase):
                    raise TypeError("cache must be instance of CacheBase")
                kwargs['cache'].init(self, self.index, self.entry, self.store)

    def insert(self, value, key=None):
        return self.index.insert(self.entry.serialize(value), key)

    def __setitem__(self, key, value):
        self.index.insert(self.entry.serialize(value), key)

    def __contains__(self, key):
        try:
            pos = self.index.query(key)
            if pos < 0: return False
            return True
        except KeyError:
            return False

    def get(self, key):
        pos = self.index.query(key)
        if pos < 0: raise KeyError(key)
        return self.entry.load(pos)

    def __getitem__(self, key):
        return self.get(key)

    def __len__(self):
        return self.index.getsize()

    def __iter__(self):
        for pos in self.index.positer():
            yield self.entry.load(pos)

    def close(self):
        if self.closed: return
        self.closed = True
        self.index.close()
        self.entry.close()
        self.store.close()
        del self.index
        del self.entry
        del self.store