summaryrefslogtreecommitdiffstats
path: root/src/plugins/fts/fts-search-serialize.c
blob: e30d4ce4d8af81c03c4ac781c2162334c5ad8570 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/* Copyright (c) 2011-2018 Dovecot authors, see the included COPYING file */

#include "lib.h"
#include "buffer.h"
#include "mail-search.h"
#include "fts-search-serialize.h"

#define HAVE_SUBARGS(arg) \
	((arg)->type == SEARCH_SUB || (arg)->type == SEARCH_OR)

void fts_search_serialize(buffer_t *buf, const struct mail_search_arg *args)
{
	char chr;

	for (; args != NULL; args = args->next) {
		chr = (args->match_always ? 1 : 0) |
			(args->nonmatch_always ? 2 : 0);
		buffer_append_c(buf, chr);

		if (HAVE_SUBARGS(args))
			fts_search_serialize(buf, args->value.subargs);
	}
}

static void fts_search_deserialize_idx(struct mail_search_arg *args,
				       const buffer_t *buf, unsigned int *idx)
{
	const char *data = buf->data;

	for (; args != NULL; args = args->next) {
		i_assert(*idx < buf->used);

		args->match_always = (data[*idx] & 1) != 0;
		args->nonmatch_always = (data[*idx] & 2) != 0;
		args->result = args->match_always ? 1 :
			(args->nonmatch_always ? 0 : -1);
		*idx += 1;

		if (HAVE_SUBARGS(args)) {
			fts_search_deserialize_idx(args->value.subargs,
						   buf, idx);
		}
	}
}

void fts_search_deserialize(struct mail_search_arg *args,
			    const buffer_t *buf)
{
	unsigned int idx = 0;

	fts_search_deserialize_idx(args, buf, &idx);
	i_assert(idx == buf->used);
}

static void
fts_search_deserialize_add_idx(struct mail_search_arg *args,
			       const buffer_t *buf, unsigned int *idx,
			       bool matches)
{
	const char *data = buf->data;

	for (; args != NULL; args = args->next) {
		i_assert(*idx < buf->used);

		if (data[*idx] != 0) {
			if (matches) {
				args->match_always = TRUE;
				args->result = 1;
			} else {
				args->nonmatch_always = TRUE;
				args->result = 0;
			}
		}
		*idx += 1;

		if (HAVE_SUBARGS(args)) {
			fts_search_deserialize_add_idx(args->value.subargs,
						       buf, idx, matches);
		}
	}
}

void fts_search_deserialize_add_matches(struct mail_search_arg *args,
					const buffer_t *buf)
{
	unsigned int idx = 0;

	fts_search_deserialize_add_idx(args, buf, &idx, TRUE);
	i_assert(idx == buf->used);
}

void fts_search_deserialize_add_nonmatches(struct mail_search_arg *args,
					   const buffer_t *buf)
{
	unsigned int idx = 0;

	fts_search_deserialize_add_idx(args, buf, &idx, FALSE);
	i_assert(idx == buf->used);
}