কম্পিউটার বিজ্ঞান · বই 3 · স্নাতক প্রথম বর্ষ

University Computer Science — Year 1

এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।

University Computer Science — Year 1 · স্নাতক প্রথম বর্ষ

30Project: A Search Engine for a Folder of Texts

A folder holds four hundred texts, 1.9 megabytes in all, and someone wants to know which of them mention quartzite. Reading every file answers the question in a few milliseconds. Now the same person asks a second question, then a hundred, then a thousand, and each time the program reads the whole folder again, although the texts have not changed. A search engine reads them once, writes down where every word occurs, and answers each question from that record. This chapter builds one in C, in six milestones, from a specification to a measurement. Nothing in it is new: it puts together the files of Chapter 6, the modules and tests of Chapter 7, the history of Chapter 9, the dynamic arrays of Chapter 14, the hash tables of Chapter 16 and the heaps of Chapter 18. What is new is making them work together, and showing that they do.

You already know

A file is read through a stream, in binary mode when every byte matters, and a robust reader checks every call (Section 6.5). A module is a header (its interface) and a source file; a makefile rebuilds what is out of date (Definition 7.5). A dynamic array doubles its capacity when it is full, at amortised constant cost per push (Definition 14.5). A hash table with separate chaining finds a key in expected constant time while its load factor stays bounded (Definition 16.5). The kk largest elements of a stream are kept in a min-heap of size kk (Listing 18.4).

30.1 Specification and corpus

The program is called search. Run as search DIR WORD..., it reads every file of the folder DIR whose name ends in .txt, and prints how many of them contain every word of the query, then the ten best of them, best first, each with its score; a word is matched whatever its case. Run with a folder and no word, it prints the size of what it built. Its exit status says what happened: 0 when some document matches, 1 when none does, 2 when the command is misused, the folder cannot be read or memory runs out, so that a script can tell “nothing found” from “something broke”. It is built by a makefile, tested by unit tests and by a comparison with a simpler program, kept in a Git repository, and measured against that simpler program, which reads every file for every query.

Four hundred texts are a desk of folders: searching it once by reading everything is fine; searching it a thousand times is not.
Four hundred texts are a desk of folders: searching it once by reading everything is fine; searching it a thousand times is not.

The corpus. The texts are generated, not downloaded, by a script seeded so that every run writes the same 400 files. Each document has between 200 and 2000 words drawn from an invented vocabulary of 5000 words made of syllables. The word of rank rr is drawn with probability proportional to 1/r1/r, so a handful of short words fill most of every text and most words are rare, as in real prose. Three words that the vocabulary cannot produce (its syllables have no q, x, y or z) are planted in known documents, so that tests know the answer in advance: quixotic in two documents, xylograph in one and quartzite in four. One document in fifty starts with Café, whose last letter is not ASCII, and one in forty has no final newline.

def document(rng, words, weights, doc):
    n = rng.randint(200, 2000)
    text = rng.choices(words, weights, k=n)
    for word, docs in PLANTED.items():
        if doc in docs:
            text[rng.randrange(n)] = word
    if doc % 50 == 0:
        text[0] = "Café"  # a non-ASCII letter: the tokenizer splits it
    lines, line = [], []
    for i, w in enumerate(text):
        end = "." if i % 12 == 11 else ""  # sentences of twelve words
        line.append(w.capitalize() if i % 12 == 0 else w + end)
        if len(line) == 10:
            lines.append(" ".join(line))
            line = []
    lines.append(" ".join(line))
    end = "" if doc % 40 == 1 else "\n"  # some files have no final newline
    return "\n".join(lines) + end, text
Listing 30.1. One document: words drawn with weights 1/r1/r, the planted words, the traps, and lines of ten words code/bachelor-1/30-project-text-search-engine/listings/make_corpus.py
$ python make_corpus.py
434742 words, 5004 distinct, in 400 files
rank  word      count  rank x count
   1  ba        47579         47579
   2  be        24003         48006
   3  bi        15799         47397
  10  du         4663         46630
 100  beli        474         47400
1000  nodo         48         48000
Output 30.1. The corpus: the word of rank rr occurs about 47 500/r47\,500 / r times, so rank times count is nearly constant.

The product in the last column is the law that George Kingsley Zipf made famous in his 1949 book for the words of real texts: in a large text, the frequency of a word is roughly inversely proportional to its rank. The script imposes it here on purpose; it matters for the engine, because it says that a few words occur in every document and most occur in very few.

The first version. Before any index, the specification is met by the simplest program that could meet it, naive: for each query, read every file, count each query word in it, and score the files that contain them all. It is slow, but it is short enough to be checked by reading, and it will serve as the oracle of the tests: the fast program must print, for every query, exactly what the slow one prints.

int scan_and(const char *dir, const Folder *f, char **terms, int nterms, Hit *top, int k,
             int *nfound) {
    int *tf = calloc((size_t)f->n * nterms, sizeof *tf), *df = calloc(nterms, sizeof *df);
    if (tf == NULL || df == NULL) {  // out of memory
        free(tf);
        free(df);
        return -1;
    }
    for (int d = 0; d < f->n; d++) {
        char path[4096], word[MAX_WORD];
        size_t len, pos = 0;
        snprintf(path, sizeof path, "%s/%s", dir, f->names[d]);
        char *text = read_file(path, &len);
        while (text != NULL && next_word(text, len, &pos, word) > 0)
            for (int i = 0; i < nterms; i++)
                tf[d * nterms + i] += strcmp(word, terms[i]) == 0;
        free(text);
        for (int i = 0; i < nterms; i++)
            df[i] += tf[d * nterms + i] > 0;
    }
    TopK t;
    topk_init(&t, top, k);
    int matches = 0;
    for (int d = 0; d < f->n; d++) {
        int all = 1;
        for (int i = 0; i < nterms; i++)
            all = all && tf[d * nterms + i] > 0;
        if (all) {
            matches++;
            topk_push(&t, (Hit){tfidf(f->n, &tf[d * nterms], df, nterms), d});
        }
    }
    *nfound = topk_sorted(&t);
    free(tf);
    free(df);
    return matches;
}
Listing 30.2. The naive scan: every file, every word, compared with every term code/bachelor-1/30-project-text-search-engine/listings/scan.c

Both programs share the code that cuts a text into words, the score and the printing, so that a difference between them can only come from the index. The whole design fits in one picture.

The modules of the search engine and the data that flows between them. The texts are read once, to build the index; each query then touches only the posting lists of its words. The naive scan reuses the tokenizer and the heap but reads every file for every query.
The modules of the search engine and the data that flows between them. The texts are read once, to build the index; each query then touches only the posting lists of its words. The naive scan reuses the tokenizer and the heap but reads every file for every query.

30.2 Splitting files into words

Definition 30.1 (Tokenizer)

A tokenizer is a function that cuts a text into a sequence of tokens, the units that the rest of a program works with, by a rule that says which characters belong to a token and which separate tokens.

Here a token is a word, and the rule is short: a word is a maximal run of ASCII letters, lowercased; every other byte separates words. The rule works on bytes, so it never has to decode the text. Its cost is a documented choice about the other alphabets. In UTF-8 the letter é is the two bytes 0xC3 0xA9, neither of which is an ASCII letter, so Café becomes the word caf. That is wrong for a reader of French, and a real engine decodes the text and folds accents. It is consistent, though: the query Café is cut by the same function into the same caf, so it still finds its documents. A word longer than 63 letters is cut to its first 63, so that it fits in a fixed buffer without overflowing it.

static int is_letter(unsigned char c) {
    return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}

size_t next_word(const char *text, size_t len, size_t *pos, char word[MAX_WORD]) {
    size_t i = *pos, n = 0;
    while (i < len && !is_letter((unsigned char)text[i]))
        i++;
    while (i < len && is_letter((unsigned char)text[i])) {
        if (n < MAX_WORD - 1)
            word[n++] = (char)(text[i] | 0x20);  // 'A'..'Z' become 'a'..'z'
        i++;
    }
    word[n] = '\0';
    *pos = i;
    return n;
}
Listing 30.3. The tokenizer: skip separators, then copy letters, lowercased, until the next separator code/bachelor-1/30-project-text-search-engine/listings/tokenize.c

The bit trick on line 18 lowercases an ASCII letter: A is 0x41 and a is 0x61, so setting bit 5 maps every capital to its small letter and leaves small letters alone. Note what the function does at the end of the text: the second loop stops at len as well as at a separator, so the last word of a file without a final newline is kept (Exercise 30.5 shows a tokenizer that loses it).

The file is read whole into memory, in binary mode, by doubling a buffer until fread returns nothing more, and every failure gives back NULL with nothing left allocated.

char *read_file(const char *path, size_t *len) {
    FILE *f = fopen(path, "rb");
    if (f == NULL)
        return NULL;
    size_t cap = 4096, n = 0, got;
    char *buf = malloc(cap);
    while (buf != NULL && (got = fread(buf + n, 1, cap - n, f)) > 0) {
        n += got;
        if (n == cap) {  // full: double the buffer
            char *bigger = realloc(buf, cap *= 2);
            if (bigger == NULL)
                free(buf);
            buf = bigger;
        }
    }
    if (buf != NULL && ferror(f)) {
        free(buf);
        buf = NULL;
    }
    fclose(f);
    *len = n;
    return buf;
}
Listing 30.4. Reading a whole file into a growing buffer code/bachelor-1/30-project-text-search-engine/listings/tokenize.c

The tokenizer gets its own unit tests, on inputs chosen for their edges: an apostrophe, two dashes, capitals, a non-ASCII letter, a digit inside a word, a word too long for the buffer, and a text whose last byte is a letter.

static void test_tokenizer(void) {
    const char *t = "Don't  STOP--now: caf\xc3\xa9 x2y\n";
    const char *want[] = {"don", "t", "stop", "now", "caf", "x", "y"};
    char w[MAX_WORD];
    size_t pos = 0, len = strlen(t);
    int n = 0;
    while (next_word(t, len, &pos, w) > 0)
        CHECK(n < 7 && strcmp(w, want[n++]) == 0);
    CHECK(n == 7);
    char longw[100];  // a word of 99 letters is cut to 63
    memset(longw, 'a', 99);
    pos = 0;
    CHECK(next_word(longw, 99, &pos, w) == MAX_WORD - 1 && pos == 99);
    pos = 0;
    CHECK(next_word("end", 3, &pos, w) == 3 && strcmp(w, "end") == 0);  // no final byte
}
Listing 30.5. Unit tests of the tokenizer on tricky inputs code/bachelor-1/30-project-text-search-engine/listings/units_test.c

30.3 The inverted index

Definition 30.2 (Inverted index, posting list)

Let a collection of documents be numbered 0,1,…,N−10, 1, \dots, N - 1. The posting list of a word is the list of the documents that contain it, in increasing order, each with the number of times the word occurs in it; each element is a posting. An inverted index of the collection is a dictionary that maps each word occurring in it to its posting list.

A document is a list of words; the index turns that around and gives, for each word, its documents, hence the name. It is built in one pass. The documents are read in order of their names, so the numbers are the same on every run, and each word of document dd either adds a posting (d,1)(d, 1) at the end of its list or, if the last posting is already (d,c)(d, c), makes it (d,c+1)(d, c + 1). Since dd only grows, every list stays sorted without being sorted. The dictionary is a hash table with separate chaining, hashed by FNV-1a, whose number of buckets doubles when there are more words than buckets; each posting list is a dynamic array of postings.

typedef struct {
    int doc;    // a document number, 0, 1, 2, ... in the order indexed
    int count;  // how many times the word occurs in it
} Posting;

typedef struct {
    Posting *items;  // sorted by document, one posting per document
    int size, cap;
} PostingList;

typedef struct Entry {
    char *word;
    PostingList list;
    struct Entry *next;  // the next entry of the same bucket
} Entry;

typedef struct {
    Entry **buckets;
    size_t nbuckets, nwords;  // the table doubles when nwords exceeds nbuckets
    long npostings;
    char **names;  // names[d]: the file name of document d
    int ndocs, cap_docs;
} Index;
Listing 30.6. The types of the index: a posting, a posting list, a bucket entry, the index code/bachelor-1/30-project-text-search-engine/listings/index.h
static Entry *find_or_add(Index *ix, const char *word) {
    size_t i = fnv1a(word) % ix->nbuckets;
    for (Entry *e = ix->buckets[i]; e != NULL; e = e->next)
        if (strcmp(e->word, word) == 0)
            return e;
    Entry *e = calloc(1, sizeof *e);
    if (e == NULL || (e->word = strdup(word)) == NULL) {
        free(e);
        return NULL;  // out of memory
    }
    e->next = ix->buckets[i];
    ix->buckets[i] = e;
    if (++ix->nwords > ix->nbuckets)
        grow_table(ix);
    return e;
}

static int add_occurrence(Index *ix, PostingList *l, int doc) {
    if (l->size > 0 && l->items[l->size - 1].doc == doc) {
        l->items[l->size - 1].count++;  // the word again, in the same document
        return 0;
    }
    if (l->size == l->cap) {  // full: grow through a temporary, which may be NULL
        int cap = l->cap ? 2 * l->cap : 2;
        Posting *items = realloc(l->items, cap * sizeof *items);
        if (items == NULL)
            return -1;  // out of memory: the list is left as it was
        l->items = items;
        l->cap = cap;
    }
    l->items[l->size++] = (Posting){doc, 1};
    ix->npostings++;
    return 0;
}
Listing 30.7. Finding a word’s entry, and adding an occurrence code/bachelor-1/30-project-text-search-engine/listings/index.c

Every allocation is checked, by the rule of Chapter 5. A full posting list grows through a temporary pointer, so that a failed realloc leaves the list as it was, and the failure goes back up to the caller, which gives up: search then exits with status 2. Only the growth of the table may fail quietly, since a table that keeps its old size is slower but still correct.

int index_add_text(Index *ix, const char *name, const char *text, size_t len) {
    if (ix->ndocs == ix->cap_docs) {
        int cap = ix->cap_docs ? 2 * ix->cap_docs : 64;
        char **names = realloc(ix->names, cap * sizeof *names);
        if (names == NULL)
            return -1;
        ix->names = names;
        ix->cap_docs = cap;
    }
    char *copy = strdup(name);
    if (copy == NULL)
        return -1;
    int doc = ix->ndocs++;
    ix->names[doc] = copy;
    char word[MAX_WORD];
    size_t pos = 0;
    while (next_word(text, len, &pos, word) > 0) {
        Entry *e = find_or_add(ix, word);
        if (e == NULL || add_occurrence(ix, &e->list, doc) != 0)
            return -1;  // out of memory: the document is only partly indexed
    }
    return doc;
}
Listing 30.8. Indexing a text, one word at a time code/bachelor-1/30-project-text-search-engine/listings/index.c
Part of the inverted index of three small documents (those of ). The array of buckets holds pointers to chains of entries; cat and hat share a bucket (the bucket numbers are made up). Each entry owns its word and its posting list, a dynamic array of (document, count) pairs.
Part of the inverted index of three small documents (those of Exercise 30.2). The array of buckets holds pointers to chains of entries; cat and hat share a bucket (the bucket numbers are made up). Each entry owns its word and its posting list, a dynamic array of (document, count) pairs.

How big is it? The function index_memory adds up what the index allocated: the array of buckets, the entries, the copies of the words, the posting arrays at their capacity (not their size, since the slack is allocated too) and the file names. On the corpus, the engine prints its statistics when it is given no word:

$ ./search corpus
400 documents, 5004 distinct words, 193455 postings, 2462055 bytes
Output 30.2. The index of the corpus: 5004 distinct words, 193 455 postings, 2.46 million bytes. Some lines are left out.

The corpus has 434 742 words, and the index has 193 455 postings: each posting stands for all the occurrences of a word in a document, which is why there are fewer than half as many. The index is a little bigger than the texts, nine tenths of it posting arrays, almost a third of whose capacity is the slack that doubling leaves (Exercise 30.11). The 5004 words are the vocabulary of 5000, every one of which occurs somewhere, the three planted words, and the fragment caf.

30.4 Answering queries

A query of kk words asks for the documents that contain all of them: the intersection of their posting lists. Two sorted lists are intersected by merging, as in merge sort: walk through both with one index each, advance the one that points at the smaller document, and keep a document when both point at it. Every step advances at least one index, so the merge of lists of lengths ℓ\ell and mm costs at most ℓ+m\ell + m steps. For kk words, the lists are taken shortest first. The running result is then never longer than the shortest list, and it shrinks as the merges go on.

The AND of two words as a merge of their sorted lists of document numbers. The shaded documents are in both. Document 8 is passed on the first list because the second has jumped from 4 to 12; documents 1, 4 and 15 are passed on the second. After 27 is compared with 30, the first list runs out and the merge stops.
The AND of two words as a merge of their sorted lists of document numbers. The shaded documents are in both. Document 8 is passed on the first list because the second has jumped from 4 to 12; documents 1, 4 and 15 are passed on the second. After 27 is compared with 30, the first list runs out and the merge stops.
int query_and(const Index *ix, char **terms, int nterms, Hit *top, int k, int *nfound) {
    const PostingList **lists = malloc(nterms * sizeof *lists);
    const PostingList **sorted = malloc(nterms * sizeof *sorted);
    int matches = -1, *docs = NULL, *tf = NULL, *df = NULL;  // -1: out of memory
    *nfound = 0;
    if (lists == NULL || sorted == NULL)
        goto done;
    matches = 0;
    for (int i = 0; i < nterms; i++)
        if ((lists[i] = sorted[i] = index_lookup(ix, terms[i])) == NULL)
            goto done;  // a word in no document: no document has them all
    qsort(sorted, nterms, sizeof *sorted, by_length);
    int n = sorted[0]->size;
    docs = malloc(n * sizeof *docs);
    tf = malloc(nterms * sizeof *tf);
    df = malloc(nterms * sizeof *df);
    if (docs == NULL || tf == NULL || df == NULL) {
        matches = -1;
        goto done;
    }
    for (int j = 0; j < n; j++)
        docs[j] = sorted[0]->items[j].doc;
    for (int i = 1; i < nterms && n > 0; i++) {  // merge: keep the docs also in list i
        int a = 0, b = 0, kept = 0;
        while (a < n && b < sorted[i]->size) {
            int d = sorted[i]->items[b].doc;
            if (docs[a] < d)
                a++;
            else if (docs[a] > d)
                b++;
            else
                docs[kept++] = docs[a++], b++;
        }
        n = kept;
    }
Listing 30.9. The AND query: look up every term, sort the lists by length, and merge them into the running result code/bachelor-1/30-project-text-search-engine/listings/query.c

A word that occurs in no document has no posting list at all; then no document can contain every word, and the function stops at once (line 43); a failed allocation stops it too, with the answer −1-1. Which of the survivors are the best? A document that uses a query word often is probably about it, and a rare word says more about a document than a word that every document uses. The usual score combines the two.

Definition 30.3 (Term frequency, document frequency, tf–idf score)

In a collection of NN documents, the term frequency tf(t,d)\mathrm{tf}(t, d) of a word tt in a document dd is the number of times tt occurs in dd, and its document frequency df(t)\mathrm{df}(t) is the number of documents that contain it. The tf–idf score of a document dd for a query of words t1,…,tkt_1, \dots, t_k is

score(d)=∑i=1ktf(ti,d)⋅ln⁡Ndf(ti).\mathrm{score}(d) = \sum_{i=1}^{k} \mathrm{tf}(t_i, d) \cdot \ln \frac{N}{\mathrm{df}(t_i)} .

The factor ln⁡(N/df)\ln (N / \mathrm{df}) is the inverse document frequency: zero for a word in every document, which therefore cannot tell documents apart, and largest for a word in only one. It is a choice, not a theorem. Other engines dampen the term frequency (a word used ten times is not ten times as relevant) or divide by the length of the document, and their results differ; this one is the plain textbook form. Both factors are already in the index: the term frequency is the count of a posting, and the document frequency is the length of the posting list.

History — Inverse document frequency

In 1972, Karen Spärck Jones published in the Journal of Documentation “A statistical interpretation of term specificity and its application in retrieval”. She argued that a term matching many documents should count for less than one matching few, and weighted each term by a function of the number of documents it occurs in. The logarithmic weight became known as the inverse document frequency. Combined with the term frequency, it is still the starting point of most ranking functions in search engines.

The query computes the score of each surviving document, finding each term’s count in its sorted posting list by binary search, and keeps the best ten in a min-heap of size ten, the method of Listing 18.4: a new hit only has to be compared with the worst hit kept, at the root.

void topk_push(TopK *t, Hit h) {
    if (t->size < t->k) {  // room left: add at the bottom and sift up
        int i = t->size++;
        t->heap[i] = h;
        while (i > 0 && hit_better(t->heap[(i - 1) / 2], t->heap[i])) {
            swap(&t->heap[i], &t->heap[(i - 1) / 2]);
            i = (i - 1) / 2;
        }
    } else if (t->k > 0 && hit_better(h, t->heap[0])) {  // it beats the worst kept
        t->heap[0] = h;
        sift_down(t, 0);
    }
}
Listing 30.10. Keeping the kk best hits: sift up while there is room, then replace the root only by a better hit code/bachelor-1/30-project-text-search-engine/listings/topk.c

“Better” is defined by hit_better: a higher score or, on equal scores, a smaller document number. Ties are frequent here, since two documents in which the query words occur equally often get the same score, and without this rule the order of equal hits would depend on the order of the heap’s operations. The naive scan would then print the same documents in another order, and the test that compares them would fail for a reason that is not an error. With the rule, the order of the hits is a property of the hits alone.

$ ./search corpus Quixotic
2 documents contain every word; the best 2:
   5.2983  doc007.txt
   5.2983  doc211.txt
$ ./search corpus nodo beli
34 documents contain every word; the best 10:
   6.0165  doc371.txt
   4.7813  doc241.txt
   4.2435  doc021.txt
   4.2435  doc076.txt
   3.8317  doc002.txt
   3.8317  doc103.txt
   3.8317  doc284.txt
   3.4200  doc082.txt
   3.4200  doc126.txt
   3.4200  doc184.txt
Output 30.3. Two queries. Quixotic is in two documents, once each: ln⁡(400/2)=5.2983\ln(400/2) = 5.2983. Of the 34 documents with nodo and beli, the best uses nodo twice and beli four times. Some lines are left out.

The first score can be checked by hand: nodo is in 45 documents and beli in 265, so the best document scores 2ln⁡(400/45)+4ln⁡(400/265)=4.3697+1.6469=6.01652 \ln(400/45) + 4 \ln(400/265) = 4.3697 + 1.6469 = 6.0165. The query Quixotic, capital included, is cut by the same tokenizer and found.

30.5 Tests, makefile and Git history

The project has five modules, three programs and one test program, so the makefile of Listing 7.4 grows a little: one variable lists the core modules that every program links, and each program adds what it needs.

# Makefile: the search engine, the naive scan, the measurement and the unit tests.
CC = gcc
CFLAGS = -std=c17 -O2 -Wall -Wextra -Werror
LDLIBS = -lm
CORE = tokenize.o folder.o index.o query.o topk.o

all: search naive measure units_test

search: main.o $(CORE)
	$(CC) -o $@ $^ $(LDLIBS)
naive: naive.o scan.o $(CORE)
	$(CC) -o $@ $^ $(LDLIBS)
measure: measure.o scan.o $(CORE)
	$(CC) -o $@ $^ $(LDLIBS)
units_test: units_test.o $(CORE)
	$(CC) -o $@ $^ $(LDLIBS)

%.o: %.c
	$(CC) $(CFLAGS) -c $<

tokenize.o: tokenize.h
folder.o: folder.h
index.o: index.h folder.h tokenize.h
query.o: query.h index.h topk.h
topk.o: topk.h
scan.o: scan.h folder.h topk.h query.h tokenize.h
main.o naive.o measure.o units_test.o: index.h query.h topk.h tokenize.h folder.h scan.h

test: units_test
	./units_test

clean:
	rm -f search naive measure units_test *.o

.PHONY: all test clean
Listing 30.11. The project’s makefile code/bachelor-1/30-project-text-search-engine/listings/Makefile
$ make
gcc -std=c17 -O2 -Wall -Wextra -Werror -c main.c
gcc -std=c17 -O2 -Wall -Wextra -Werror -c tokenize.c
gcc -std=c17 -O2 -Wall -Wextra -Werror -c folder.c
gcc -std=c17 -O2 -Wall -Wextra -Werror -c index.c
gcc -std=c17 -O2 -Wall -Wextra -Werror -c query.c
gcc -std=c17 -O2 -Wall -Wextra -Werror -c topk.c
gcc -o search main.o tokenize.o folder.o index.o query.o topk.o -lm
gcc -std=c17 -O2 -Wall -Wextra -Werror -c naive.c
gcc -std=c17 -O2 -Wall -Wextra -Werror -c scan.c
gcc -o naive naive.o scan.o tokenize.o folder.o index.o query.o topk.o -lm
gcc -std=c17 -O2 -Wall -Wextra -Werror -c measure.c
gcc -o measure measure.o scan.o tokenize.o folder.o index.o query.o topk.o -lm
gcc -std=c17 -O2 -Wall -Wextra -Werror -c units_test.c
gcc -o units_test units_test.o tokenize.o folder.o index.o query.o topk.o -lm
$ make test
./units_test
18 checks, 0 failed
Output 30.4. A build from scratch, then the unit tests. Some lines are left out.

The unit tests check each module on its own, on small inputs whose answers are known: the tokenizer on the line of Listing 30.5; the index on four documents of a few words, then after 3000 more words, which make the table grow; the heap on a stream of seven scores with a tie. They catch an error close to where it is. They cannot show that the modules fit together, that the program reads the folder it is given, or that its output is the one the specification asks for. That is the job of another kind of test.

Definition 30.4 (End-to-end test)

An end-to-end test runs a whole program as its users do, from its real inputs (here a folder and a command line) to its real outputs (the printed text and the exit status), and checks those outputs, without looking inside the program.

Here the end-to-end test has an oracle: the naive scan, which shares the tokenizer, the score and the printing with the engine, but not the index. The test builds both programs with the makefile in a fresh temporary folder, generates the corpus, and runs both on the 200 seeded queries of one to three words, plus the planted words, a query with a capital and a punctuation mark, and a word found nowhere. For every query the two outputs and the two exit statuses must be identical, byte for byte.

def build(folder, cflags=None):
    for name in SOURCES:
        shutil.copy(LISTINGS / name, folder)
    args = ["make", "-s", "search", "naive"] + ([f"CFLAGS={cflags}", f"LDLIBS=-lm {cflags}"]
                                                if cflags else [])
    subprocess.run(args, cwd=folder, check=True, capture_output=True)
    subprocess.run(["python3", "make_corpus.py", "corpus"], cwd=folder, check=True,
                   capture_output=True)
    return (folder / "queries.txt").read_text().splitlines()


def run(folder, program, words, env=None):
    return subprocess.run([f"./{program}", "corpus", *words], cwd=folder, env=env,
                          capture_output=True, text=True)


def test_search_agrees_with_the_naive_scan():
    with tempfile.TemporaryDirectory() as tmp:
        folder = Path(tmp)
        queries = build(folder)
        statuses = set()
        for q in queries + ["quixotic", "Quartzite!", "xylograph quixotic", "zzz"]:
            a, b = run(folder, "search", q.split()), run(folder, "naive", q.split())
            assert (a.stdout, a.returncode) == (b.stdout, b.returncode), q
            statuses.add(a.returncode)
        assert statuses == {0, 1}
        assert run(folder, "search", ["quartzite"]).stdout.startswith("4 documents")
        nowhere = subprocess.run(["./search", "nowhere", "x"], cwd=folder,
                                 capture_output=True)
        assert nowhere.returncode == 2
Listing 30.12. The end-to-end test: build, generate, and compare with the oracle on every query code/bachelor-1/30-project-text-search-engine/tests/test_end_to_end.py

The scores are printed with four decimals, so the comparison is exact only because both programs add the same terms in the same order, through the same function tfidf; two different orders of addition can round differently in the last bit. The test also builds the engine with the address and undefined-behaviour sanitizers and requires them to stay silent on twenty queries, an empty query and a word found nowhere. That covers the paths that free memory early, such as the word with no posting list. Here is such a run by hand:

$ S=-fsanitize=address,undefined
$ make -s search CFLAGS="-std=c17 -O1 -g $S" LDLIBS="-lm $S"
$ ./search corpus nodo beli | head -3
34 documents contain every word; the best 10:
   6.0165  doc371.txt
   4.7813  doc241.txt
$ ./search corpus; echo "exit status $?"
400 documents, 5004 distinct words, 193455 postings, 2462055 bytes
exit status 0
Output 30.5. The engine built with the sanitizers: the same answers, and not a word on the error stream.
$ ./naive corpus nodo beli | cmp - <(./search corpus nodo beli) && echo identical
identical
$ ./search corpus quixotic nodo; echo "exit status $?"
no document contains every word
exit status 1
$ ./search nowhere nodo; echo "exit status $?"
search: cannot read the texts of nowhere
exit status 2
Output 30.6. The two programs agree on a query, and the exit statuses 1 (nothing found) and 2 (no such folder). Some lines are left out.

The history. The project was kept in Git from the start, in four commits, each a version that does one more thing: the specification with the corpus and the naive scan, the index, the queries, then the makefile, the tests and the measurement. The session below replays that history in a fresh repository: it copies the files of each version and commits them, then shows the log, the content of one commit, and a working tree with nothing left to commit after a build, since the .gitignore lists the programs, the object files and the generated corpus.

$ git log --oneline
f9f71ca Makefile, unit tests, measurement
ffdef6b Answer AND queries from the index, the best ten
a896f37 Build the inverted index
d8427fc Specify search; generate the corpus; the naive scan
$ git show --stat --format='%s' HEAD~2 | head -5
Build the inverted index

 index.c | 150 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 index.h |  36 ++++++++++++++++
 2 files changed, 186 insertions(+)
$ make -s && ./units_test
18 checks, 0 failed
$ git status --short | wc -l
0
Output 30.7. The project’s history in four commits, and the clean working tree after a build.

Generated files stay out of the repository: the corpus is 1.9 megabytes that the script rewrites in a second, and a committed copy could drift from the script that is supposed to make it.

30.6 Measured against the naive scan

Is the index worth its cost? Building it reads every file once, as one naive query does, and also fills a hash table. After that, a query touches only the posting lists of its words. A small program, measure, times the building of the index, the 200 queries answered ten times over from the index, and the first twenty queries answered by the scan. It checks that the two methods agree on those twenty, and prints the number of queries from which the index has paid for itself.

$ ./measure corpus queries.txt
index built in 15.0 ms: 400 documents, 5004 words, 2462055 bytes
one query: 5.97 ms scanning the files, 0.0032 ms with the index
same answers on the first 20 queries: yes
the index pays for itself from query 3 on
Output 30.8. The index against the naive scan, measured on the author’s laptop.

One query from the index takes about three microseconds, against nearly six milliseconds for the scan, which reads 1.9 megabytes and compares every word of them with every term: nearly two thousand times faster. The index costs about two and a half scans to build (more than one, since it also hashes every word and grows the table), so it pays for itself from the third query on.

Total time of q queries on the corpus, from the measured output above. The scan’s line rises by almost six milliseconds per query; the index’s line starts at its building time and stays flat, its queries far too fast to show at this scale. The lines cross between the second and third queries.
Total time of qq queries on the corpus, from the measured output above. The scan’s line rises by almost six milliseconds per query; the index’s line starts at its building time and stays flat, its queries far too fast to show at this scale. The lines cross between the second and third queries.

The saving grows with the corpus. The scan’s cost is proportional to the total size of the texts, while a query on the index costs in proportion to the lengths of the posting lists of its words. For the rare words that make good queries, those lists are short, and Zipf’s law says that most words are rare. The cost of the index is memory, a little more than the texts here, and the time to build it again when a text changes. A real engine updates it piece by piece, which this one cannot do.

What would come next. Three improvements are classic. Stemming would let index match indexes, by cutting words to a common root, a rule that depends on the language. Phrase queries, such as the five words of a title in that order, need the positions of the words in the postings, and Exercise 30.10 adds them. Compressing the postings would make the index smaller than the texts: the gaps between successive document numbers are small, and small numbers fit in a byte or less. The algorithms on texts in the next volume go further, and Exercise 30.12 makes the index survive the end of the program by writing it to a file.

30.7 Exercises

Exercise 30.1 ★

Give the words that next_word (Listing 30.3) finds in the UTF-8 line It’s 9:30--Ünal’s "e-mail" (v2.0)!, in order. Which of them would a reader not call words, and why does the query Ünal still find this line?

Solution

Solution of Exercise 30.1.

it, s, nal, s, e, mail, v. The digits and punctuation only separate. The letter Ü is the two bytes 0xC3 0x9C, neither of them an ASCII letter, so it separates too. A reader would not call s, nal, e or v words. The query Ünal goes through the same tokenizer and becomes nal, which is in the index for this line. So it is found, together with every other text in which a non-ASCII letter is followed by nal: the rule is consistent, not exact.

Exercise 30.2 ★

Three documents are indexed in this order: document 0, the cat sat on the mat; document 1, The Cat and the Hat; document 2, a cat, a hat; a bat. Write the posting lists of the, cat, hat and a, and give the number of distinct words and the number of postings of the index.

Solution

Solution of Exercise 30.2.

the: (0,2),(1,2)(0, 2), (1, 2). cat: (0,1),(1,1),(2,1)(0, 1), (1, 1), (2, 1). hat: (1,1),(2,1)(1, 1), (2, 1). a: (2,3)(2, 3). The capitals of document 1 are lowercased, and the comma and semicolon of document 2 separate. There are 9 distinct words (the, cat, sat, on, mat, and, hat, a, bat) and 5+4+4=135 + 4 + 4 = 13 postings, one per distinct word of each document.

Exercise 30.3 ★

Merge the posting lists of documents [2,5,9,14,20,31][2, 5, 9, 14, 20, 31] and [1,5,6,14,31,40,41][1, 5, 6, 14, 31, 40, 41] as the loop of Listing 30.9 does. Give the result and the number of times the loop’s body runs. Why does the loop stop before the end of the second list?

Solution

Solution of Exercise 30.3.

The steps, written (document of the result list, document of the second list): (2,1)(2, 1) advances the second list; (2,5)(2, 5) the first; (5,5)(5, 5) keeps 5; (9,6)(9, 6) the second; (9,14)(9, 14) the first; (14,14)(14, 14) keeps 14; (20,31)(20, 31) the first; (31,31)(31, 31) keeps 31. The result is [5,14,31][5, 14, 31], after 8 runs of the body. The first list is then exhausted, and since every later document of the second list (40 and 41) is greater than all of the first, none of them can be in both.

Exercise 30.4 ★

A heap of size k=3k = 3 (Listing 30.10) receives hits of scores 4, 8, 1, 6, 9, 3, 7, for documents 0 to 6 in this order. Give the heap’s array after each push, and the three hits that topk_sorted returns.

Solution

Solution of Exercise 30.4.

Writing hits by their scores: [4][4]; [4,8][4, 8], since 8 is better than its parent 4 and stays below it; [1,8,4][1, 8, 4], the 1 rising to the root; then the heap is full. 6 beats the root 1 and replaces it, and sinks below its worse child 4: [4,8,6][4, 8, 6]. 9 beats 4, replaces it and sinks below 6: [6,8,9][6, 8, 9]. 3 does not beat 6 and is dropped. 7 beats 6 and stays at the root, both children being better: [7,8,9][7, 8, 9]. topk_sorted returns 9 (document 4), 8 (document 1) and 7 (document 6).

Exercise 30.5 ★★

A colleague counts words with the function below, a word being a run of ASCII letters. On the three texts of the output it prints 4, 4 and 3. Explain the 3, give the class of input it fails on, and correct the function with one line. Why does next_word not have this error?

static size_t count_words(const char *text, size_t len) {
    size_t n = 0;
    int in_word = 0;
    for (size_t i = 0; i < len; i++) {
        unsigned char c = (unsigned char)text[i];
        if ((c | 0x20) >= 'a' && (c | 0x20) <= 'z') {
            in_word = 1;
        } else if (in_word) {  // a separator ends the word in progress
            n++;
            in_word = 0;
        }
    }
    return n;
}
Listing 30.13. Counting words at the separators code/bachelor-1/30-project-text-search-engine/listings/exo_last_word.c
Red fish, blue fish.     4 words
Red fish, blue fish      4 words
Red fish, blue fish      3 words
Output 30.9. Three texts, the last without a final newline. Some lines are left out.
Solution

Solution of Exercise 30.5.

A word is counted only when a separator ends it. In the third text the last word, fish, is followed by no byte at all, so it is never counted. The function fails on every text whose last byte is a letter, which is a file without a final newline ending on a word, or any string passed without one. The correction counts the word still open at the end: return n + in_word;. next_word has no such case, because its loop over letters stops at the end of the text as well as at a separator, and returns the word it has copied.

Exercise 30.6 ★★

The program below builds the posting list of cat for document 0, cat cat the, and document 1, dog cat. Explain its output, including the negative inverse document frequency, and say which line of Listing 30.7 prevents the error in the engine. What would the error do to the answers of the end-to-end test?

int main(void) {
    const int words_of_doc[][4] = {{1, 1, 0, -1}, {2, 1, -1, -1}};  // 0 the, 1 cat, 2 dog
    Posting cat[8];
    int size = 0, ndocs = 2;
    for (int d = 0; d < ndocs; d++)
        for (int i = 0; i < 4 && words_of_doc[d][i] >= 0; i++)
            if (words_of_doc[d][i] == 1)
                cat[size++] = (Posting){d, 1};  // always a new posting
    for (int j = 0; j < size; j++)
        printf("(doc %d, count %d)%s", cat[j].doc, cat[j].count, j + 1 < size ? " " : "\n");
    printf("document frequency of cat: %d, idf: %.3f\n", size, log((double)ndocs / size));
    return 0;
Listing 30.14. A posting list that never looks at its last posting code/bachelor-1/30-project-text-search-engine/listings/exo_twice.c
(doc 0, count 1) (doc 0, count 1) (doc 1, count 1)
document frequency of cat: 3, idf: -0.405
Output 30.10. The posting list of cat. Some lines are left out.
Solution

Solution of Exercise 30.6.

Every occurrence of cat adds a posting, so document 0, which has it twice, gets two postings (0,1)(0, 1). The length of the list, taken as the document frequency, is then 3, more than the 2 documents. The weight ln⁡(2/3)\ln(2/3) is negative, so a document would lose score for containing the word. In the engine, line 62 of Listing 30.7 looks at the last posting and increments its count when it is already for the current document. With the error, the engine’s document frequencies would count occurrences, its scores would differ from those of the naive scan, which counts documents, and the end-to-end test would fail on the first query of a word used twice in a document, that is, on almost every query.

Exercise 30.7 ★★

Write a function query_or, with the same arguments as query_and, that finds the documents containing at least one of the terms, scored by the sum of the tf–idf terms of the words they contain. Test it against a brute-force count on small documents. How does its cost compare with that of query_and?

Solution

Solution of Exercise 30.7.

An array of scores, one per document, receives the weight of each posting of each term; a document is a match if it received anything. The matches then go through the heap.

int query_or(const Index *ix, char **terms, int nterms, Hit *top, int k, int *nfound) {
    double *score = calloc(ix->ndocs, sizeof *score);  // a score per document: simple
    char *seen = calloc(ix->ndocs, 1);
    if (score == NULL || seen == NULL) {
        free(score);
        free(seen);
        return -1;  // out of memory
    }
    for (int i = 0; i < nterms; i++) {
        const PostingList *l = index_lookup(ix, terms[i]);
        for (int j = 0; l != NULL && j < l->size; j++) {
            score[l->items[j].doc] += l->items[j].count * log((double)ix->ndocs / l->size);
            seen[l->items[j].doc] = 1;
        }
    }
    TopK t;
    topk_init(&t, top, k);
    int matches = 0;
    for (int d = 0; d < ix->ndocs; d++)
        if (seen[d]) {
            matches++;
            topk_push(&t, (Hit){score[d], d});
        }
    *nfound = topk_sorted(&t);
    free(score);
    free(seen);
    return matches;
}
OR queries, by adding the weights of every posting code/bachelor-1/30-project-text-search-engine/exercises/or_query.c

The test tests/exercises_test.c compares the number of matches with a brute-force count on six small documents, for every pair of six words, one of which occurs nowhere. The cost is the total length of the posting lists, ℓ1+⋯+ℓk\ell_1 + \dots + \ell_k, plus O ⁣(N)\Oh{N} to clear and scan the arrays. There is no shortcut by the shortest list as for AND: every posting of every list contributes. The result can be large too, since an OR query with one frequent word matches almost every document.

Exercise 30.8 ★★

Add an option --count to search: search DIR --count WORD… prints only the number of documents that contain every word, with the same exit status. Write the counting function so that it allocates nothing and does not compute a single score.

Solution

Solution of Exercise 30.8.

The function takes the shortest list and keeps each of its documents only if a binary search finds it in every other list; it counts and allocates nothing.

int count_and(const Index *ix, char **terms, int nterms) {
    const PostingList *shortest = NULL;
    for (int i = 0; i < nterms; i++) {
        const PostingList *l = index_lookup(ix, terms[i]);
        if (l == NULL)
            return 0;
        if (shortest == NULL || l->size < shortest->size)
            shortest = l;
    }
    int n = 0;
    for (int j = 0; j < shortest->size; j++) {  // a document of the shortest list...
        int doc = shortest->items[j].doc, all = 1;
        for (int i = 0; i < nterms && all; i++) {  // ...must be in every other list
            const PostingList *l = index_lookup(ix, terms[i]);
            int lo = 0, hi = l->size - 1, found = 0;
            while (lo <= hi && !found) {
                int mid = lo + (hi - lo) / 2;
                found = l->items[mid].doc == doc;
                if (l->items[mid].doc < doc)
                    lo = mid + 1;
                else
                    hi = mid - 1;
            }
            all = found;
        }
        n += all;
    }
    return n;
}
Counting the documents that contain every term code/bachelor-1/30-project-text-search-engine/exercises/count.c

In main, when argv[2] is --count, the terms are split from argv + 3 instead, and the program prints count_and(&ix, terms, n) and returns 0 if that number is positive, 1 otherwise. The test compares count_and with the brute-force count of the previous exercise.

Exercise 30.9 ★★

An AND query has k≥2k \ge 2 words whose posting lists have lengths ℓ1≤ℓ2≤⋯≤ℓk\ell_1 \le \ell_2 \le \dots \le \ell_k.

  1. Prove that the merges of Listing 30.9, shortest list first, run their loop body at most (k−1)ℓ1+ℓ2+⋯+ℓk(k - 1)\ell_1 + \ell_2 + \dots + \ell_k times in all.
  2. Another method takes each document of the shortest list and looks for it in each other list by binary search. Show that it costs O ⁣(ℓ1log⁡ℓk⋅k)\Oh{\ell_1 \log \ell_k \cdot k} comparisons.
  3. Compare the two for the query xylograph ba, where ba is in all 400 documents.
Solution

Solution of Exercise 30.9.

  1. The running result starts as the shortest list and only loses documents, so it has at most ℓ1\ell_1 elements. In the merge with list ii, every run of the body advances the index of the result, or that of list ii, or both. The first index takes at most ℓ1\ell_1 values and the second at most ℓi\ell_i, so the body runs at most ℓ1+ℓi\ell_1 + \ell_i times. Summing over i=2,…,ki = 2, \dots, k gives (k−1)ℓ1+ℓ2+⋯+ℓk(k - 1)\ell_1 + \ell_2 + \dots + \ell_k.
  2. Each of the ℓ1\ell_1 documents is searched for in k−1k - 1 lists, and a binary search in a list of length ℓi≤ℓk\ell_i \le \ell_k makes at most ⌊log⁡2ℓi⌋+1≤log⁡2ℓk+1\lfloor \log_2 \ell_i \rfloor + 1 \le \log_2 \ell_k + 1 comparisons. In all, ℓ1(k−1)(log⁡2ℓk+1)=O ⁣(ℓ1log⁡ℓk⋅k)\ell_1 (k - 1)(\log_2 \ell_k + 1) = \Oh{\ell_1 \log \ell_k \cdot k}.
  3. xylograph is in one document (42) and ba in 400. The bound of the merge is 1+400=4011 + 400 = 401 runs; the real merge runs 43 times, advancing through ba’s documents 0 to 42, then stops when the result is exhausted. The binary search makes at most ⌊log⁡2400⌋+1=9\lfloor \log_2 400 \rfloor + 1 = 9 comparisons. When one list is much shorter than the others, searching beats merging; when they have similar lengths, ℓ1log⁡ℓk\ell_1 \log \ell_k exceeds ℓ1+ℓk\ell_1 + \ell_k and merging wins.

Exercise 30.10 ★★★

Add phrase queries: the documents in which the words w1,…,wkw_1, \dots, w_k occur consecutively, in this order. Store with each occurrence its position in the document (its rank among the document’s words), and find the positions pp such that wiw_i occurs at p+i−1p + i - 1 for every ii, by merging lists of (document, position) pairs. Test it on documents where the words occur in both orders.

Solution

Solution of Exercise 30.10.

A positional posting list holds, for a word, the pairs (document, position) of its occurrences, in increasing order. The phrase starts at the places of w1w_1 that are followed by wiw_i at +(i−1)+ (i - 1) for every ii. Each word filters the places kept so far by one merge, comparing (d,p+i−1)(d, p + i - 1) with the places of wiw_i in lexicographic order.

int phrase_docs(const char **texts, int ndocs, char **words, int nwords, int *docs) {
    Place *start;
    int n = places_of(texts, ndocs, words[0], &start), ndone = 0;
    if (n < 0)
        return -1;  // out of memory
    for (int i = 1; i < nwords; i++) {  // keep the starts followed by word i at +i
        Place *next;
        int m = places_of(texts, ndocs, words[i], &next), a = 0, b = 0, kept = 0;
        if (m < 0) {
            free(start);
            return -1;
        }
        while (a < n && b < m) {
            Place want = {start[a].doc, start[a].pos + i};
            if (want.doc < next[b].doc || (want.doc == next[b].doc && want.pos < next[b].pos))
                a++;
            else if (want.doc == next[b].doc && want.pos == next[b].pos)
                start[kept++] = start[a++], b++;
            else
                b++;
        }
        n = kept;
        free(next);
    }
    for (int j = 0; j < n; j++)
        if (ndone == 0 || docs[ndone - 1] != start[j].doc)
            docs[ndone++] = start[j].doc;
    free(start);
    return ndone;
}
Phrase queries, by merging lists of (document, position) pairs code/bachelor-1/30-project-text-search-engine/exercises/phrase.c

Here the positional lists are built from the texts by places_of; in the engine they would be stored in each posting, as an array of positions next to the count, which multiplies the size of the index by about the number of occurrences per posting. The test finds red fish in documents 0 and 3, and fish red in none, although both words are in documents 0 and 3: fish is never just before red.

Exercise 30.11 ★★★

Write the memory counted by index_memory as a function of the number of buckets BB, the number of distinct words WW, their total length LL, the capacities ctc_t of the posting lists, and the documents’ names, on a machine where pointers take 8 bytes and int 4. On the corpus, W=5004W = 5004, L=30 203L = 30\,203, ∑tct=274 086\sum_t c_t = 274\,086, and the 400 names have 10 characters each. Find BB from the growth rule of the table, check the total of Output 30.2, and say what fraction of the posting arrays is slack.

Solution

Solution of Exercise 30.11.

An entry is a pointer to its word, a posting list (a pointer and two ints) and a pointer to the next entry: 8+16+8=328 + 16 + 8 = 32 bytes. A posting is two ints, 8 bytes. The array of names has a capacity DD that doubles from 64. Then

M=8B+32W+(L+W)+8∑tct+8D+∑d(∣named∣+1).M = 8B + 32W + (L + W) + 8 \sum_t c_t + 8D + \sum_d (|\mathit{name}_d| + 1) .

The table starts with 1024 buckets and doubles when the number of words exceeds the number of buckets: at the 1025th, 2049th and 4097th word, so B=8192B = 8192 for 5004 words. Likewise D=512D = 512 for 400 documents. Then 8B=65 5368B = 65\,536, 32W=160 12832W = 160\,128, L+W=35 207L + W = 35\,207, 8∑tct=2 192 6888 \sum_t c_t = 2\,192\,688, 8D=40968D = 4096 and the names take 400×11=4400400 \times 11 = 4400 bytes: M=2 462 055M = 2\,462\,055 bytes, the number printed. The posting arrays hold 274 086274\,086 places for 193 455193\,455 postings, so 80 63180\,631 places, 29 % of them and 645 048 bytes, are slack.

Exercise 30.12 ★★★

Make the index persist: write index_save, which writes the index into a binary file, and index_load, which reads it back into an index that gives the same posting lists, counts and document numbers. Specify the file’s format, make the loader refuse a truncated or corrupted file rather than crash, and write a round-trip test. Why is the file not portable between machines as it stands?

Solution

Solution of Exercise 30.12.

The format: the number of documents and their names, then the number of words, then each word followed by the length of its posting list and its postings; every number is an int, every string its length then its bytes.

int index_save(const Index *ix, const char *path) {
    FILE *f = fopen(path, "wb");
    int ok = f != NULL && put_int(f, ix->ndocs);
    for (int d = 0; ok && d < ix->ndocs; d++)
        ok = put_str(f, ix->names[d]);
    ok = ok && put_int(f, (int)ix->nwords);
    for (size_t b = 0; ok && b < ix->nbuckets; b++)
        for (Entry *e = ix->buckets[b]; ok && e != NULL; e = e->next) {
            ok = put_str(f, e->word) && put_int(f, e->list.size) &&
                 fwrite(e->list.items, sizeof(Posting), e->list.size, f) ==
                     (size_t)e->list.size;
        }
    if (f != NULL && fclose(f) != 0)
        ok = 0;
    return ok ? 0 : -1;
}
Saving the index code/bachelor-1/30-project-text-search-engine/exercises/persist.c

Loading rebuilds, for each document, a text made of its words, each repeated as often as its count, and indexes these texts in document order: the lists, counts and numbers come out as before, through the code that is already tested. The loader refuses a file that ends early (every fread is checked), a name or word longer than 4096 bytes, a document number out of range, an empty list or a count that is not positive, and returns −1-1 without crashing. The test in tests/exercises_test.c saves, loads, and compares the numbers of documents, words and postings and the posting lists of five words. The file is not portable because it stores ints and Postings as the machine lays them out in memory: a machine of the other byte order (Definition 6.10) or with another size of int would read other numbers. A portable format fixes the size and the byte order of every number, as network formats do.

এই অধ্যায়ে সংজ্ঞায়িত পরিভাষা-শব্দ

পরিভাষায় সব 1050 টি শব্দ দেখো