Implemented Sort.
[idzebra-moved-to-github.git] / index / sortidx.c
1
2 #include <string.h>
3
4 #include <log.h>
5 #include <bfile.h>
6 #include <sortidx.h>
7
8 #define SORT_IDX_BLOCKSIZE 64
9
10 struct sortFileHead {
11     int sysno_max;
12 };
13
14 struct sortFile {
15     int type;
16     BFile bf;
17     struct sortFile *next;
18     struct sortFileHead head;
19 };
20
21 struct sortIdx {
22     BFiles bfs;
23     int write_flag;
24     int sysno;
25     char *entry_buf;
26     struct sortFile *current_file;
27     struct sortFile *files;
28 };
29
30 SortIdx sortIdx_open (BFiles bfs, int write_flag)
31 {
32     SortIdx si = xmalloc (sizeof(*si));
33     si->bfs = bfs;
34     si->write_flag = write_flag;
35     si->current_file = NULL;
36     si->files = NULL;
37     si->entry_buf = xmalloc (SORT_IDX_ENTRYSIZE);
38     return si;
39 }
40
41 void sortIdx_close (SortIdx si)
42 {
43     struct sortFile *sf = si->files;
44     while (sf)
45     {
46         struct sortFile *sf_next = sf->next;
47         if (sf->bf)
48             bf_close (sf->bf);
49         xfree (sf);
50         sf = sf_next;
51     }
52     xfree (si->entry_buf);
53     xfree (si);
54 }
55
56 int sortIdx_type (SortIdx si, int type)
57 {
58     char fname[80];
59     struct sortFile *sf;
60     if (si->current_file && si->current_file->type == type)
61         return 0;
62     for (sf = si->files; sf; sf = sf->next)
63         if (sf->type == type)
64         {
65             si->current_file = sf;
66             return 0;
67         }
68     sf = xmalloc (sizeof(*sf));
69     sf->type = type;
70     sf->bf = NULL;
71     sf->next = si->files;
72     si->current_file = si->files = sf;
73     sprintf (fname, "sort%d", type);
74     logf (LOG_DEBUG, "sort idx %s wr=%d", fname, si->write_flag);
75     sf->bf = bf_open (si->bfs, fname, SORT_IDX_BLOCKSIZE, si->write_flag);
76     if (!sf->bf)
77         return -1;
78     if (!bf_read (sf->bf, 0, 0, sizeof(sf->head), &sf->head))
79     {
80         sf->head.sysno_max = 0;
81         if (!si->write_flag)
82             return -1;
83     }
84     return 0;
85 }
86
87 void sortIdx_sysno (SortIdx si, int sysno)
88 {
89     si->sysno = sysno;
90 }
91
92 void sortIdx_add (SortIdx si, const char *buf, int len)
93 {
94     if (!si->current_file || !si->current_file->bf)
95         return;
96     if (len > SORT_IDX_ENTRYSIZE)
97     {
98         len = SORT_IDX_ENTRYSIZE;
99         memcpy (si->entry_buf, buf, len);
100     }
101     else
102     {
103         memcpy (si->entry_buf, buf, len);
104         memset (si->entry_buf+len, 0, SORT_IDX_ENTRYSIZE-len);
105     }
106     bf_write (si->current_file->bf, si->sysno+1, 0, 0, si->entry_buf);
107 }
108
109 void sortIdx_read (SortIdx si, char *buf)
110 {
111     bf_read (si->current_file->bf, si->sysno+1, 0, 0, buf);
112 }