Debian Codegraph @

lib/ii.cpp

raw symbols SCIP
1 // Copyright (C) 2009-2018 Brazil
2 // Copyright (C) 2018-2026 Sutou Kouhei <[email protected]>
3 //
4 // This library is free software; you can redistribute it and/or
5 // modify it under the terms of the GNU Lesser General Public
6 // License as published by the Free Software Foundation; either
7 // version 2.1 of the License, or (at your option) any later version.
8 //
9 // This library is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 // Lesser General Public License for more details.
13 //
14 // You should have received a copy of the GNU Lesser General Public
15 // License along with this library; if not, write to the Free Software
16 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
18 #include "grn.h"
19
20 #include <fcntl.h>
21 #include <float.h>
22 #include <math.h>
23 #include <stdio.h>
24 #include <string.h>
25 #include <sys/stat.h>
26
27 #ifdef WIN32
28 # include <io.h>
29 # include <share.h>
30 #endif /* WIN32 */
31
32 #include "grn_ctx.hpp"
33 #include "grn_ii.h"
34 #include "grn_ii_select_cursor.h"
35 #include "grn_ctx_impl.h"
36 #include "grn_table.h"
37 #include "grn_token_cursor.h"
38 #include "grn_pat.h"
39 #include "grn_db.h"
40 #include "grn_obj.h"
41 #include "grn_output.h"
42 #include "grn_progress.h"
43 #include "grn_report.h"
44 #include "grn_scorer.h"
45 #include "grn_util.h"
46 #include "grn_posting.h"
47 #include "grn_vector.h"
48 #include "grn_selector.h"
49 #include "grn_wal.h"
50
51 #include <condition_variable>
52 #include <map>
53 #include <memory>
54 #include <mutex>
55 #include <vector>
56
57 #ifdef GRN_SUPPORT_REGEXP
58 # define GRN_II_SELECT_ENABLE_SEQUENTIAL_SEARCH_TEXT
59 #endif
60
61 #ifdef GRN_II_SELECT_ENABLE_SEQUENTIAL_SEARCH_TEXT
62 # include "grn_string.h"
63 # include "grn_onigmo.h"
64 #endif
65
66 /* #define GRN_II_TOKEN_INFO_DEBUG */
67 #ifdef GRN_II_TOKEN_INFO_DEBUG
68 # define P_NOTE(...) printf(__VA_ARGS__)
69 # define P_TI(ctx, token_info) grn_p_token_info((ctx), (token_info))
70 # define P_TIS(ctx, token_info, n) grn_p_token_infos((ctx), (token_info), (n))
71 #else
72 # define P_NOTE(...)
73 # define P_TI(ctx, token_info)
74 # define P_TIS(ctx, token_info, n)
75 #endif
76
77 /* P is for physical? */
78 #define MAX_PSEG 0x20000
79 #define MAX_PSEG_SMALL 0x00200
80 /* MAX_PSEG_MEDIUM has enough space for the following source:
81 * * Single source.
82 * * Source is a fixed size column or _key of a table.
83 * * Source column is a scalar column.
84 * * Lexicon doesn't have tokenizer.
85 */
86 #define MAX_PSEG_MEDIUM 0x10000
87 #define MAX_PSEG_LARGE 0x40000
88 #define S_CHUNK (1 << GRN_II_W_CHUNK)
89 #define W_SEGMENT 18
90 #define S_SEGMENT (1 << W_SEGMENT)
91 #define W_ARRAY_ELEMENT 3
92 #define S_ARRAY_ELEMENT (1 << W_ARRAY_ELEMENT)
93 #define W_ARRAY (W_SEGMENT - W_ARRAY_ELEMENT)
94 #define ARRAY_MASK_IN_A_SEGMENT ((1 << W_ARRAY) - 1)
95
96 #define S_GARBAGE (1 << 12)
97
98 #define CHUNK_SPLIT 0x80000000
99 #define CHUNK_SPLIT_THRESHOLD 0x60000
100 #define CHUNK_SPLIT_OFF(tid) ((tid) & ~CHUNK_SPLIT)
101
102 #define MAX_N_ELEMENTS 5
103
104 #ifndef S_IRUSR
105 # define S_IRUSR 0400
106 #endif /* S_IRUSR */
107 #ifndef S_IWUSR
108 # define S_IWUSR 0200
109 #endif /* S_IWUSR */
110
111 static bool grn_ii_cursor_set_min_enable = true;
112 static double grn_ii_select_too_many_index_match_ratio_text = -1;
113 static double grn_ii_select_too_many_index_match_ratio_reference = -1;
114 static double grn_ii_estimate_size_for_query_reduce_ratio = 0.9;
115 static bool grn_ii_overlap_token_skip_enable = false;
116 static uint32_t grn_ii_builder_block_threshold_force = 0;
117 static uint32_t grn_ii_max_n_segments_small = MAX_PSEG_SMALL;
118 static uint32_t grn_ii_max_n_chunks_small = GRN_II_MAX_CHUNK_SMALL;
119 static int64_t grn_ii_reduce_expire_threshold = 32;
120 static bool grn_ii_dump_index_source_on_merge = false;
121
122 extern "C" void
123 grn_ii_init_from_env(void)
124 {
125 {
126 char grn_ii_cursor_set_min_enable_env[GRN_ENV_BUFFER_SIZE];
127 grn_getenv("GRN_II_CURSOR_SET_MIN_ENABLE",
128 grn_ii_cursor_set_min_enable_env,
129 GRN_ENV_BUFFER_SIZE);
130 if (strcmp(grn_ii_cursor_set_min_enable_env, "no") == 0) {
131 grn_ii_cursor_set_min_enable = false;
132 } else {
133 grn_ii_cursor_set_min_enable = true;
134 }
135 }
136
137 {
138 char grn_ii_select_too_many_index_match_ratio_text_env[GRN_ENV_BUFFER_SIZE];
139 grn_getenv("GRN_II_SELECT_TOO_MANY_INDEX_MATCH_RATIO_TEXT",
140 grn_ii_select_too_many_index_match_ratio_text_env,
141 GRN_ENV_BUFFER_SIZE);
142 if (grn_ii_select_too_many_index_match_ratio_text_env[0]) {
143 grn_ii_select_too_many_index_match_ratio_text =
144 atof(grn_ii_select_too_many_index_match_ratio_text_env);
145 } else {
146 /* For backward compatibility. */
147 char grn_ii_select_too_many_index_match_ratio_env[GRN_ENV_BUFFER_SIZE];
148 grn_getenv("GRN_II_SELECT_TOO_MANY_INDEX_MATCH_RATIO",
149 grn_ii_select_too_many_index_match_ratio_env,
150 GRN_ENV_BUFFER_SIZE);
151 if (grn_ii_select_too_many_index_match_ratio_env[0]) {
152 grn_ii_select_too_many_index_match_ratio_text =
153 atof(grn_ii_select_too_many_index_match_ratio_env);
154 }
155 }
156 }
157
158 {
159 char grn_ii_select_too_many_index_match_ratio_reference_env
160 [GRN_ENV_BUFFER_SIZE];
161 grn_getenv("GRN_II_SELECT_TOO_MANY_INDEX_MATCH_RATIO_REFERENCE",
162 grn_ii_select_too_many_index_match_ratio_reference_env,
163 GRN_ENV_BUFFER_SIZE);
164 if (grn_ii_select_too_many_index_match_ratio_reference_env[0]) {
165 grn_ii_select_too_many_index_match_ratio_reference =
166 atof(grn_ii_select_too_many_index_match_ratio_reference_env);
167 }
168 }
169
170 {
171 char grn_ii_estimate_size_for_query_reduce_ratio_env[GRN_ENV_BUFFER_SIZE];
172 grn_getenv("GRN_II_ESTIMATE_SIZE_FOR_QUERY_REDUCE_RATIO",
173 grn_ii_estimate_size_for_query_reduce_ratio_env,
174 GRN_ENV_BUFFER_SIZE);
175 if (grn_ii_estimate_size_for_query_reduce_ratio_env[0]) {
176 grn_ii_estimate_size_for_query_reduce_ratio =
177 atof(grn_ii_estimate_size_for_query_reduce_ratio_env);
178 }
179 }
180
181 {
182 char grn_ii_overlap_token_skip_enable_env[GRN_ENV_BUFFER_SIZE];
183 grn_getenv("GRN_II_OVERLAP_TOKEN_SKIP_ENABLE",
184 grn_ii_overlap_token_skip_enable_env,
185 GRN_ENV_BUFFER_SIZE);
186 if (strcmp(grn_ii_overlap_token_skip_enable_env, "yes") == 0) {
187 grn_ii_overlap_token_skip_enable = true;
188 } else {
189 grn_ii_overlap_token_skip_enable = false;
190 }
191 }
192
193 {
194 char grn_ii_builder_block_threshold_env[GRN_ENV_BUFFER_SIZE];
195 grn_getenv("GRN_II_BUILDER_BLOCK_THRESHOLD",
196 grn_ii_builder_block_threshold_env,
197 GRN_ENV_BUFFER_SIZE);
198 if (grn_ii_builder_block_threshold_env[0]) {
199 grn_ii_builder_block_threshold_force =
200 grn_atoui(grn_ii_builder_block_threshold_env,
201 grn_ii_builder_block_threshold_env +
202 strlen(grn_ii_builder_block_threshold_env),
203 NULL);
204 } else {
205 grn_ii_builder_block_threshold_force = 0;
206 }
207 }
208
209 {
210 char grn_ii_max_n_segments_small_env[GRN_ENV_BUFFER_SIZE];
211 grn_getenv("GRN_II_MAX_N_SEGMENTS_SMALL",
212 grn_ii_max_n_segments_small_env,
213 GRN_ENV_BUFFER_SIZE);
214 if (grn_ii_max_n_segments_small_env[0]) {
215 grn_ii_max_n_segments_small =
216 grn_atoui(grn_ii_max_n_segments_small_env,
217 grn_ii_max_n_segments_small_env +
218 strlen(grn_ii_max_n_segments_small_env),
219 NULL);
220 if (grn_ii_max_n_segments_small > MAX_PSEG) {
221 grn_ii_max_n_segments_small = MAX_PSEG;
222 }
223 }
224 }
225
226 {
227 char grn_ii_max_n_chunks_small_env[GRN_ENV_BUFFER_SIZE];
228 grn_getenv("GRN_II_MAX_N_CHUNKS_SMALL",
229 grn_ii_max_n_chunks_small_env,
230 GRN_ENV_BUFFER_SIZE);
231 if (grn_ii_max_n_chunks_small_env[0]) {
232 grn_ii_max_n_chunks_small = grn_atoui(
233 grn_ii_max_n_chunks_small_env,
234 grn_ii_max_n_chunks_small_env + strlen(grn_ii_max_n_chunks_small_env),
235 NULL);
236 if (grn_ii_max_n_chunks_small > GRN_II_MAX_CHUNK) {
237 grn_ii_max_n_chunks_small = GRN_II_MAX_CHUNK;
238 }
239 }
240 }
241
242 {
243 char grn_ii_reduce_expire_threshold_env[GRN_ENV_BUFFER_SIZE];
244 grn_getenv("GRN_II_REDUCE_EXPIRE_THRESHOLD",
245 grn_ii_reduce_expire_threshold_env,
246 GRN_ENV_BUFFER_SIZE);
247 if (grn_ii_reduce_expire_threshold_env[0]) {
248 grn_ii_reduce_expire_threshold =
249 grn_atoll(grn_ii_reduce_expire_threshold_env,
250 grn_ii_reduce_expire_threshold_env +
251 strlen(grn_ii_reduce_expire_threshold_env),
252 NULL);
253 }
254 }
255
256 {
257 char grn_ii_dump_index_source_on_merge_env[GRN_ENV_BUFFER_SIZE];
258 grn_getenv("GRN_II_DUMP_INDEX_SOURCE_ON_MERGE",
259 grn_ii_dump_index_source_on_merge_env,
260 GRN_ENV_BUFFER_SIZE);
261 if (strcmp(grn_ii_dump_index_source_on_merge_env, "yes") == 0) {
262 grn_ii_dump_index_source_on_merge = true;
263 } else {
264 grn_ii_dump_index_source_on_merge = false;
265 }
266 }
267 }
268
269 extern "C" void
270 grn_ii_cursor_set_min_enable_set(bool enable)
271 {
272 grn_ii_cursor_set_min_enable = enable;
273 }
274
275 extern "C" bool
276 grn_ii_cursor_set_min_enable_get(void)
277 {
278 return grn_ii_cursor_set_min_enable;
279 }
280
281 static void
282 grn_ii_get_term(grn_ctx *ctx, grn_ii *ii, grn_id tid, grn_obj *term)
283 {
284 if (tid == GRN_ID_NIL) {
285 return;
286 }
287
288 char key[GRN_TABLE_MAX_KEY_SIZE];
289 int key_size;
290 key_size =
291 grn_table_get_key(ctx, ii->lexicon, tid, key, GRN_TABLE_MAX_KEY_SIZE);
292 if (key_size != 0) {
293 grn_obj key_buf;
294 GRN_OBJ_INIT(&key_buf,
295 GRN_BULK,
296 GRN_OBJ_DO_SHALLOW_COPY,
297 ii->lexicon->header.domain);
298 GRN_TEXT_SET(ctx, &key_buf, key, key_size);
299 grn_inspect(ctx, term, &key_buf);
300 GRN_OBJ_FIN(ctx, &key_buf);
301 }
302 }
303
304 /* segment */
305
306 static inline uint32_t
307 grn_ii_get_array_pseg_inline(grn_ii *ii, uint32_t lseg)
308 {
309 if (lseg < GRN_II_MAX_LSEG) {
310 return ii->header.common->ainfo[lseg];
311 } else {
312 return ii->header.large->ainfo_extend[lseg - GRN_II_MAX_LSEG];
313 }
314 }
315
316 static inline void
317 grn_ii_set_array_pseg_inline(grn_ii *ii, uint32_t lseg, uint32_t pseg)
318 {
319 if (lseg < GRN_II_MAX_LSEG) {
320 ii->header.common->ainfo[lseg] = pseg;
321 } else {
322 ii->header.large->ainfo_extend[lseg - GRN_II_MAX_LSEG] = pseg;
323 }
324 }
325
326 static inline uint32_t
327 grn_ii_get_buffer_pseg_inline(grn_ii *ii, uint32_t lseg)
328 {
329 if (lseg < GRN_II_MAX_LSEG) {
330 return ii->header.common->binfo[lseg];
331 } else {
332 return ii->header.large->binfo_extend[lseg - GRN_II_MAX_LSEG];
333 }
334 }
335
336 static inline uint32_t *
337 grn_ii_get_buffer_pseg_address_inline(grn_ii *ii, uint32_t lseg)
338 {
339 if (lseg < GRN_II_MAX_LSEG) {
340 return &(ii->header.common->binfo[lseg]);
341 } else {
342 return &(ii->header.large->binfo_extend[lseg - GRN_II_MAX_LSEG]);
343 }
344 }
345
346 static inline void
347 grn_ii_set_buffer_pseg_inline(grn_ii *ii, uint32_t lseg, uint32_t pseg)
348 {
349 if (lseg < GRN_II_MAX_LSEG) {
350 ii->header.common->binfo[lseg] = pseg;
351 } else {
352 ii->header.large->binfo_extend[lseg - GRN_II_MAX_LSEG] = pseg;
353 }
354 }
355
356 static inline uint32_t
357 grn_ii_n_logical_segments_inline(grn_ii *ii)
358 {
359 if (ii->header.common->flags & GRN_OBJ_INDEX_LARGE) {
360 return GRN_II_MAX_LSEG + GRN_II_MAX_LSEG_EXTEND;
361 } else {
362 return GRN_II_MAX_LSEG;
363 }
364 }
365
366 static inline uint32_t
367 segment_get(grn_ctx *ctx, grn_ii *ii)
368 {
369 grn_ii_header_common *header = ii->header.common;
370 uint32_t pseg;
371 if (header->bgqtail == ((header->bgqhead + 1) & (GRN_II_BGQSIZE - 1))) {
372 pseg = header->bgqbody[header->bgqtail];
373 header->bgqtail = (header->bgqtail + 1) & (GRN_II_BGQSIZE - 1);
374 } else {
375 pseg = header->pnext;
376 if (!pseg) {
377 uint32_t i;
378 uint32_t pmax = 0;
379 const uint32_t max_segment = ii->seg->header->max_segment;
380 auto used = static_cast<char *>(GRN_CALLOC(max_segment));
381 if (!used) {
382 return max_segment;
383 }
384 const uint32_t n_logical_segments = grn_ii_n_logical_segments_inline(ii);
385 for (i = 0; i < n_logical_segments; i++) {
386 pseg = grn_ii_get_array_pseg_inline(ii, i);
387 if (pseg != GRN_II_PSEG_NOT_ASSIGNED) {
388 if (pseg > pmax) {
389 pmax = pseg;
390 }
391 used[pseg] = 1;
392 }
393 pseg = grn_ii_get_buffer_pseg_inline(ii, i);
394 if (pseg != GRN_II_PSEG_NOT_ASSIGNED) {
395 if (pseg > pmax) {
396 pmax = pseg;
397 }
398 used[pseg] = 1;
399 }
400 }
401 for (pseg = 0; pseg < max_segment && used[pseg]; pseg++)
402 ;
403 GRN_FREE(used);
404 header->pnext = pmax + 1;
405 } else if (ii->header.common->pnext < ii->seg->header->max_segment) {
406 header->pnext++;
407 }
408 }
409 return pseg;
410 }
411
412 static inline grn_rc
413 segment_get_clear(grn_ctx *ctx, grn_ii *ii, uint32_t *pseg)
414 {
415 uint32_t seg = segment_get(ctx, ii);
416 if (seg < ii->seg->header->max_segment) {
417 void *p = grn_io_seg_ref(ctx, ii->seg, seg);
418 if (!p) {
419 return GRN_NO_MEMORY_AVAILABLE;
420 }
421 memset(p, 0, S_SEGMENT);
422 grn_io_seg_unref(ctx, ii->seg, seg);
423 *pseg = seg;
424 return GRN_SUCCESS;
425 } else {
426 return GRN_NO_MEMORY_AVAILABLE;
427 }
428 }
429
430 static inline grn_rc
431 buffer_segment_new(grn_ctx *ctx, grn_ii *ii, uint32_t *segno)
432 {
433 uint32_t lseg, pseg;
434 if (*segno == GRN_II_PSEG_NOT_ASSIGNED) {
435 const uint32_t n_logical_segments = grn_ii_n_logical_segments_inline(ii);
436 for (lseg = 0; lseg < n_logical_segments; lseg++) {
437 if (grn_ii_get_buffer_pseg_inline(ii, lseg) == GRN_II_PSEG_NOT_ASSIGNED) {
438 break;
439 }
440 }
441 if (lseg == n_logical_segments) {
442 return GRN_NO_MEMORY_AVAILABLE;
443 }
444 *segno = lseg;
445 } else {
446 if (grn_ii_get_buffer_pseg_inline(ii, *segno) != GRN_II_PSEG_NOT_ASSIGNED) {
447 return GRN_INVALID_ARGUMENT;
448 }
449 lseg = *segno;
450 }
451 pseg = segment_get(ctx, ii);
452 if (pseg < ii->seg->header->max_segment) {
453 grn_ii_set_buffer_pseg_inline(ii, lseg, pseg);
454 if (lseg >= ii->header.common->bmax) {
455 ii->header.common->bmax = lseg + 1;
456 }
457 return GRN_SUCCESS;
458 } else {
459 return GRN_NO_MEMORY_AVAILABLE;
460 }
461 }
462
463 static grn_rc
464 buffer_segment_reserve(grn_ctx *ctx,
465 grn_ii *ii,
466 uint32_t *lseg0,
467 uint32_t *pseg0,
468 uint32_t *lseg1,
469 uint32_t *pseg1)
470 {
471 uint32_t i = 0;
472 const uint32_t n_logical_segments = grn_ii_n_logical_segments_inline(ii);
473 for (;; i++) {
474 if (i == n_logical_segments) {
475 GRN_DEFINE_NAME(ii);
476 MERR("[ii][buffer][segment][reserve] "
477 "couldn't find a free buffer: <%.*s>: max:<%u>",
478 name_size,
479 name,
480 n_logical_segments);
481 return ctx->rc;
482 }
483 if (grn_ii_get_buffer_pseg_inline(ii, i) == GRN_II_PSEG_NOT_ASSIGNED) {
484 break;
485 }
486 }
487 *lseg0 = i++;
488 for (;; i++) {
489 if (i == n_logical_segments) {
490 GRN_DEFINE_NAME(ii);
491 MERR("[ii][buffer][segment][reserve] "
492 "couldn't find two free buffers: "
493 "<%.*s>: "
494 "found:<%u>, max:<%u>",
495 name_size,
496 name,
497 *lseg0,
498 n_logical_segments);
499 return ctx->rc;
500 }
501 if (grn_ii_get_buffer_pseg_inline(ii, i) == GRN_II_PSEG_NOT_ASSIGNED) {
502 break;
503 }
504 }
505 *lseg1 = i;
506 if ((*pseg0 = segment_get(ctx, ii)) == ii->seg->header->max_segment) {
507 GRN_DEFINE_NAME(ii);
508 MERR("[ii][buffer][segment][reserve] "
509 "couldn't allocate a free segment: <%.*s>: "
510 "buffer:<%u>, max:<%u>",
511 name_size,
512 name,
513 *lseg0,
514 ii->seg->header->max_segment);
515 return ctx->rc;
516 }
517 if ((*pseg1 = segment_get(ctx, ii)) == ii->seg->header->max_segment) {
518 GRN_DEFINE_NAME(ii);
519 MERR("[ii][buffer][segment][reserve] "
520 "couldn't allocate two free segments: "
521 "<%.*s>: "
522 "found:<%u>, not-found:<%u>, max:<%u>",
523 name_size,
524 name,
525 *lseg0,
526 *lseg1,
527 ii->seg->header->max_segment);
528 return ctx->rc;
529 }
530 return ctx->rc;
531 }
532
533 static inline void
534 buffer_garbage_enqueue(grn_ii *ii, uint32_t lseg)
535 {
536 const uint32_t pseg = grn_ii_get_buffer_pseg_inline(ii, lseg);
537 if (pseg != GRN_II_PSEG_NOT_ASSIGNED) {
538 grn_ii_header_common *header = ii->header.common;
539 header->bgqbody[header->bgqhead] = header->binfo[lseg];
540 header->bgqhead = (header->bgqhead + 1) & (GRN_II_BGQSIZE - 1);
541 GRN_ASSERT(header->bgqhead != header->bgqtail);
542 }
543 }
544
545 static inline void
546 buffer_segment_update(grn_ii *ii, uint32_t lseg, uint32_t pseg)
547 {
548 buffer_garbage_enqueue(ii, lseg);
549 // smb_wmb();
550 grn_ii_set_buffer_pseg_inline(ii, lseg, pseg);
551 if (lseg >= ii->header.common->bmax) {
552 ii->header.common->bmax = lseg + 1;
553 }
554 }
555
556 static inline void
557 buffer_segment_clear(grn_ii *ii, uint32_t lseg)
558 {
559 buffer_garbage_enqueue(ii, lseg);
560 // smb_wmb();
561 grn_ii_set_buffer_pseg_inline(ii, lseg, GRN_II_PSEG_NOT_ASSIGNED);
562 }
563
564 /* chunk */
565
566 #define HEADER_CHUNK_AT(ii, offset) \
567 ((((ii)->header.common->chunks[((offset) >> 3)]) >> ((offset) & 7)) & 1)
568
569 #define HEADER_CHUNK_ON(ii, offset) \
570 (((ii)->header.common->chunks[((offset) >> 3)]) |= (1 << ((offset) & 7)))
571
572 #define HEADER_CHUNK_OFF(ii, offset) \
573 (((ii)->header.common->chunks[((offset) >> 3)]) &= ~(1 << ((offset) & 7)))
574
575 #define N_GARBAGES_TH 1
576
577 #define N_GARBAGES ((S_GARBAGE - (sizeof(uint32_t) * 4)) / (sizeof(uint32_t)))
578
579 typedef struct {
580 uint32_t head;
581 uint32_t tail;
582 uint32_t nrecs;
583 uint32_t next;
584 uint32_t recs[N_GARBAGES];
585 } grn_ii_ginfo;
586
587 #define WIN_MAP(ctx, chunk, iw, seg, pos, size, mode) \
588 grn_io_win_map(ctx, \
589 chunk, \
590 iw, \
591 ((seg) >> GRN_II_N_CHUNK_VARIATION), \
592 (((seg) & ((1 << GRN_II_N_CHUNK_VARIATION) - 1)) \
593 << GRN_II_W_LEAST_CHUNK) + \
594 (pos), \
595 size, \
596 mode)
597
598 /*
599 static int new_histogram[32];
600 static int free_histogram[32];
601 */
602
603 /*
604 N = grn_ii_max_n_chunks_small for GRN_OBJ_INDEX_SMALL
605 N = GRN_II_MAX_N_CHUNKS_MEDIUM for GRN_OBJ_INDEX_MEDIUM
606 N = GRN_II_MAX_N_CHUNKS for GRN_OBJ_INDEX_LARGE
607 N = GRN_II_MAX_N_CHUNKS without index size flag
608
609 S_CHUNK = (1 << GRN_II_W_CHUNK(22)) = 4MiB
610
611 +------------+ +------------+
612 | chunk0 | ... | chunkN |
613 +------------+ +------------+
614 |<--S_CHUNK->|
615
616 ii->header.common->chunks has flags whether the target chunk is
617 assigned or not. We can manipulate the flags by HEADER_CHUNK_AT(),
618 HEADER_CHUNK_ON() and HEADER_CHUNK_OFF(). Here is a snapshot when we
619 only assign chunk0 and chunk2:
620
621 +------------+------------+------------+ +------------+
622 | chunk0 | chunk1 | chunk2 | ... | chunkN |
623 +------------+------------+------------+ +------------+
624 ON OFF ON OFF
625
626 If requested size is greater than S_CHUNK, continuous non-assigned
627 chunks are assigned. For example, if S_CHUNK + 100 is requested and
628 chunk1 is assigned, chunk0 isn't assigned. chunk2 and chunk3 are
629 assigned.
630
631 +------------+------------+------------+------------+ +------------+
632 | chunk0 | chunk1 | chunk2 | chunk3 | ... | chunkN |
633 +------------+------------+------------+------------+ +------------+
634 OFF ON OFF -> ON OFF -> ON OFF
635
636 If requested size is smaller than or equal to S_CHUNK, a subchunk is
637 assigned. Subchunks in the same chunk has the same size. The
638 smallest subchunk size is (1 << GRN_II_W_LEAST_CHUNK(8)) = 256
639 bytes. Subchunk size is power of 2. For example, chunk0 uses 512
640 bytes for subchunk size, chunk0 can have 812 (S_CHUNK / 512)
641 subchunks.
642
643 +-------------+
644 | chunk0 |
645 +-------------+
646 <->|<->|...|<-> subchunks
647 512|512| |512
648
649 If one of subchunk is assigned, HEADER_CHUNK_AT() of the chunk is true.
650
651 +-------------+
652 | chunk0 |
653 +-------------+
654 <------>|<->|... subchunks
655 ASSIGNED|NOT|
656 ON
657
658 Chunks that are assigning subchunks are keeping in
659 ii->header.common.free_chunks. free_chunks keeps a chunk per
660 subchunk size. For example, chunk0 is kept for 256 subchunk size and
661 chunk1 is kept for 512 subchunk size.
662
663 chunk_new() returns the (offset >> GRN_II_W_LEAST_CHUNK(8)) of
664 subchunk not the index of chunk. For example, if the third subchunk
665 of chunk0 that uses 512 bytes for subchunk size is assigned, 4 (1024
666 >> 8) is returned.
667
668 +-------------+
669 | chunk0 |
670 +-------------+
671 <0>|<1>|<2>|...
672 0 2 4
673
674 chunk_new() wants to reuse freed subchunks as much as possible to
675 reduce disk usage. ii->header.common.garbages keeps freed subchunks
676 to reuse later.
677
678 TODO: More description for garbages.
679 */
680
681 static grn_rc
682 chunk_free(grn_ctx *ctx, grn_ii *ii, uint32_t offset, uint32_t size);
683
684 static grn_rc
685 chunk_new(grn_ctx *ctx, grn_ii *ii, uint32_t *res, uint32_t size)
686 {
687 uint32_t n_chunks;
688
689 n_chunks = ii->chunk->header->max_segment;
690
691 /*
692 if (size) {
693 int es = size - 1;
694 grn_bit_scan_rev_result m;
695 GRN_BIT_SCAN_REV(es, m);
696 m++;
697 new_histogram[m]++;
698 }
699 */
700 if (size > S_CHUNK) {
701 uint32_t i, j;
702 uint32_t n = (size + S_CHUNK - 1) >> GRN_II_W_CHUNK;
703 for (i = 0, j = -1; i < n_chunks; i++) {
704 if (HEADER_CHUNK_AT(ii, i)) {
705 j = i;
706 } else {
707 if (i == j + n) {
708 j++;
709 *res = j << GRN_II_N_CHUNK_VARIATION;
710 for (; j <= i; j++) {
711 HEADER_CHUNK_ON(ii, j);
712 }
713 return GRN_SUCCESS;
714 }
715 }
716 }
717 {
718 GRN_DEFINE_NAME(ii);
719 MERR("[ii][chunk][new] index is full: "
720 "<%.*s>: "
721 "size:<%u>, n-chunks:<%u>",
722 name_size,
723 name,
724 size,
725 n_chunks);
726 }
727 return ctx->rc;
728 } else {
729 uint32_t *vp;
730 grn_bit_scan_rev_result m;
731 if (size > (1 << GRN_II_W_LEAST_CHUNK)) {
732 int es = size - 1;
733 GRN_BIT_SCAN_REV(es, m);
734 m++;
735 } else {
736 m = GRN_II_W_LEAST_CHUNK;
737 }
738 grn_ii_header_common *header = ii->header.common;
739 if (header->ngarbages[m - GRN_II_W_LEAST_CHUNK] > N_GARBAGES_TH) {
740 uint32_t *gseg;
741 grn_io_win iw, iw_;
742 iw_.addr = NULL;
743 gseg = &header->garbages[m - GRN_II_W_LEAST_CHUNK];
744 while (*gseg != GRN_II_PSEG_NOT_ASSIGNED) {
745 auto ginfo = static_cast<grn_ii_ginfo *>(
746 WIN_MAP(ctx, ii->chunk, &iw, *gseg, 0, S_GARBAGE, GRN_IO_RDWR));
747 // GRN_IO_SEG_MAP2(ii->chunk, *gseg, ginfo);
748 if (!ginfo) {
749 if (iw_.addr) {
750 grn_io_win_unmap(ctx, &iw_);
751 }
752 {
753 GRN_DEFINE_NAME(ii);
754 MERR("[ii][chunk][new] failed to allocate garbage segment: "
755 "<%.*s>: "
756 "n-garbages:<%u>, size:<%u>, n-chunks:<%u>",
757 name_size,
758 name,
759 header->ngarbages[m - GRN_II_W_LEAST_CHUNK],
760 size,
761 n_chunks);
762 }
763 return ctx->rc;
764 }
765 if (ginfo->next != GRN_II_PSEG_NOT_ASSIGNED ||
766 ginfo->nrecs > N_GARBAGES_TH) {
767 *res = ginfo->recs[ginfo->tail];
768 if (++ginfo->tail == N_GARBAGES) {
769 ginfo->tail = 0;
770 }
771 ginfo->nrecs--;
772 header->ngarbages[m - GRN_II_W_LEAST_CHUNK]--;
773 uint32_t current_garbage_segment = *gseg;
774 bool no_garbage_info = (ginfo->nrecs == 0);
775 if (no_garbage_info) {
776 *gseg = ginfo->next;
777 }
778 if (iw_.addr) {
779 grn_io_win_unmap(ctx, &iw_);
780 }
781 grn_io_win_unmap(ctx, &iw);
782 if (no_garbage_info) {
783 chunk_free(ctx, ii, current_garbage_segment, S_GARBAGE);
784 }
785 return GRN_SUCCESS;
786 }
787 if (iw_.addr) {
788 grn_io_win_unmap(ctx, &iw_);
789 }
790 iw_ = iw;
791 gseg = &ginfo->next;
792 }
793 if (iw_.addr) {
794 grn_io_win_unmap(ctx, &iw_);
795 }
796 }
797 vp = &header->free_chunks[m - GRN_II_W_LEAST_CHUNK];
798 if (*vp == GRN_II_PSEG_NOT_ASSIGNED) {
799 uint32_t i = 0;
800 while (HEADER_CHUNK_AT(ii, i)) {
801 if (++i >= n_chunks) {
802 GRN_DEFINE_NAME(ii);
803 MERR("[ii][chunk][new] failed to find a free chunk: "
804 "<%.*s>: "
805 "index:<%u>, size:<%u>, n-chunks:<%u>",
806 name_size,
807 name,
808 m - GRN_II_W_LEAST_CHUNK,
809 size,
810 n_chunks);
811 return ctx->rc;
812 }
813 }
814 HEADER_CHUNK_ON(ii, i);
815 *vp = i << GRN_II_N_CHUNK_VARIATION;
816 }
817 *res = *vp;
818 /* Next subchunk. */
819 *vp += 1 << (m - GRN_II_W_LEAST_CHUNK);
820 /* (*vp % GRN_II_N_CHUNK_VARIATION) == 0 */
821 if (!(*vp & ((1 << GRN_II_N_CHUNK_VARIATION) - 1))) {
822 /* All subchunks are consumed. */
823 *vp = GRN_II_PSEG_NOT_ASSIGNED;
824 }
825 return GRN_SUCCESS;
826 }
827 }
828
829 static grn_rc
830 chunk_free(grn_ctx *ctx, grn_ii *ii, uint32_t offset, uint32_t size)
831 {
832 /*
833 if (size) {
834 int es = size - 1;
835 grn_bit_scan_rev_result m;
836 GRN_BIT_SCAN_REV(es, m);
837 m++;
838 free_histogram[m]++;
839 }
840 */
841 grn_io_win iw, iw_;
842 grn_ii_ginfo *ginfo;
843 uint32_t seg, *gseg;
844 seg = offset >> GRN_II_N_CHUNK_VARIATION;
845 if (size > S_CHUNK) {
846 int n = (size + S_CHUNK - 1) >> GRN_II_W_CHUNK;
847 for (; n--; seg++) {
848 HEADER_CHUNK_OFF(ii, seg);
849 }
850 return GRN_SUCCESS;
851 }
852 grn_bit_scan_rev_result m;
853 if (size > (1 << GRN_II_W_LEAST_CHUNK)) {
854 int es = size - 1;
855 GRN_BIT_SCAN_REV(es, m);
856 m++;
857 } else {
858 m = GRN_II_W_LEAST_CHUNK;
859 }
860 gseg = &ii->header.common->garbages[m - GRN_II_W_LEAST_CHUNK];
861 iw_.addr = NULL;
862 while (*gseg != GRN_II_PSEG_NOT_ASSIGNED) {
863 ginfo = static_cast<grn_ii_ginfo *>(
864 WIN_MAP(ctx, ii->chunk, &iw, *gseg, 0, S_GARBAGE, GRN_IO_RDWR));
865 // GRN_IO_SEG_MAP2(ii->chunk, *gseg, ginfo);
866 if (!ginfo) {
867 if (iw_.addr) {
868 grn_io_win_unmap(ctx, &iw_);
869 }
870 return GRN_NO_MEMORY_AVAILABLE;
871 }
872 if (ginfo->nrecs < N_GARBAGES) {
873 break;
874 }
875 if (iw_.addr) {
876 grn_io_win_unmap(ctx, &iw_);
877 }
878 iw_ = iw;
879 gseg = &ginfo->next;
880 }
881 if (*gseg == GRN_II_PSEG_NOT_ASSIGNED) {
882 grn_rc rc;
883 if ((rc = chunk_new(ctx, ii, gseg, S_GARBAGE))) {
884 if (iw_.addr) {
885 grn_io_win_unmap(ctx, &iw_);
886 }
887 return rc;
888 }
889 ginfo = static_cast<grn_ii_ginfo *>(
890 WIN_MAP(ctx, ii->chunk, &iw, *gseg, 0, S_GARBAGE, GRN_IO_RDWR));
891 /*
892 uint32_t i = 0;
893 while (HEADER_CHUNK_AT(ii, i)) {
894 if (++i >= ii->chunk->header->max_segment) {
895 return GRN_NO_MEMORY_AVAILABLE;
896 }
897 }
898 HEADER_CHUNK_ON(ii, i);
899 *gseg = i;
900 GRN_IO_SEG_MAP2(ii->chunk, *gseg, ginfo);
901 */
902 if (!ginfo) {
903 if (iw_.addr) {
904 grn_io_win_unmap(ctx, &iw_);
905 }
906 return GRN_NO_MEMORY_AVAILABLE;
907 }
908 ginfo->head = 0;
909 ginfo->tail = 0;
910 ginfo->nrecs = 0;
911 ginfo->next = GRN_II_PSEG_NOT_ASSIGNED;
912 }
913 if (iw_.addr) {
914 grn_io_win_unmap(ctx, &iw_);
915 }
916 ginfo->recs[ginfo->head] = offset;
917 if (++ginfo->head == N_GARBAGES) {
918 ginfo->head = 0;
919 }
920 ginfo->nrecs++;
921 grn_io_win_unmap(ctx, &iw);
922 ii->header.common->ngarbages[m - GRN_II_W_LEAST_CHUNK]++;
923 return GRN_SUCCESS;
924 }
925
926 #define DATA_USE_P_FOR_ENC (1 << 0) /* Use PFor */
927 #define DATA_ODD (1 << 2) /* Variable size data */
928
929 typedef struct {
930 uint32_t *data;
931 uint32_t data_size;
932 uint32_t flags;
933 } datavec;
934
935 static grn_rc
936 datavec_reset(
937 grn_ctx *ctx, grn_ii *ii, datavec *dv, size_t unitsize, size_t totalsize)
938 {
939 uint32_t i;
940 if (!dv[0].data || dv[ii->n_elements].data < dv[0].data + totalsize) {
941 if (dv[0].data) {
942 GRN_FREE(dv[0].data);
943 }
944 if (!(dv[0].data = static_cast<uint32_t *>(
945 GRN_MALLOC(totalsize * sizeof(uint32_t))))) {
946 MERR("[ii][data-vector][reset] failed to allocate data: "
947 "length:<%u>, "
948 "unit-size:<%" GRN_FMT_SIZE ">, "
949 "total-size:<%" GRN_FMT_SIZE ">",
950 ii->n_elements,
951 unitsize,
952 totalsize);
953 return ctx->rc;
954 }
955 dv[ii->n_elements].data = dv[0].data + totalsize;
956 }
957 for (i = 1; i < ii->n_elements; i++) {
958 dv[i].data = dv[i - 1].data + unitsize;
959 }
960 return GRN_SUCCESS;
961 }
962
963 static grn_rc
964 datavec_init(
965 grn_ctx *ctx, grn_ii *ii, datavec *dv, size_t unitsize, size_t totalsize)
966 {
967 uint32_t i;
968 if (totalsize == 0) {
969 memset(dv, 0, sizeof(datavec) * (ii->n_elements + 1));
970 } else {
971 if (!(dv[0].data = static_cast<uint32_t *>(
972 GRN_MALLOC(totalsize * sizeof(uint32_t))))) {
973 MERR("[ii][data-vector][init] failed to allocate data: "
974 "length:<%u>, "
975 "unit-size:<%" GRN_FMT_SIZE ">, "
976 "total-size:<%" GRN_FMT_SIZE ">",
977 ii->n_elements,
978 unitsize,
979 totalsize);
980 return ctx->rc;
981 }
982 dv[ii->n_elements].data = dv[0].data + totalsize;
983 dv[0].flags = 0;
984 for (i = 1; i < ii->n_elements; i++) {
985 dv[i].data = dv[i - 1].data + unitsize;
986 dv[i].flags = 0;
987 }
988 }
989 if (ii->header.common->flags & GRN_OBJ_WITH_POSITION) {
990 dv[ii->n_elements - 1].flags = DATA_ODD;
991 }
992 return GRN_SUCCESS;
993 }
994
995 static void
996 datavec_fin(grn_ctx *ctx, datavec *dv)
997 {
998 if (dv[0].data) {
999 GRN_FREE(dv[0].data);
1000 }
1001 }
1002
1003 static inline bool
1004 data_records_use_p_for_enc(uint32_t n_records, uint32_t max_record_id)
1005 {
1006 return n_records >= 16 && (n_records > (max_record_id >> 8));
1007 }
1008
1009 static inline bool
1010 data_sections_use_p_for_enc(uint32_t n_records)
1011 {
1012 return n_records >= 3;
1013 }
1014
1015 static inline bool
1016 data_positions_use_p_for_enc(uint32_t n_positions, uint32_t max_position)
1017 {
1018 return n_positions >= 32 && n_positions > (max_position >> 13);
1019 }
1020
1021 static inline void
1022 datavec_set_data_size(grn_ctx *ctx,
1023 grn_ii *ii,
1024 datavec *dv,
1025 uint32_t n_records,
1026 grn_id max_record_id,
1027 uint32_t n_positions,
1028 uint32_t max_position)
1029 {
1030 int i = 0;
1031 bool records_use_p_for_enc =
1032 data_records_use_p_for_enc(n_records, max_record_id);
1033 bool sections_use_p_for_enc = data_sections_use_p_for_enc(n_records);
1034 /* record IDs */
1035 dv[i].data_size = n_records;
1036 if (records_use_p_for_enc) {
1037 dv[i++].flags |= DATA_USE_P_FOR_ENC;
1038 } else {
1039 dv[i++].flags &= ~DATA_USE_P_FOR_ENC;
1040 }
1041 if ((ii->header.common->flags & GRN_OBJ_WITH_SECTION)) {
1042 /* section IDs */
1043 dv[i].data_size = n_records;
1044 if (sections_use_p_for_enc) {
1045 dv[i++].flags |= DATA_USE_P_FOR_ENC;
1046 } else {
1047 dv[i++].flags &= ~DATA_USE_P_FOR_ENC;
1048 }
1049 }
1050 /* term frequencies */
1051 dv[i].data_size = n_records;
1052 if (sections_use_p_for_enc) {
1053 dv[i++].flags |= DATA_USE_P_FOR_ENC;
1054 } else {
1055 dv[i++].flags &= ~DATA_USE_P_FOR_ENC;
1056 }
1057 if ((ii->header.common->flags & GRN_OBJ_WITH_WEIGHT)) {
1058 /* weights */
1059 dv[i].data_size = n_records;
1060 if (sections_use_p_for_enc) {
1061 dv[i++].flags |= DATA_USE_P_FOR_ENC;
1062 } else {
1063 dv[i++].flags &= ~DATA_USE_P_FOR_ENC;
1064 }
1065 }
1066 if (ii->header.common->flags & GRN_OBJ_WITH_POSITION) {
1067 /* positions */
1068 dv[i].data_size = n_positions;
1069 if (data_positions_use_p_for_enc(n_positions, max_position)) {
1070 dv[i++].flags |= DATA_USE_P_FOR_ENC;
1071 } else {
1072 dv[i++].flags &= ~DATA_USE_P_FOR_ENC;
1073 }
1074 }
1075 }
1076
1077 typedef struct {
1078 grn_ii *ii;
1079 grn_id term_id;
1080 uint32_t nth_element;
1081 uint32_t n_odd_values;
1082 uint32_t *values;
1083 uint32_t n_values;
1084 uint32_t flags;
1085 size_t offset;
1086 size_t size;
1087 /* Only for encoder */
1088 uint8_t *output;
1089 /* Only for decoder */
1090 const uint8_t *input;
1091 } grn_codec_data;
1092
1093 static inline void
1094 grn_codec_error(grn_ctx *ctx,
1095 grn_rc rc,
1096 grn_codec_data *data,
1097 const char *message,
1098 const char *file,
1099 uint32_t line,
1100 const char *function)
1101 {
1102 grn_obj term;
1103 GRN_DEFINE_NAME(data->ii);
1104 GRN_TEXT_INIT(&term, 0);
1105 if (data->term_id != GRN_ID_NIL) {
1106 grn_ii_get_term(ctx, data->ii, data->term_id, &term);
1107 }
1108 grn_error_set(ctx,
1109 GRN_ERROR,
1110 rc,
1111 file,
1112 line,
1113 function,
1114 "%s: "
1115 "<%.*s>: "
1116 "<%.*s>(%u): "
1117 "n-values(%u): "
1118 "n-odd-values(%u): "
1119 "dv[%u/%u]: "
1120 "data[%" GRN_FMT_SIZE "/%" GRN_FMT_SIZE "]",
1121 message,
1122 name_size,
1123 name,
1124 (int)GRN_TEXT_LEN(&term),
1125 GRN_TEXT_VALUE(&term),
1126 data->term_id,
1127 data->n_values,
1128 data->n_odd_values,
1129 data->nth_element,
1130 data->ii->n_elements,
1131 data->offset,
1132 data->size);
1133 GRN_OBJ_FIN(ctx, &term);
1134 }
1135
1136 static inline size_t
1137 grn_enc_estimate_byte(grn_ctx *ctx, grn_codec_data *data)
1138 {
1139 return GRN_B_ENC_MAX_SIZE * data->n_values;
1140 }
1141
1142 static inline uint8_t *
1143 grn_enc_byte(grn_ctx *ctx, grn_codec_data *data)
1144 {
1145 uint8_t *output = data->output;
1146 uint32_t i;
1147 for (i = 0; i < data->n_values; i++) {
1148 GRN_B_ENC(data->values[i], output);
1149 }
1150 return output;
1151 }
1152
1153 static inline const uint8_t *
1154 grn_dec_byte_check(grn_ctx *ctx,
1155 grn_codec_data *data,
1156 uint32_t *value,
1157 const uint8_t *input,
1158 const uint8_t *input_end)
1159 {
1160 if (input >= input_end) {
1161 grn_codec_error(ctx,
1162 GRN_FILE_CORRUPT,
1163 data,
1164 "[ii][dec][byte] "
1165 "input is short: at least 1 byte is needed",
1166 __FILE__,
1167 __LINE__,
1168 __FUNCTION__);
1169 return NULL;
1170 }
1171 uint32_t v = *input++;
1172 data->offset++;
1173 switch (v >> 4) {
1174 case 0x08:
1175 if (v == 0x8f) {
1176 if (input + sizeof(uint32_t) > input_end) {
1177 grn_codec_error(ctx,
1178 GRN_FILE_CORRUPT,
1179 data,
1180 "[ii][dec][byte] "
1181 "input is short: at least more 4 bytes are needed",
1182 __FILE__,
1183 __LINE__,
1184 __FUNCTION__);
1185 return NULL;
1186 }
1187 grn_memcpy(&v, input, sizeof(uint32_t));
1188 input += sizeof(uint32_t);
1189 data->offset += sizeof(uint32_t);
1190 }
1191 break;
1192 case 0x09:
1193 if (input + 3 > input_end) {
1194 grn_codec_error(ctx,
1195 GRN_FILE_CORRUPT,
1196 data,
1197 "[ii][dec][byte] "
1198 "input is short: at least more 3 bytes are needed",
1199 __FILE__,
1200 __LINE__,
1201 __FUNCTION__);
1202 return NULL;
1203 }
1204 v = (v - 0x90) * 0x100 + *input++;
1205 v = v * 0x100 + *input++;
1206 v = v * 0x100 + *input++ + 0x20408f;
1207 data->offset += 3;
1208 break;
1209 case 0x0a:
1210 case 0x0b:
1211 if (input + 2 > input_end) {
1212 grn_codec_error(ctx,
1213 GRN_FILE_CORRUPT,
1214 data,
1215 "[ii][dec][byte] "
1216 "input is short: at least more 2 bytes are needed",
1217 __FILE__,
1218 __LINE__,
1219 __FUNCTION__);
1220 return NULL;
1221 }
1222 v = (v - 0xa0) * 0x100 + *input++;
1223 v = v * 0x100 + *input++ + 0x408f;
1224 data->offset += 2;
1225 break;
1226 case 0x0c:
1227 case 0x0d:
1228 case 0x0e:
1229 case 0x0f:
1230 if (input + 1 > input_end) {
1231 grn_codec_error(ctx,
1232 GRN_FILE_CORRUPT,
1233 data,
1234 "[ii][dec][byte] "
1235 "input is short: at least more 1 byte is needed",
1236 __FILE__,
1237 __LINE__,
1238 __FUNCTION__);
1239 return NULL;
1240 }
1241 v = (v - 0xc0) * 0x100 + *input++ + 0x8f;
1242 break;
1243 }
1244 *value = v;
1245 return input;
1246 }
1247
1248 static inline const uint8_t *
1249 grn_dec_byte(grn_ctx *ctx, grn_codec_data *data)
1250 {
1251 const uint8_t *input = data->input;
1252 const uint8_t *input_end = input + data->size;
1253 uint32_t i;
1254 for (i = 0; i < data->n_values && input; i++) {
1255 input = grn_dec_byte_check(ctx, data, &(data->values[i]), input, input_end);
1256 }
1257 return input;
1258 }
1259
1260 /* PFor implementation: start */
1261
1262 /*
1263 * PFor (Patched Frame of Reference) encode: M. Zukowski , S. Heman,
1264 * N. Nes, P. Boncz, Super-Scalar RAM-CPU Cache Compression,
1265 * Proceedings of the 22nd International Conference on Data
1266 * Engineering, 2006
1267 *
1268 * Delta decoding must be done by caller. So pack()/unpack() only do
1269 * PFor (not PForDelta).
1270 */
1271
1272 /*
1273 * We use PForDelta not NewPForDelta nor OptPForDelta because "An
1274 * Experimental Study of Bitmap Compression vs. Inverted List
1275 * Compression"
1276 * https://www.cs.purdue.edu/homes/csjgwang/pubs/SIGMOD17-Bitmap.pdf
1277 * shows that PForDelta is faster than others. (They are smaller than
1278 * PForDelta.)
1279 *
1280 * We use PForDelta not Roaring bitmaps because PForDelta is faster
1281 * and smaller for posting list. And we need a cursor interface for
1282 * searching. Roaring bitmaps' intersection and union may be faster
1283 * but it's not a cursor interface. See also the above paper.
1284 */
1285
1286 #define UNIT_SIZE 0x80
1287 #define UNIT_MASK (UNIT_SIZE - 1)
1288
1289 /* clang-format off */
1290 /* <generated> */
1291 static uint8_t *
1292 pack_1(uint32_t *p, uint8_t *rp)
1293 {
1294 uint8_t v;
1295 v = *p++ << 7;
1296 v += *p++ << 6;
1297 v += *p++ << 5;
1298 v += *p++ << 4;
1299 v += *p++ << 3;
1300 v += *p++ << 2;
1301 v += *p++ << 1;
1302 *rp++ = v + *p++;
1303 return rp;
1304 }
1305 static const uint8_t *
1306 unpack_1(uint32_t *p, const uint8_t *dp)
1307 {
1308 *p++ = (*dp >> 7);
1309 *p++ = ((*dp >> 6) & 0x1);
1310 *p++ = ((*dp >> 5) & 0x1);
1311 *p++ = ((*dp >> 4) & 0x1);
1312 *p++ = ((*dp >> 3) & 0x1);
1313 *p++ = ((*dp >> 2) & 0x1);
1314 *p++ = ((*dp >> 1) & 0x1);
1315 *p++ = (*dp++ & 0x1);
1316 return dp;
1317 }
1318 static uint8_t *
1319 pack_2(uint32_t *p, uint8_t *rp)
1320 {
1321 uint8_t v;
1322 v = *p++ << 6;
1323 v += *p++ << 4;
1324 v += *p++ << 2;
1325 *rp++ = v + *p++;
1326 v = *p++ << 6;
1327 v += *p++ << 4;
1328 v += *p++ << 2;
1329 *rp++ = v + *p++;
1330 return rp;
1331 }
1332 static const uint8_t *
1333 unpack_2(uint32_t *p, const uint8_t *dp)
1334 {
1335 *p++ = (*dp >> 6);
1336 *p++ = ((*dp >> 4) & 0x3);
1337 *p++ = ((*dp >> 2) & 0x3);
1338 *p++ = (*dp++ & 0x3);
1339 *p++ = (*dp >> 6);
1340 *p++ = ((*dp >> 4) & 0x3);
1341 *p++ = ((*dp >> 2) & 0x3);
1342 *p++ = (*dp++ & 0x3);
1343 return dp;
1344 }
1345 static uint8_t *
1346 pack_3(uint32_t *p, uint8_t *rp)
1347 {
1348 uint8_t v;
1349 v = *p++ << 5;
1350 v += *p++ << 2;
1351 *rp++ = v + (*p >> 1); v = *p++ << 7;
1352 v += *p++ << 4;
1353 v += *p++ << 1;
1354 *rp++ = v + (*p >> 2); v = *p++ << 6;
1355 v += *p++ << 3;
1356 *rp++ = v + *p++;
1357 return rp;
1358 }
1359 static const uint8_t *
1360 unpack_3(uint32_t *p, const uint8_t *dp)
1361 {
1362 uint32_t v;
1363 *p++ = (*dp >> 5);
1364 *p++ = ((*dp >> 2) & 0x7);
1365 v = ((*dp++ << 1) & 0x7); *p++ = v + (*dp >> 7);
1366 *p++ = ((*dp >> 4) & 0x7);
1367 *p++ = ((*dp >> 1) & 0x7);
1368 v = ((*dp++ << 2) & 0x7); *p++ = v + (*dp >> 6);
1369 *p++ = ((*dp >> 3) & 0x7);
1370 *p++ = (*dp++ & 0x7);
1371 return dp;
1372 }
1373 static uint8_t *
1374 pack_4(uint32_t *p, uint8_t *rp)
1375 {
1376 uint8_t v;
1377 v = *p++ << 4;
1378 *rp++ = v + *p++;
1379 v = *p++ << 4;
1380 *rp++ = v + *p++;
1381 v = *p++ << 4;
1382 *rp++ = v + *p++;
1383 v = *p++ << 4;
1384 *rp++ = v + *p++;
1385 return rp;
1386 }
1387 static const uint8_t *
1388 unpack_4(uint32_t *p, const uint8_t *dp)
1389 {
1390 *p++ = (*dp >> 4);
1391 *p++ = (*dp++ & 0xf);
1392 *p++ = (*dp >> 4);
1393 *p++ = (*dp++ & 0xf);
1394 *p++ = (*dp >> 4);
1395 *p++ = (*dp++ & 0xf);
1396 *p++ = (*dp >> 4);
1397 *p++ = (*dp++ & 0xf);
1398 return dp;
1399 }
1400 static uint8_t *
1401 pack_5(uint32_t *p, uint8_t *rp)
1402 {
1403 uint8_t v;
1404 v = *p++ << 3;
1405 *rp++ = v + (*p >> 2); v = *p++ << 6;
1406 v += *p++ << 1;
1407 *rp++ = v + (*p >> 4); v = *p++ << 4;
1408 *rp++ = v + (*p >> 1); v = *p++ << 7;
1409 v += *p++ << 2;
1410 *rp++ = v + (*p >> 3); v = *p++ << 5;
1411 *rp++ = v + *p++;
1412 return rp;
1413 }
1414 static const uint8_t *
1415 unpack_5(uint32_t *p, const uint8_t *dp)
1416 {
1417 uint32_t v;
1418 *p++ = (*dp >> 3);
1419 v = ((*dp++ << 2) & 0x1f); *p++ = v + (*dp >> 6);
1420 *p++ = ((*dp >> 1) & 0x1f);
1421 v = ((*dp++ << 4) & 0x1f); *p++ = v + (*dp >> 4);
1422 v = ((*dp++ << 1) & 0x1f); *p++ = v + (*dp >> 7);
1423 *p++ = ((*dp >> 2) & 0x1f);
1424 v = ((*dp++ << 3) & 0x1f); *p++ = v + (*dp >> 5);
1425 *p++ = (*dp++ & 0x1f);
1426 return dp;
1427 }
1428 static uint8_t *
1429 pack_6(uint32_t *p, uint8_t *rp)
1430 {
1431 uint8_t v;
1432 v = *p++ << 2;
1433 *rp++ = v + (*p >> 4); v = *p++ << 4;
1434 *rp++ = v + (*p >> 2); v = *p++ << 6;
1435 *rp++ = v + *p++;
1436 v = *p++ << 2;
1437 *rp++ = v + (*p >> 4); v = *p++ << 4;
1438 *rp++ = v + (*p >> 2); v = *p++ << 6;
1439 *rp++ = v + *p++;
1440 return rp;
1441 }
1442 static const uint8_t *
1443 unpack_6(uint32_t *p, const uint8_t *dp)
1444 {
1445 uint32_t v;
1446 *p++ = (*dp >> 2);
1447 v = ((*dp++ << 4) & 0x3f); *p++ = v + (*dp >> 4);
1448 v = ((*dp++ << 2) & 0x3f); *p++ = v + (*dp >> 6);
1449 *p++ = (*dp++ & 0x3f);
1450 *p++ = (*dp >> 2);
1451 v = ((*dp++ << 4) & 0x3f); *p++ = v + (*dp >> 4);
1452 v = ((*dp++ << 2) & 0x3f); *p++ = v + (*dp >> 6);
1453 *p++ = (*dp++ & 0x3f);
1454 return dp;
1455 }
1456 static uint8_t *
1457 pack_7(uint32_t *p, uint8_t *rp)
1458 {
1459 uint8_t v;
1460 v = *p++ << 1;
1461 *rp++ = v + (*p >> 6); v = *p++ << 2;
1462 *rp++ = v + (*p >> 5); v = *p++ << 3;
1463 *rp++ = v + (*p >> 4); v = *p++ << 4;
1464 *rp++ = v + (*p >> 3); v = *p++ << 5;
1465 *rp++ = v + (*p >> 2); v = *p++ << 6;
1466 *rp++ = v + (*p >> 1); v = *p++ << 7;
1467 *rp++ = v + *p++;
1468 return rp;
1469 }
1470 static const uint8_t *
1471 unpack_7(uint32_t *p, const uint8_t *dp)
1472 {
1473 uint32_t v;
1474 *p++ = (*dp >> 1);
1475 v = ((*dp++ << 6) & 0x7f); *p++ = v + (*dp >> 2);
1476 v = ((*dp++ << 5) & 0x7f); *p++ = v + (*dp >> 3);
1477 v = ((*dp++ << 4) & 0x7f); *p++ = v + (*dp >> 4);
1478 v = ((*dp++ << 3) & 0x7f); *p++ = v + (*dp >> 5);
1479 v = ((*dp++ << 2) & 0x7f); *p++ = v + (*dp >> 6);
1480 v = ((*dp++ << 1) & 0x7f); *p++ = v + (*dp >> 7);
1481 *p++ = (*dp++ & 0x7f);
1482 return dp;
1483 }
1484 static uint8_t *
1485 pack_8(uint32_t *p, uint8_t *rp)
1486 {
1487 *rp++ = *p++;
1488 *rp++ = *p++;
1489 *rp++ = *p++;
1490 *rp++ = *p++;
1491 *rp++ = *p++;
1492 *rp++ = *p++;
1493 *rp++ = *p++;
1494 *rp++ = *p++;
1495 return rp;
1496 }
1497 static const uint8_t *
1498 unpack_8(uint32_t *p, const uint8_t *dp)
1499 {
1500 *p++ = *dp++;
1501 *p++ = *dp++;
1502 *p++ = *dp++;
1503 *p++ = *dp++;
1504 *p++ = *dp++;
1505 *p++ = *dp++;
1506 *p++ = *dp++;
1507 *p++ = *dp++;
1508 return dp;
1509 }
1510 static uint8_t *
1511 pack_9(uint32_t *p, uint8_t *rp)
1512 {
1513 uint8_t v;
1514 *rp++ = (*p >> 1); v = *p++ << 7;
1515 *rp++ = v + (*p >> 2); v = *p++ << 6;
1516 *rp++ = v + (*p >> 3); v = *p++ << 5;
1517 *rp++ = v + (*p >> 4); v = *p++ << 4;
1518 *rp++ = v + (*p >> 5); v = *p++ << 3;
1519 *rp++ = v + (*p >> 6); v = *p++ << 2;
1520 *rp++ = v + (*p >> 7); v = *p++ << 1;
1521 *rp++ = v + (*p >> 8); *rp++ = *p++;
1522 return rp;
1523 }
1524 static const uint8_t *
1525 unpack_9(uint32_t *p, const uint8_t *dp)
1526 {
1527 uint32_t v;
1528 v = *dp++ << 1; *p++ = v + (*dp >> 7);
1529 v = ((*dp++ << 2) & 0x1ff); *p++ = v + (*dp >> 6);
1530 v = ((*dp++ << 3) & 0x1ff); *p++ = v + (*dp >> 5);
1531 v = ((*dp++ << 4) & 0x1ff); *p++ = v + (*dp >> 4);
1532 v = ((*dp++ << 5) & 0x1ff); *p++ = v + (*dp >> 3);
1533 v = ((*dp++ << 6) & 0x1ff); *p++ = v + (*dp >> 2);
1534 v = ((*dp++ << 7) & 0x1ff); *p++ = v + (*dp >> 1);
1535 v = ((*dp++ << 8) & 0x1ff); *p++ = v + *dp++;
1536 return dp;
1537 }
1538 static uint8_t *
1539 pack_10(uint32_t *p, uint8_t *rp)
1540 {
1541 uint8_t v;
1542 *rp++ = (*p >> 2); v = *p++ << 6;
1543 *rp++ = v + (*p >> 4); v = *p++ << 4;
1544 *rp++ = v + (*p >> 6); v = *p++ << 2;
1545 *rp++ = v + (*p >> 8); *rp++ = *p++;
1546 *rp++ = (*p >> 2); v = *p++ << 6;
1547 *rp++ = v + (*p >> 4); v = *p++ << 4;
1548 *rp++ = v + (*p >> 6); v = *p++ << 2;
1549 *rp++ = v + (*p >> 8); *rp++ = *p++;
1550 return rp;
1551 }
1552 static const uint8_t *
1553 unpack_10(uint32_t *p, const uint8_t *dp)
1554 {
1555 uint32_t v;
1556 v = *dp++ << 2; *p++ = v + (*dp >> 6);
1557 v = ((*dp++ << 4) & 0x3ff); *p++ = v + (*dp >> 4);
1558 v = ((*dp++ << 6) & 0x3ff); *p++ = v + (*dp >> 2);
1559 v = ((*dp++ << 8) & 0x3ff); *p++ = v + *dp++;
1560 v = *dp++ << 2; *p++ = v + (*dp >> 6);
1561 v = ((*dp++ << 4) & 0x3ff); *p++ = v + (*dp >> 4);
1562 v = ((*dp++ << 6) & 0x3ff); *p++ = v + (*dp >> 2);
1563 v = ((*dp++ << 8) & 0x3ff); *p++ = v + *dp++;
1564 return dp;
1565 }
1566 static uint8_t *
1567 pack_11(uint32_t *p, uint8_t *rp)
1568 {
1569 uint8_t v;
1570 *rp++ = (*p >> 3); v = *p++ << 5;
1571 *rp++ = v + (*p >> 6); v = *p++ << 2;
1572 *rp++ = v + (*p >> 9); *rp++ = (*p >> 1); v = *p++ << 7;
1573 *rp++ = v + (*p >> 4); v = *p++ << 4;
1574 *rp++ = v + (*p >> 7); v = *p++ << 1;
1575 *rp++ = v + (*p >> 10); *rp++ = (*p >> 2); v = *p++ << 6;
1576 *rp++ = v + (*p >> 5); v = *p++ << 3;
1577 *rp++ = v + (*p >> 8); *rp++ = *p++;
1578 return rp;
1579 }
1580 static const uint8_t *
1581 unpack_11(uint32_t *p, const uint8_t *dp)
1582 {
1583 uint32_t v;
1584 v = *dp++ << 3; *p++ = v + (*dp >> 5);
1585 v = ((*dp++ << 6) & 0x7ff); *p++ = v + (*dp >> 2);
1586 v = ((*dp++ << 9) & 0x7ff); v += *dp++ << 1; *p++ = v + (*dp >> 7);
1587 v = ((*dp++ << 4) & 0x7ff); *p++ = v + (*dp >> 4);
1588 v = ((*dp++ << 7) & 0x7ff); *p++ = v + (*dp >> 1);
1589 v = ((*dp++ << 10) & 0x7ff); v += *dp++ << 2; *p++ = v + (*dp >> 6);
1590 v = ((*dp++ << 5) & 0x7ff); *p++ = v + (*dp >> 3);
1591 v = ((*dp++ << 8) & 0x7ff); *p++ = v + *dp++;
1592 return dp;
1593 }
1594 static uint8_t *
1595 pack_12(uint32_t *p, uint8_t *rp)
1596 {
1597 uint8_t v;
1598 *rp++ = (*p >> 4); v = *p++ << 4;
1599 *rp++ = v + (*p >> 8); *rp++ = *p++;
1600 *rp++ = (*p >> 4); v = *p++ << 4;
1601 *rp++ = v + (*p >> 8); *rp++ = *p++;
1602 *rp++ = (*p >> 4); v = *p++ << 4;
1603 *rp++ = v + (*p >> 8); *rp++ = *p++;
1604 *rp++ = (*p >> 4); v = *p++ << 4;
1605 *rp++ = v + (*p >> 8); *rp++ = *p++;
1606 return rp;
1607 }
1608 static const uint8_t *
1609 unpack_12(uint32_t *p, const uint8_t *dp)
1610 {
1611 uint32_t v;
1612 v = *dp++ << 4; *p++ = v + (*dp >> 4);
1613 v = ((*dp++ << 8) & 0xfff); *p++ = v + *dp++;
1614 v = *dp++ << 4; *p++ = v + (*dp >> 4);
1615 v = ((*dp++ << 8) & 0xfff); *p++ = v + *dp++;
1616 v = *dp++ << 4; *p++ = v + (*dp >> 4);
1617 v = ((*dp++ << 8) & 0xfff); *p++ = v + *dp++;
1618 v = *dp++ << 4; *p++ = v + (*dp >> 4);
1619 v = ((*dp++ << 8) & 0xfff); *p++ = v + *dp++;
1620 return dp;
1621 }
1622 static uint8_t *
1623 pack_13(uint32_t *p, uint8_t *rp)
1624 {
1625 uint8_t v;
1626 *rp++ = (*p >> 5); v = *p++ << 3;
1627 *rp++ = v + (*p >> 10); *rp++ = (*p >> 2); v = *p++ << 6;
1628 *rp++ = v + (*p >> 7); v = *p++ << 1;
1629 *rp++ = v + (*p >> 12); *rp++ = (*p >> 4); v = *p++ << 4;
1630 *rp++ = v + (*p >> 9); *rp++ = (*p >> 1); v = *p++ << 7;
1631 *rp++ = v + (*p >> 6); v = *p++ << 2;
1632 *rp++ = v + (*p >> 11); *rp++ = (*p >> 3); v = *p++ << 5;
1633 *rp++ = v + (*p >> 8); *rp++ = *p++;
1634 return rp;
1635 }
1636 static const uint8_t *
1637 unpack_13(uint32_t *p, const uint8_t *dp)
1638 {
1639 uint32_t v;
1640 v = *dp++ << 5; *p++ = v + (*dp >> 3);
1641 v = ((*dp++ << 10) & 0x1fff); v += *dp++ << 2; *p++ = v + (*dp >> 6);
1642 v = ((*dp++ << 7) & 0x1fff); *p++ = v + (*dp >> 1);
1643 v = ((*dp++ << 12) & 0x1fff); v += *dp++ << 4; *p++ = v + (*dp >> 4);
1644 v = ((*dp++ << 9) & 0x1fff); v += *dp++ << 1; *p++ = v + (*dp >> 7);
1645 v = ((*dp++ << 6) & 0x1fff); *p++ = v + (*dp >> 2);
1646 v = ((*dp++ << 11) & 0x1fff); v += *dp++ << 3; *p++ = v + (*dp >> 5);
1647 v = ((*dp++ << 8) & 0x1fff); *p++ = v + *dp++;
1648 return dp;
1649 }
1650 static uint8_t *
1651 pack_14(uint32_t *p, uint8_t *rp)
1652 {
1653 uint8_t v;
1654 *rp++ = (*p >> 6); v = *p++ << 2;
1655 *rp++ = v + (*p >> 12); *rp++ = (*p >> 4); v = *p++ << 4;
1656 *rp++ = v + (*p >> 10); *rp++ = (*p >> 2); v = *p++ << 6;
1657 *rp++ = v + (*p >> 8); *rp++ = *p++;
1658 *rp++ = (*p >> 6); v = *p++ << 2;
1659 *rp++ = v + (*p >> 12); *rp++ = (*p >> 4); v = *p++ << 4;
1660 *rp++ = v + (*p >> 10); *rp++ = (*p >> 2); v = *p++ << 6;
1661 *rp++ = v + (*p >> 8); *rp++ = *p++;
1662 return rp;
1663 }
1664 static const uint8_t *
1665 unpack_14(uint32_t *p, const uint8_t *dp)
1666 {
1667 uint32_t v;
1668 v = *dp++ << 6; *p++ = v + (*dp >> 2);
1669 v = ((*dp++ << 12) & 0x3fff); v += *dp++ << 4; *p++ = v + (*dp >> 4);
1670 v = ((*dp++ << 10) & 0x3fff); v += *dp++ << 2; *p++ = v + (*dp >> 6);
1671 v = ((*dp++ << 8) & 0x3fff); *p++ = v + *dp++;
1672 v = *dp++ << 6; *p++ = v + (*dp >> 2);
1673 v = ((*dp++ << 12) & 0x3fff); v += *dp++ << 4; *p++ = v + (*dp >> 4);
1674 v = ((*dp++ << 10) & 0x3fff); v += *dp++ << 2; *p++ = v + (*dp >> 6);
1675 v = ((*dp++ << 8) & 0x3fff); *p++ = v + *dp++;
1676 return dp;
1677 }
1678 static uint8_t *
1679 pack_15(uint32_t *p, uint8_t *rp)
1680 {
1681 uint8_t v;
1682 *rp++ = (*p >> 7); v = *p++ << 1;
1683 *rp++ = v + (*p >> 14); *rp++ = (*p >> 6); v = *p++ << 2;
1684 *rp++ = v + (*p >> 13); *rp++ = (*p >> 5); v = *p++ << 3;
1685 *rp++ = v + (*p >> 12); *rp++ = (*p >> 4); v = *p++ << 4;
1686 *rp++ = v + (*p >> 11); *rp++ = (*p >> 3); v = *p++ << 5;
1687 *rp++ = v + (*p >> 10); *rp++ = (*p >> 2); v = *p++ << 6;
1688 *rp++ = v + (*p >> 9); *rp++ = (*p >> 1); v = *p++ << 7;
1689 *rp++ = v + (*p >> 8); *rp++ = *p++;
1690 return rp;
1691 }
1692 static const uint8_t *
1693 unpack_15(uint32_t *p, const uint8_t *dp)
1694 {
1695 uint32_t v;
1696 v = *dp++ << 7; *p++ = v + (*dp >> 1);
1697 v = ((*dp++ << 14) & 0x7fff); v += *dp++ << 6; *p++ = v + (*dp >> 2);
1698 v = ((*dp++ << 13) & 0x7fff); v += *dp++ << 5; *p++ = v + (*dp >> 3);
1699 v = ((*dp++ << 12) & 0x7fff); v += *dp++ << 4; *p++ = v + (*dp >> 4);
1700 v = ((*dp++ << 11) & 0x7fff); v += *dp++ << 3; *p++ = v + (*dp >> 5);
1701 v = ((*dp++ << 10) & 0x7fff); v += *dp++ << 2; *p++ = v + (*dp >> 6);
1702 v = ((*dp++ << 9) & 0x7fff); v += *dp++ << 1; *p++ = v + (*dp >> 7);
1703 v = ((*dp++ << 8) & 0x7fff); *p++ = v + *dp++;
1704 return dp;
1705 }
1706 static uint8_t *
1707 pack_16(uint32_t *p, uint8_t *rp)
1708 {
1709 *rp++ = (*p >> 8); *rp++ = *p++;
1710 *rp++ = (*p >> 8); *rp++ = *p++;
1711 *rp++ = (*p >> 8); *rp++ = *p++;
1712 *rp++ = (*p >> 8); *rp++ = *p++;
1713 *rp++ = (*p >> 8); *rp++ = *p++;
1714 *rp++ = (*p >> 8); *rp++ = *p++;
1715 *rp++ = (*p >> 8); *rp++ = *p++;
1716 *rp++ = (*p >> 8); *rp++ = *p++;
1717 return rp;
1718 }
1719 static const uint8_t *
1720 unpack_16(uint32_t *p, const uint8_t *dp)
1721 {
1722 uint32_t v;
1723 v = *dp++ << 8; *p++ = v + *dp++;
1724 v = *dp++ << 8; *p++ = v + *dp++;
1725 v = *dp++ << 8; *p++ = v + *dp++;
1726 v = *dp++ << 8; *p++ = v + *dp++;
1727 v = *dp++ << 8; *p++ = v + *dp++;
1728 v = *dp++ << 8; *p++ = v + *dp++;
1729 v = *dp++ << 8; *p++ = v + *dp++;
1730 v = *dp++ << 8; *p++ = v + *dp++;
1731 return dp;
1732 }
1733 static uint8_t *
1734 pack_17(uint32_t *p, uint8_t *rp)
1735 {
1736 uint8_t v;
1737 *rp++ = (*p >> 9); *rp++ = (*p >> 1); v = *p++ << 7;
1738 *rp++ = v + (*p >> 10); *rp++ = (*p >> 2); v = *p++ << 6;
1739 *rp++ = v + (*p >> 11); *rp++ = (*p >> 3); v = *p++ << 5;
1740 *rp++ = v + (*p >> 12); *rp++ = (*p >> 4); v = *p++ << 4;
1741 *rp++ = v + (*p >> 13); *rp++ = (*p >> 5); v = *p++ << 3;
1742 *rp++ = v + (*p >> 14); *rp++ = (*p >> 6); v = *p++ << 2;
1743 *rp++ = v + (*p >> 15); *rp++ = (*p >> 7); v = *p++ << 1;
1744 *rp++ = v + (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
1745 return rp;
1746 }
1747 static const uint8_t *
1748 unpack_17(uint32_t *p, const uint8_t *dp)
1749 {
1750 uint32_t v;
1751 v = *dp++ << 9; v += *dp++ << 1; *p++ = v + (*dp >> 7);
1752 v = ((*dp++ << 10) & 0x1ffff); v += *dp++ << 2; *p++ = v + (*dp >> 6);
1753 v = ((*dp++ << 11) & 0x1ffff); v += *dp++ << 3; *p++ = v + (*dp >> 5);
1754 v = ((*dp++ << 12) & 0x1ffff); v += *dp++ << 4; *p++ = v + (*dp >> 4);
1755 v = ((*dp++ << 13) & 0x1ffff); v += *dp++ << 5; *p++ = v + (*dp >> 3);
1756 v = ((*dp++ << 14) & 0x1ffff); v += *dp++ << 6; *p++ = v + (*dp >> 2);
1757 v = ((*dp++ << 15) & 0x1ffff); v += *dp++ << 7; *p++ = v + (*dp >> 1);
1758 v = ((*dp++ << 16) & 0x1ffff); v += *dp++ << 8; *p++ = v + *dp++;
1759 return dp;
1760 }
1761 static uint8_t *
1762 pack_18(uint32_t *p, uint8_t *rp)
1763 {
1764 uint8_t v;
1765 *rp++ = (*p >> 10); *rp++ = (*p >> 2); v = *p++ << 6;
1766 *rp++ = v + (*p >> 12); *rp++ = (*p >> 4); v = *p++ << 4;
1767 *rp++ = v + (*p >> 14); *rp++ = (*p >> 6); v = *p++ << 2;
1768 *rp++ = v + (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
1769 *rp++ = (*p >> 10); *rp++ = (*p >> 2); v = *p++ << 6;
1770 *rp++ = v + (*p >> 12); *rp++ = (*p >> 4); v = *p++ << 4;
1771 *rp++ = v + (*p >> 14); *rp++ = (*p >> 6); v = *p++ << 2;
1772 *rp++ = v + (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
1773 return rp;
1774 }
1775 static const uint8_t *
1776 unpack_18(uint32_t *p, const uint8_t *dp)
1777 {
1778 uint32_t v;
1779 v = *dp++ << 10; v += *dp++ << 2; *p++ = v + (*dp >> 6);
1780 v = ((*dp++ << 12) & 0x3ffff); v += *dp++ << 4; *p++ = v + (*dp >> 4);
1781 v = ((*dp++ << 14) & 0x3ffff); v += *dp++ << 6; *p++ = v + (*dp >> 2);
1782 v = ((*dp++ << 16) & 0x3ffff); v += *dp++ << 8; *p++ = v + *dp++;
1783 v = *dp++ << 10; v += *dp++ << 2; *p++ = v + (*dp >> 6);
1784 v = ((*dp++ << 12) & 0x3ffff); v += *dp++ << 4; *p++ = v + (*dp >> 4);
1785 v = ((*dp++ << 14) & 0x3ffff); v += *dp++ << 6; *p++ = v + (*dp >> 2);
1786 v = ((*dp++ << 16) & 0x3ffff); v += *dp++ << 8; *p++ = v + *dp++;
1787 return dp;
1788 }
1789 static uint8_t *
1790 pack_19(uint32_t *p, uint8_t *rp)
1791 {
1792 uint8_t v;
1793 *rp++ = (*p >> 11); *rp++ = (*p >> 3); v = *p++ << 5;
1794 *rp++ = v + (*p >> 14); *rp++ = (*p >> 6); v = *p++ << 2;
1795 *rp++ = v + (*p >> 17); *rp++ = (*p >> 9); *rp++ = (*p >> 1); v = *p++ << 7;
1796 *rp++ = v + (*p >> 12); *rp++ = (*p >> 4); v = *p++ << 4;
1797 *rp++ = v + (*p >> 15); *rp++ = (*p >> 7); v = *p++ << 1;
1798 *rp++ = v + (*p >> 18); *rp++ = (*p >> 10); *rp++ = (*p >> 2); v = *p++ << 6;
1799 *rp++ = v + (*p >> 13); *rp++ = (*p >> 5); v = *p++ << 3;
1800 *rp++ = v + (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
1801 return rp;
1802 }
1803 static const uint8_t *
1804 unpack_19(uint32_t *p, const uint8_t *dp)
1805 {
1806 uint32_t v;
1807 v = *dp++ << 11; v += *dp++ << 3; *p++ = v + (*dp >> 5);
1808 v = ((*dp++ << 14) & 0x7ffff); v += *dp++ << 6; *p++ = v + (*dp >> 2);
1809 v = ((*dp++ << 17) & 0x7ffff); v += *dp++ << 9; v += *dp++ << 1;
1810 *p++ = v + (*dp >> 7);
1811 v = ((*dp++ << 12) & 0x7ffff); v += *dp++ << 4; *p++ = v + (*dp >> 4);
1812 v = ((*dp++ << 15) & 0x7ffff); v += *dp++ << 7; *p++ = v + (*dp >> 1);
1813 v = ((*dp++ << 18) & 0x7ffff); v += *dp++ << 10; v += *dp++ << 2;
1814 *p++ = v + (*dp >> 6);
1815 v = ((*dp++ << 13) & 0x7ffff); v += *dp++ << 5; *p++ = v + (*dp >> 3);
1816 v = ((*dp++ << 16) & 0x7ffff); v += *dp++ << 8; *p++ = v + *dp++;
1817 return dp;
1818 }
1819 static uint8_t *
1820 pack_20(uint32_t *p, uint8_t *rp)
1821 {
1822 uint8_t v;
1823 *rp++ = (*p >> 12); *rp++ = (*p >> 4); v = *p++ << 4;
1824 *rp++ = v + (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
1825 *rp++ = (*p >> 12); *rp++ = (*p >> 4); v = *p++ << 4;
1826 *rp++ = v + (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
1827 *rp++ = (*p >> 12); *rp++ = (*p >> 4); v = *p++ << 4;
1828 *rp++ = v + (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
1829 *rp++ = (*p >> 12); *rp++ = (*p >> 4); v = *p++ << 4;
1830 *rp++ = v + (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
1831 return rp;
1832 }
1833 static const uint8_t *
1834 unpack_20(uint32_t *p, const uint8_t *dp)
1835 {
1836 uint32_t v;
1837 v = *dp++ << 12; v += *dp++ << 4; *p++ = v + (*dp >> 4);
1838 v = ((*dp++ << 16) & 0xfffff); v += *dp++ << 8; *p++ = v + *dp++;
1839 v = *dp++ << 12; v += *dp++ << 4; *p++ = v + (*dp >> 4);
1840 v = ((*dp++ << 16) & 0xfffff); v += *dp++ << 8; *p++ = v + *dp++;
1841 v = *dp++ << 12; v += *dp++ << 4; *p++ = v + (*dp >> 4);
1842 v = ((*dp++ << 16) & 0xfffff); v += *dp++ << 8; *p++ = v + *dp++;
1843 v = *dp++ << 12; v += *dp++ << 4; *p++ = v + (*dp >> 4);
1844 v = ((*dp++ << 16) & 0xfffff); v += *dp++ << 8; *p++ = v + *dp++;
1845 return dp;
1846 }
1847 static uint8_t *
1848 pack_21(uint32_t *p, uint8_t *rp)
1849 {
1850 uint8_t v;
1851 *rp++ = (*p >> 13); *rp++ = (*p >> 5); v = *p++ << 3;
1852 *rp++ = v + (*p >> 18); *rp++ = (*p >> 10); *rp++ = (*p >> 2); v = *p++ << 6;
1853 *rp++ = v + (*p >> 15); *rp++ = (*p >> 7); v = *p++ << 1;
1854 *rp++ = v + (*p >> 20); *rp++ = (*p >> 12); *rp++ = (*p >> 4); v = *p++ << 4;
1855 *rp++ = v + (*p >> 17); *rp++ = (*p >> 9); *rp++ = (*p >> 1); v = *p++ << 7;
1856 *rp++ = v + (*p >> 14); *rp++ = (*p >> 6); v = *p++ << 2;
1857 *rp++ = v + (*p >> 19); *rp++ = (*p >> 11); *rp++ = (*p >> 3); v = *p++ << 5;
1858 *rp++ = v + (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
1859 return rp;
1860 }
1861 static const uint8_t *
1862 unpack_21(uint32_t *p, const uint8_t *dp)
1863 {
1864 uint32_t v;
1865 v = *dp++ << 13; v += *dp++ << 5; *p++ = v + (*dp >> 3);
1866 v = ((*dp++ << 18) & 0x1fffff); v += *dp++ << 10; v += *dp++ << 2;
1867 *p++ = v + (*dp >> 6);
1868 v = ((*dp++ << 15) & 0x1fffff); v += *dp++ << 7; *p++ = v + (*dp >> 1);
1869 v = ((*dp++ << 20) & 0x1fffff); v += *dp++ << 12; v += *dp++ << 4;
1870 *p++ = v + (*dp >> 4);
1871 v = ((*dp++ << 17) & 0x1fffff); v += *dp++ << 9; v += *dp++ << 1;
1872 *p++ = v + (*dp >> 7);
1873 v = ((*dp++ << 14) & 0x1fffff); v += *dp++ << 6; *p++ = v + (*dp >> 2);
1874 v = ((*dp++ << 19) & 0x1fffff); v += *dp++ << 11; v += *dp++ << 3;
1875 *p++ = v + (*dp >> 5);
1876 v = ((*dp++ << 16) & 0x1fffff); v += *dp++ << 8; *p++ = v + *dp++;
1877 return dp;
1878 }
1879 static uint8_t *
1880 pack_22(uint32_t *p, uint8_t *rp)
1881 {
1882 uint8_t v;
1883 *rp++ = (*p >> 14); *rp++ = (*p >> 6); v = *p++ << 2;
1884 *rp++ = v + (*p >> 20); *rp++ = (*p >> 12); *rp++ = (*p >> 4); v = *p++ << 4;
1885 *rp++ = v + (*p >> 18); *rp++ = (*p >> 10); *rp++ = (*p >> 2); v = *p++ << 6;
1886 *rp++ = v + (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
1887 *rp++ = (*p >> 14); *rp++ = (*p >> 6); v = *p++ << 2;
1888 *rp++ = v + (*p >> 20); *rp++ = (*p >> 12); *rp++ = (*p >> 4); v = *p++ << 4;
1889 *rp++ = v + (*p >> 18); *rp++ = (*p >> 10); *rp++ = (*p >> 2); v = *p++ << 6;
1890 *rp++ = v + (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
1891 return rp;
1892 }
1893 static const uint8_t *
1894 unpack_22(uint32_t *p, const uint8_t *dp)
1895 {
1896 uint32_t v;
1897 v = *dp++ << 14; v += *dp++ << 6; *p++ = v + (*dp >> 2);
1898 v = ((*dp++ << 20) & 0x3fffff); v += *dp++ << 12; v += *dp++ << 4;
1899 *p++ = v + (*dp >> 4);
1900 v = ((*dp++ << 18) & 0x3fffff); v += *dp++ << 10; v += *dp++ << 2;
1901 *p++ = v + (*dp >> 6);
1902 v = ((*dp++ << 16) & 0x3fffff); v += *dp++ << 8; *p++ = v + *dp++;
1903 v = *dp++ << 14; v += *dp++ << 6; *p++ = v + (*dp >> 2);
1904 v = ((*dp++ << 20) & 0x3fffff); v += *dp++ << 12; v += *dp++ << 4;
1905 *p++ = v + (*dp >> 4);
1906 v = ((*dp++ << 18) & 0x3fffff); v += *dp++ << 10; v += *dp++ << 2;
1907 *p++ = v + (*dp >> 6);
1908 v = ((*dp++ << 16) & 0x3fffff); v += *dp++ << 8; *p++ = v + *dp++;
1909 return dp;
1910 }
1911 static uint8_t *
1912 pack_23(uint32_t *p, uint8_t *rp)
1913 {
1914 uint8_t v;
1915 *rp++ = (*p >> 15); *rp++ = (*p >> 7); v = *p++ << 1;
1916 *rp++ = v + (*p >> 22); *rp++ = (*p >> 14); *rp++ = (*p >> 6); v = *p++ << 2;
1917 *rp++ = v + (*p >> 21); *rp++ = (*p >> 13); *rp++ = (*p >> 5); v = *p++ << 3;
1918 *rp++ = v + (*p >> 20); *rp++ = (*p >> 12); *rp++ = (*p >> 4); v = *p++ << 4;
1919 *rp++ = v + (*p >> 19); *rp++ = (*p >> 11); *rp++ = (*p >> 3); v = *p++ << 5;
1920 *rp++ = v + (*p >> 18); *rp++ = (*p >> 10); *rp++ = (*p >> 2); v = *p++ << 6;
1921 *rp++ = v + (*p >> 17); *rp++ = (*p >> 9); *rp++ = (*p >> 1); v = *p++ << 7;
1922 *rp++ = v + (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
1923 return rp;
1924 }
1925 static const uint8_t *
1926 unpack_23(uint32_t *p, const uint8_t *dp)
1927 {
1928 uint32_t v;
1929 v = *dp++ << 15; v += *dp++ << 7; *p++ = v + (*dp >> 1);
1930 v = ((*dp++ << 22) & 0x7fffff); v += *dp++ << 14; v += *dp++ << 6;
1931 *p++ = v + (*dp >> 2);
1932 v = ((*dp++ << 21) & 0x7fffff); v += *dp++ << 13; v += *dp++ << 5;
1933 *p++ = v + (*dp >> 3);
1934 v = ((*dp++ << 20) & 0x7fffff); v += *dp++ << 12; v += *dp++ << 4;
1935 *p++ = v + (*dp >> 4);
1936 v = ((*dp++ << 19) & 0x7fffff); v += *dp++ << 11; v += *dp++ << 3;
1937 *p++ = v + (*dp >> 5);
1938 v = ((*dp++ << 18) & 0x7fffff); v += *dp++ << 10; v += *dp++ << 2;
1939 *p++ = v + (*dp >> 6);
1940 v = ((*dp++ << 17) & 0x7fffff); v += *dp++ << 9; v += *dp++ << 1;
1941 *p++ = v + (*dp >> 7);
1942 v = ((*dp++ << 16) & 0x7fffff); v += *dp++ << 8; *p++ = v + *dp++;
1943 return dp;
1944 }
1945 static uint8_t *
1946 pack_24(uint32_t *p, uint8_t *rp)
1947 {
1948 *rp++ = (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
1949 *rp++ = (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
1950 *rp++ = (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
1951 *rp++ = (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
1952 *rp++ = (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
1953 *rp++ = (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
1954 *rp++ = (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
1955 *rp++ = (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
1956 return rp;
1957 }
1958 static const uint8_t *
1959 unpack_24(uint32_t *p, const uint8_t *dp)
1960 {
1961 uint32_t v;
1962 v = *dp++ << 16; v += *dp++ << 8; *p++ = v + *dp++;
1963 v = *dp++ << 16; v += *dp++ << 8; *p++ = v + *dp++;
1964 v = *dp++ << 16; v += *dp++ << 8; *p++ = v + *dp++;
1965 v = *dp++ << 16; v += *dp++ << 8; *p++ = v + *dp++;
1966 v = *dp++ << 16; v += *dp++ << 8; *p++ = v + *dp++;
1967 v = *dp++ << 16; v += *dp++ << 8; *p++ = v + *dp++;
1968 v = *dp++ << 16; v += *dp++ << 8; *p++ = v + *dp++;
1969 v = *dp++ << 16; v += *dp++ << 8; *p++ = v + *dp++;
1970 return dp;
1971 }
1972 static uint8_t *
1973 pack_25(uint32_t *p, uint8_t *rp)
1974 {
1975 uint8_t v;
1976 *rp++ = (*p >> 17); *rp++ = (*p >> 9); *rp++ = (*p >> 1); v = *p++ << 7;
1977 *rp++ = v + (*p >> 18); *rp++ = (*p >> 10); *rp++ = (*p >> 2); v = *p++ << 6;
1978 *rp++ = v + (*p >> 19); *rp++ = (*p >> 11); *rp++ = (*p >> 3); v = *p++ << 5;
1979 *rp++ = v + (*p >> 20); *rp++ = (*p >> 12); *rp++ = (*p >> 4); v = *p++ << 4;
1980 *rp++ = v + (*p >> 21); *rp++ = (*p >> 13); *rp++ = (*p >> 5); v = *p++ << 3;
1981 *rp++ = v + (*p >> 22); *rp++ = (*p >> 14); *rp++ = (*p >> 6); v = *p++ << 2;
1982 *rp++ = v + (*p >> 23); *rp++ = (*p >> 15); *rp++ = (*p >> 7); v = *p++ << 1;
1983 *rp++ = v + (*p >> 24); *rp++ = (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
1984 return rp;
1985 }
1986 static const uint8_t *
1987 unpack_25(uint32_t *p, const uint8_t *dp)
1988 {
1989 uint32_t v;
1990 v = *dp++ << 17; v += *dp++ << 9; v += *dp++ << 1; *p++ = v + (*dp >> 7);
1991 v = ((*dp++ << 18) & 0x1ffffff); v += *dp++ << 10; v += *dp++ << 2;
1992 *p++ = v + (*dp >> 6);
1993 v = ((*dp++ << 19) & 0x1ffffff); v += *dp++ << 11; v += *dp++ << 3;
1994 *p++ = v + (*dp >> 5);
1995 v = ((*dp++ << 20) & 0x1ffffff); v += *dp++ << 12; v += *dp++ << 4;
1996 *p++ = v + (*dp >> 4);
1997 v = ((*dp++ << 21) & 0x1ffffff); v += *dp++ << 13; v += *dp++ << 5;
1998 *p++ = v + (*dp >> 3);
1999 v = ((*dp++ << 22) & 0x1ffffff); v += *dp++ << 14; v += *dp++ << 6;
2000 *p++ = v + (*dp >> 2);
2001 v = ((*dp++ << 23) & 0x1ffffff); v += *dp++ << 15; v += *dp++ << 7;
2002 *p++ = v + (*dp >> 1);
2003 v = ((*dp++ << 24) & 0x1ffffff); v += *dp++ << 16; v += *dp++ << 8;
2004 *p++ = v + *dp++;
2005 return dp;
2006 }
2007 static uint8_t *
2008 pack_26(uint32_t *p, uint8_t *rp)
2009 {
2010 uint8_t v;
2011 *rp++ = (*p >> 18); *rp++ = (*p >> 10); *rp++ = (*p >> 2); v = *p++ << 6;
2012 *rp++ = v + (*p >> 20); *rp++ = (*p >> 12); *rp++ = (*p >> 4); v = *p++ << 4;
2013 *rp++ = v + (*p >> 22); *rp++ = (*p >> 14); *rp++ = (*p >> 6); v = *p++ << 2;
2014 *rp++ = v + (*p >> 24); *rp++ = (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
2015 *rp++ = (*p >> 18); *rp++ = (*p >> 10); *rp++ = (*p >> 2); v = *p++ << 6;
2016 *rp++ = v + (*p >> 20); *rp++ = (*p >> 12); *rp++ = (*p >> 4); v = *p++ << 4;
2017 *rp++ = v + (*p >> 22); *rp++ = (*p >> 14); *rp++ = (*p >> 6); v = *p++ << 2;
2018 *rp++ = v + (*p >> 24); *rp++ = (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
2019 return rp;
2020 }
2021 static const uint8_t *
2022 unpack_26(uint32_t *p, const uint8_t *dp)
2023 {
2024 uint32_t v;
2025 v = *dp++ << 18; v += *dp++ << 10; v += *dp++ << 2; *p++ = v + (*dp >> 6);
2026 v = ((*dp++ << 20) & 0x3ffffff); v += *dp++ << 12; v += *dp++ << 4;
2027 *p++ = v + (*dp >> 4);
2028 v = ((*dp++ << 22) & 0x3ffffff); v += *dp++ << 14; v += *dp++ << 6;
2029 *p++ = v + (*dp >> 2);
2030 v = ((*dp++ << 24) & 0x3ffffff); v += *dp++ << 16; v += *dp++ << 8;
2031 *p++ = v + *dp++;
2032 v = *dp++ << 18; v += *dp++ << 10; v += *dp++ << 2; *p++ = v + (*dp >> 6);
2033 v = ((*dp++ << 20) & 0x3ffffff); v += *dp++ << 12; v += *dp++ << 4;
2034 *p++ = v + (*dp >> 4);
2035 v = ((*dp++ << 22) & 0x3ffffff); v += *dp++ << 14; v += *dp++ << 6;
2036 *p++ = v + (*dp >> 2);
2037 v = ((*dp++ << 24) & 0x3ffffff); v += *dp++ << 16; v += *dp++ << 8;
2038 *p++ = v + *dp++;
2039 return dp;
2040 }
2041 static uint8_t *
2042 pack_27(uint32_t *p, uint8_t *rp)
2043 {
2044 uint8_t v;
2045 *rp++ = (*p >> 19); *rp++ = (*p >> 11); *rp++ = (*p >> 3); v = *p++ << 5;
2046 *rp++ = v + (*p >> 22); *rp++ = (*p >> 14); *rp++ = (*p >> 6); v = *p++ << 2;
2047 *rp++ = v + (*p >> 25); *rp++ = (*p >> 17); *rp++ = (*p >> 9);
2048 *rp++ = (*p >> 1); v = *p++ << 7;
2049 *rp++ = v + (*p >> 20); *rp++ = (*p >> 12); *rp++ = (*p >> 4); v = *p++ << 4;
2050 *rp++ = v + (*p >> 23); *rp++ = (*p >> 15); *rp++ = (*p >> 7); v = *p++ << 1;
2051 *rp++ = v + (*p >> 26); *rp++ = (*p >> 18); *rp++ = (*p >> 10);
2052 *rp++ = (*p >> 2); v = *p++ << 6;
2053 *rp++ = v + (*p >> 21); *rp++ = (*p >> 13); *rp++ = (*p >> 5); v = *p++ << 3;
2054 *rp++ = v + (*p >> 24); *rp++ = (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
2055 return rp;
2056 }
2057 static const uint8_t *
2058 unpack_27(uint32_t *p, const uint8_t *dp)
2059 {
2060 uint32_t v;
2061 v = *dp++ << 19; v += *dp++ << 11; v += *dp++ << 3; *p++ = v + (*dp >> 5);
2062 v = ((*dp++ << 22) & 0x7ffffff); v += *dp++ << 14; v += *dp++ << 6;
2063 *p++ = v + (*dp >> 2);
2064 v = ((*dp++ << 25) & 0x7ffffff); v += *dp++ << 17; v += *dp++ << 9;
2065 v += *dp++ << 1; *p++ = v + (*dp >> 7);
2066 v = ((*dp++ << 20) & 0x7ffffff); v += *dp++ << 12; v += *dp++ << 4;
2067 *p++ = v + (*dp >> 4);
2068 v = ((*dp++ << 23) & 0x7ffffff); v += *dp++ << 15; v += *dp++ << 7;
2069 *p++ = v + (*dp >> 1);
2070 v = ((*dp++ << 26) & 0x7ffffff); v += *dp++ << 18; v += *dp++ << 10;
2071 v += *dp++ << 2; *p++ = v + (*dp >> 6);
2072 v = ((*dp++ << 21) & 0x7ffffff); v += *dp++ << 13; v += *dp++ << 5;
2073 *p++ = v + (*dp >> 3);
2074 v = ((*dp++ << 24) & 0x7ffffff); v += *dp++ << 16; v += *dp++ << 8;
2075 *p++ = v + *dp++;
2076 return dp;
2077 }
2078 static uint8_t *
2079 pack_28(uint32_t *p, uint8_t *rp)
2080 {
2081 uint8_t v;
2082 *rp++ = (*p >> 20); *rp++ = (*p >> 12); *rp++ = (*p >> 4); v = *p++ << 4;
2083 *rp++ = v + (*p >> 24); *rp++ = (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
2084 *rp++ = (*p >> 20); *rp++ = (*p >> 12); *rp++ = (*p >> 4); v = *p++ << 4;
2085 *rp++ = v + (*p >> 24); *rp++ = (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
2086 *rp++ = (*p >> 20); *rp++ = (*p >> 12); *rp++ = (*p >> 4); v = *p++ << 4;
2087 *rp++ = v + (*p >> 24); *rp++ = (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
2088 *rp++ = (*p >> 20); *rp++ = (*p >> 12); *rp++ = (*p >> 4); v = *p++ << 4;
2089 *rp++ = v + (*p >> 24); *rp++ = (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
2090 return rp;
2091 }
2092 static const uint8_t *
2093 unpack_28(uint32_t *p, const uint8_t *dp)
2094 {
2095 uint32_t v;
2096 v = *dp++ << 20; v += *dp++ << 12; v += *dp++ << 4; *p++ = v + (*dp >> 4);
2097 v = ((*dp++ << 24) & 0xfffffff); v += *dp++ << 16; v += *dp++ << 8;
2098 *p++ = v + *dp++;
2099 v = *dp++ << 20; v += *dp++ << 12; v += *dp++ << 4; *p++ = v + (*dp >> 4);
2100 v = ((*dp++ << 24) & 0xfffffff); v += *dp++ << 16; v += *dp++ << 8;
2101 *p++ = v + *dp++;
2102 v = *dp++ << 20; v += *dp++ << 12; v += *dp++ << 4; *p++ = v + (*dp >> 4);
2103 v = ((*dp++ << 24) & 0xfffffff); v += *dp++ << 16; v += *dp++ << 8;
2104 *p++ = v + *dp++;
2105 v = *dp++ << 20; v += *dp++ << 12; v += *dp++ << 4; *p++ = v + (*dp >> 4);
2106 v = ((*dp++ << 24) & 0xfffffff); v += *dp++ << 16; v += *dp++ << 8;
2107 *p++ = v + *dp++;
2108 return dp;
2109 }
2110 static uint8_t *
2111 pack_29(uint32_t *p, uint8_t *rp)
2112 {
2113 uint8_t v;
2114 *rp++ = (*p >> 21); *rp++ = (*p >> 13); *rp++ = (*p >> 5); v = *p++ << 3;
2115 *rp++ = v + (*p >> 26); *rp++ = (*p >> 18); *rp++ = (*p >> 10);
2116 *rp++ = (*p >> 2); v = *p++ << 6;
2117 *rp++ = v + (*p >> 23); *rp++ = (*p >> 15); *rp++ = (*p >> 7); v = *p++ << 1;
2118 *rp++ = v + (*p >> 28); *rp++ = (*p >> 20); *rp++ = (*p >> 12);
2119 *rp++ = (*p >> 4); v = *p++ << 4;
2120 *rp++ = v + (*p >> 25); *rp++ = (*p >> 17); *rp++ = (*p >> 9);
2121 *rp++ = (*p >> 1); v = *p++ << 7;
2122 *rp++ = v + (*p >> 22); *rp++ = (*p >> 14); *rp++ = (*p >> 6); v = *p++ << 2;
2123 *rp++ = v + (*p >> 27); *rp++ = (*p >> 19); *rp++ = (*p >> 11);
2124 *rp++ = (*p >> 3); v = *p++ << 5;
2125 *rp++ = v + (*p >> 24); *rp++ = (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
2126 return rp;
2127 }
2128 static const uint8_t *
2129 unpack_29(uint32_t *p, const uint8_t *dp)
2130 {
2131 uint32_t v;
2132 v = *dp++ << 21; v += *dp++ << 13; v += *dp++ << 5; *p++ = v + (*dp >> 3);
2133 v = ((*dp++ << 26) & 0x1fffffff); v += *dp++ << 18; v += *dp++ << 10;
2134 v += *dp++ << 2; *p++ = v + (*dp >> 6);
2135 v = ((*dp++ << 23) & 0x1fffffff); v += *dp++ << 15; v += *dp++ << 7;
2136 *p++ = v + (*dp >> 1);
2137 v = ((*dp++ << 28) & 0x1fffffff); v += *dp++ << 20; v += *dp++ << 12;
2138 v += *dp++ << 4; *p++ = v + (*dp >> 4);
2139 v = ((*dp++ << 25) & 0x1fffffff); v += *dp++ << 17; v += *dp++ << 9;
2140 v += *dp++ << 1; *p++ = v + (*dp >> 7);
2141 v = ((*dp++ << 22) & 0x1fffffff); v += *dp++ << 14; v += *dp++ << 6;
2142 *p++ = v + (*dp >> 2);
2143 v = ((*dp++ << 27) & 0x1fffffff); v += *dp++ << 19; v += *dp++ << 11;
2144 v += *dp++ << 3; *p++ = v + (*dp >> 5);
2145 v = ((*dp++ << 24) & 0x1fffffff); v += *dp++ << 16; v += *dp++ << 8;
2146 *p++ = v + *dp++;
2147 return dp;
2148 }
2149 static uint8_t *
2150 pack_30(uint32_t *p, uint8_t *rp)
2151 {
2152 uint8_t v;
2153 *rp++ = (*p >> 22); *rp++ = (*p >> 14); *rp++ = (*p >> 6); v = *p++ << 2;
2154 *rp++ = v + (*p >> 28); *rp++ = (*p >> 20); *rp++ = (*p >> 12);
2155 *rp++ = (*p >> 4); v = *p++ << 4;
2156 *rp++ = v + (*p >> 26); *rp++ = (*p >> 18); *rp++ = (*p >> 10);
2157 *rp++ = (*p >> 2); v = *p++ << 6;
2158 *rp++ = v + (*p >> 24); *rp++ = (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
2159 *rp++ = (*p >> 22); *rp++ = (*p >> 14); *rp++ = (*p >> 6); v = *p++ << 2;
2160 *rp++ = v + (*p >> 28); *rp++ = (*p >> 20); *rp++ = (*p >> 12);
2161 *rp++ = (*p >> 4); v = *p++ << 4;
2162 *rp++ = v + (*p >> 26); *rp++ = (*p >> 18); *rp++ = (*p >> 10);
2163 *rp++ = (*p >> 2); v = *p++ << 6;
2164 *rp++ = v + (*p >> 24); *rp++ = (*p >> 16); *rp++ = (*p >> 8);
2165 *rp++ = *p++;
2166 return rp;
2167 }
2168 static const uint8_t *
2169 unpack_30(uint32_t *p, const uint8_t *dp)
2170 {
2171 uint32_t v;
2172 v = *dp++ << 22; v += *dp++ << 14; v += *dp++ << 6; *p++ = v + (*dp >> 2);
2173 v = ((*dp++ << 28) & 0x3fffffff); v += *dp++ << 20; v += *dp++ << 12;
2174 v += *dp++ << 4; *p++ = v + (*dp >> 4);
2175 v = ((*dp++ << 26) & 0x3fffffff); v += *dp++ << 18; v += *dp++ << 10;
2176 v += *dp++ << 2; *p++ = v + (*dp >> 6);
2177 v = ((*dp++ << 24) & 0x3fffffff); v += *dp++ << 16; v += *dp++ << 8;
2178 *p++ = v + *dp++;
2179 v = *dp++ << 22; v += *dp++ << 14; v += *dp++ << 6; *p++ = v + (*dp >> 2);
2180 v = ((*dp++ << 28) & 0x3fffffff); v += *dp++ << 20; v += *dp++ << 12;
2181 v += *dp++ << 4; *p++ = v + (*dp >> 4);
2182 v = ((*dp++ << 26) & 0x3fffffff); v += *dp++ << 18; v += *dp++ << 10;
2183 v += *dp++ << 2; *p++ = v + (*dp >> 6);
2184 v = ((*dp++ << 24) & 0x3fffffff); v += *dp++ << 16; v += *dp++ << 8;
2185 *p++ = v + *dp++;
2186 return dp;
2187 }
2188 static uint8_t *
2189 pack_31(uint32_t *p, uint8_t *rp)
2190 {
2191 uint8_t v;
2192 *rp++ = (*p >> 23); *rp++ = (*p >> 15); *rp++ = (*p >> 7); v = *p++ << 1;
2193 *rp++ = v + (*p >> 30); *rp++ = (*p >> 22); *rp++ = (*p >> 14);
2194 *rp++ = (*p >> 6); v = *p++ << 2;
2195 *rp++ = v + (*p >> 29); *rp++ = (*p >> 21); *rp++ = (*p >> 13);
2196 *rp++ = (*p >> 5); v = *p++ << 3;
2197 *rp++ = v + (*p >> 28); *rp++ = (*p >> 20); *rp++ = (*p >> 12);
2198 *rp++ = (*p >> 4); v = *p++ << 4;
2199 *rp++ = v + (*p >> 27); *rp++ = (*p >> 19); *rp++ = (*p >> 11);
2200 *rp++ = (*p >> 3); v = *p++ << 5;
2201 *rp++ = v + (*p >> 26); *rp++ = (*p >> 18); *rp++ = (*p >> 10);
2202 *rp++ = (*p >> 2); v = *p++ << 6;
2203 *rp++ = v + (*p >> 25); *rp++ = (*p >> 17); *rp++ = (*p >> 9);
2204 *rp++ = (*p >> 1); v = *p++ << 7;
2205 *rp++ = v + (*p >> 24); *rp++ = (*p >> 16); *rp++ = (*p >> 8);
2206 *rp++ = *p++;
2207 return rp;
2208 }
2209 static const uint8_t *
2210 unpack_31(uint32_t *p, const uint8_t *dp)
2211 {
2212 uint32_t v;
2213 v = *dp++ << 23; v += *dp++ << 15; v += *dp++ << 7; *p++ = v + (*dp >> 1);
2214 v = ((*dp++ << 30) & 0x7fffffff); v += *dp++ << 22; v += *dp++ << 14;
2215 v += *dp++ << 6; *p++ = v + (*dp >> 2);
2216 v = ((*dp++ << 29) & 0x7fffffff); v += *dp++ << 21; v += *dp++ << 13;
2217 v += *dp++ << 5; *p++ = v + (*dp >> 3);
2218 v = ((*dp++ << 28) & 0x7fffffff); v += *dp++ << 20; v += *dp++ << 12;
2219 v += *dp++ << 4; *p++ = v + (*dp >> 4);
2220 v = ((*dp++ << 27) & 0x7fffffff); v += *dp++ << 19; v += *dp++ << 11;
2221 v += *dp++ << 3; *p++ = v + (*dp >> 5);
2222 v = ((*dp++ << 26) & 0x7fffffff); v += *dp++ << 18; v += *dp++ << 10;
2223 v += *dp++ << 2; *p++ = v + (*dp >> 6);
2224 v = ((*dp++ << 25) & 0x7fffffff); v += *dp++ << 17; v += *dp++ << 9;
2225 v += *dp++ << 1; *p++ = v + (*dp >> 7);
2226 v = ((*dp++ << 24) & 0x7fffffff); v += *dp++ << 16; v += *dp++ << 8;
2227 *p++ = v + *dp++;
2228 return dp;
2229 }
2230 static uint8_t *
2231 pack_32(uint32_t *p, uint8_t *rp)
2232 {
2233 *rp++ = (*p >> 24); *rp++ = (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
2234 *rp++ = (*p >> 24); *rp++ = (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
2235 *rp++ = (*p >> 24); *rp++ = (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
2236 *rp++ = (*p >> 24); *rp++ = (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
2237 *rp++ = (*p >> 24); *rp++ = (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
2238 *rp++ = (*p >> 24); *rp++ = (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
2239 *rp++ = (*p >> 24); *rp++ = (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
2240 *rp++ = (*p >> 24); *rp++ = (*p >> 16); *rp++ = (*p >> 8); *rp++ = *p++;
2241 return rp;
2242 }
2243 static const uint8_t *
2244 unpack_32(uint32_t *p, const uint8_t *dp)
2245 {
2246 uint32_t v;
2247 v = *dp++ << 24; v += *dp++ << 16; v += *dp++ << 8; *p++ = v + *dp++;
2248 v = *dp++ << 24; v += *dp++ << 16; v += *dp++ << 8; *p++ = v + *dp++;
2249 v = *dp++ << 24; v += *dp++ << 16; v += *dp++ << 8; *p++ = v + *dp++;
2250 v = *dp++ << 24; v += *dp++ << 16; v += *dp++ << 8; *p++ = v + *dp++;
2251 v = *dp++ << 24; v += *dp++ << 16; v += *dp++ << 8; *p++ = v + *dp++;
2252 v = *dp++ << 24; v += *dp++ << 16; v += *dp++ << 8; *p++ = v + *dp++;
2253 v = *dp++ << 24; v += *dp++ << 16; v += *dp++ << 8; *p++ = v + *dp++;
2254 v = *dp++ << 24; v += *dp++ << 16; v += *dp++ << 8; *p++ = v + *dp++;
2255 return dp;
2256 }
2257 /* </generated> */
2258 /* clang-format on */
2259
2260 static uint8_t *
2261 pack_(uint32_t *p, uint32_t i, int w, uint8_t *rp)
2262 {
2263 while (i >= 8) {
2264 /* clang-format off */
2265 switch (w) {
2266 case 0 : break;
2267 case 1 : rp = pack_1(p, rp); break;
2268 case 2 : rp = pack_2(p, rp); break;
2269 case 3 : rp = pack_3(p, rp); break;
2270 case 4 : rp = pack_4(p, rp); break;
2271 case 5 : rp = pack_5(p, rp); break;
2272 case 6 : rp = pack_6(p, rp); break;
2273 case 7 : rp = pack_7(p, rp); break;
2274 case 8 : rp = pack_8(p, rp); break;
2275 case 9 : rp = pack_9(p, rp); break;
2276 case 10 : rp = pack_10(p, rp); break;
2277 case 11 : rp = pack_11(p, rp); break;
2278 case 12 : rp = pack_12(p, rp); break;
2279 case 13 : rp = pack_13(p, rp); break;
2280 case 14 : rp = pack_14(p, rp); break;
2281 case 15 : rp = pack_15(p, rp); break;
2282 case 16 : rp = pack_16(p, rp); break;
2283 case 17 : rp = pack_17(p, rp); break;
2284 case 18 : rp = pack_18(p, rp); break;
2285 case 19 : rp = pack_19(p, rp); break;
2286 case 20 : rp = pack_20(p, rp); break;
2287 case 21 : rp = pack_21(p, rp); break;
2288 case 22 : rp = pack_22(p, rp); break;
2289 case 23 : rp = pack_23(p, rp); break;
2290 case 24 : rp = pack_24(p, rp); break;
2291 case 25 : rp = pack_25(p, rp); break;
2292 case 26 : rp = pack_26(p, rp); break;
2293 case 27 : rp = pack_27(p, rp); break;
2294 case 28 : rp = pack_28(p, rp); break;
2295 case 29 : rp = pack_29(p, rp); break;
2296 case 30 : rp = pack_30(p, rp); break;
2297 case 31 : rp = pack_31(p, rp); break;
2298 case 32 : rp = pack_32(p, rp); break;
2299 }
2300 /* clang-format on */
2301 p += 8;
2302 i -= 8;
2303 }
2304 {
2305 int b;
2306 uint8_t v;
2307 uint32_t *pe = p + i;
2308 for (b = 8 - w, v = 0; p < pe;) {
2309 if (b > 0) {
2310 v += *p++ << b;
2311 b -= w;
2312 } else if (b < 0) {
2313 *rp++ = v + (*p >> -b);
2314 b += 8;
2315 v = 0;
2316 } else {
2317 *rp++ = v + *p++;
2318 b = 8 - w;
2319 v = 0;
2320 }
2321 }
2322 if (b + w != 8) {
2323 *rp++ = v;
2324 }
2325 return rp;
2326 }
2327 }
2328
2329 /* TODO: This is too rough. I hope that this is large enough. */
2330 #define PACK_MAX_SIZE ((UNIT_SIZE / 8) * 32 + (UNIT_SIZE * GRN_B_ENC_MAX_SIZE))
2331
2332 /*
2333 * w: b on the paper.
2334 * ebuf, ep: exception values on the paper.
2335 */
2336 static uint8_t *
2337 pack(uint32_t *p, uint32_t i, uint8_t *freq, uint8_t *rp)
2338 {
2339 int32_t k, w;
2340 uint8_t ebuf[UNIT_SIZE], *ep = ebuf;
2341 uint32_t s, *pe = p + i, r, th = i - (i >> 3);
2342 for (w = 0, s = 0; w <= 32; w++) {
2343 if ((s += freq[w]) >= th) {
2344 break;
2345 }
2346 }
2347 if (i == s) {
2348 *rp++ = w;
2349 return pack_(p, i, w, rp);
2350 }
2351 r = 1 << w;
2352 *rp++ = w + 0x80;
2353 *rp++ = i - s;
2354 if (r >= UNIT_SIZE) {
2355 uint32_t first, *last = &first;
2356 for (k = 0; p < pe; p++, k++) {
2357 if (*p >= r) {
2358 GRN_B_ENC(*p - r, ep);
2359 *last = k;
2360 last = p;
2361 }
2362 }
2363 *last = 0;
2364 *rp++ = (uint8_t)first;
2365 } else {
2366 for (k = 0; p < pe; p++, k++) {
2367 if (*p >= r) {
2368 *ep++ = k;
2369 GRN_B_ENC(*p - r, ep);
2370 *p = 0;
2371 }
2372 }
2373 }
2374 rp = pack_(p - i, i, w, rp);
2375 grn_memcpy(rp, ebuf, ep - ebuf);
2376 return rp + (ep - ebuf);
2377 }
2378
2379 /*
2380 * w: b on the paper.
2381 * ne: the number of exception values on the paper.
2382 */
2383 static const uint8_t *
2384 unpack(grn_ctx *ctx,
2385 grn_codec_data *data,
2386 const uint8_t *dp,
2387 const uint8_t *dpe,
2388 int i,
2389 uint32_t *rp)
2390 {
2391 uint8_t ne = 0, k = 0, w = *dp++;
2392 uint32_t m, *p = rp;
2393 if (w & 0x80) {
2394 ne = *dp++;
2395 w -= 0x80;
2396 m = (1 << w) - 1;
2397 if (m >= UNIT_MASK) {
2398 k = *dp++;
2399 }
2400 } else {
2401 m = (1 << w) - 1;
2402 }
2403 if (w) {
2404 while (i >= 8) {
2405 if (dp + w > dpe) {
2406 return NULL;
2407 }
2408 /* clang-format off */
2409 switch (w) {
2410 case 1 : dp = unpack_1(p, dp); break;
2411 case 2 : dp = unpack_2(p, dp); break;
2412 case 3 : dp = unpack_3(p, dp); break;
2413 case 4 : dp = unpack_4(p, dp); break;
2414 case 5 : dp = unpack_5(p, dp); break;
2415 case 6 : dp = unpack_6(p, dp); break;
2416 case 7 : dp = unpack_7(p, dp); break;
2417 case 8 : dp = unpack_8(p, dp); break;
2418 case 9 : dp = unpack_9(p, dp); break;
2419 case 10 : dp = unpack_10(p, dp); break;
2420 case 11 : dp = unpack_11(p, dp); break;
2421 case 12 : dp = unpack_12(p, dp); break;
2422 case 13 : dp = unpack_13(p, dp); break;
2423 case 14 : dp = unpack_14(p, dp); break;
2424 case 15 : dp = unpack_15(p, dp); break;
2425 case 16 : dp = unpack_16(p, dp); break;
2426 case 17 : dp = unpack_17(p, dp); break;
2427 case 18 : dp = unpack_18(p, dp); break;
2428 case 19 : dp = unpack_19(p, dp); break;
2429 case 20 : dp = unpack_20(p, dp); break;
2430 case 21 : dp = unpack_21(p, dp); break;
2431 case 22 : dp = unpack_22(p, dp); break;
2432 case 23 : dp = unpack_23(p, dp); break;
2433 case 24 : dp = unpack_24(p, dp); break;
2434 case 25 : dp = unpack_25(p, dp); break;
2435 case 26 : dp = unpack_26(p, dp); break;
2436 case 27 : dp = unpack_27(p, dp); break;
2437 case 28 : dp = unpack_28(p, dp); break;
2438 case 29 : dp = unpack_29(p, dp); break;
2439 case 30 : dp = unpack_30(p, dp); break;
2440 case 31 : dp = unpack_31(p, dp); break;
2441 case 32 : dp = unpack_32(p, dp); break;
2442 }
2443 /* clang-format on */
2444 i -= 8;
2445 p += 8;
2446 }
2447 {
2448 int b;
2449 uint32_t v, *pe;
2450 for (b = 8 - w, v = 0, pe = p + i; p < pe && dp < dpe;) {
2451 if (b > 0) {
2452 *p++ = v + ((*dp >> b) & m);
2453 b -= w;
2454 v = 0;
2455 } else if (b < 0) {
2456 v += (*dp++ << -b) & m;
2457 b += 8;
2458 } else {
2459 *p++ = v + (*dp++ & m);
2460 b = 8 - w;
2461 v = 0;
2462 }
2463 }
2464 if (b + w != 8) {
2465 dp++;
2466 }
2467 }
2468 } else {
2469 memset(p, 0, sizeof(uint32_t) * i);
2470 }
2471 if (ne) {
2472 if (m >= UNIT_MASK) {
2473 uint32_t *pp;
2474 while (ne-- && dp) {
2475 pp = &rp[k];
2476 k = *pp;
2477 dp = grn_dec_byte_check(ctx, data, pp, dp, dpe);
2478 *pp += (m + 1);
2479 }
2480 } else {
2481 while (ne-- && dp) {
2482 k = *dp++;
2483 dp = grn_dec_byte_check(ctx, data, &(rp[k]), dp, dpe);
2484 rp[k] += (m + 1);
2485 }
2486 }
2487 }
2488 return dp;
2489 }
2490
2491 static inline size_t
2492 grn_enc_estimate_p_for(grn_ctx *ctx, grn_codec_data *data)
2493 {
2494 return PACK_MAX_SIZE * ((data->n_values / UNIT_SIZE) + 1);
2495 }
2496
2497 static inline uint8_t *
2498 grn_enc_p_for(grn_ctx *ctx, grn_codec_data *data)
2499 {
2500 uint8_t *output = data->output;
2501 uint32_t *values = data->values;
2502 uint32_t n_values = data->n_values;
2503 uint32_t unit[UNIT_SIZE];
2504 uint8_t freq[33];
2505 while (n_values >= UNIT_SIZE) {
2506 memset(freq, 0, 33);
2507 uint32_t i;
2508 for (i = 0; i < UNIT_SIZE; i++) {
2509 unit[i] = values[i];
2510 if (unit[i]) {
2511 grn_bit_scan_rev_result w;
2512 GRN_BIT_SCAN_REV(unit[i], w);
2513 freq[w + 1]++;
2514 } else {
2515 freq[0]++;
2516 }
2517 }
2518 data->offset = output - data->output;
2519 output = pack(unit, UNIT_SIZE, freq, output);
2520 values += UNIT_SIZE;
2521 n_values -= UNIT_SIZE;
2522 }
2523 if (n_values > 0) {
2524 memset(freq, 0, 33);
2525 uint32_t i;
2526 for (i = 0; i < n_values; i++) {
2527 unit[i] = values[i];
2528 if (unit[i]) {
2529 grn_bit_scan_rev_result w;
2530 GRN_BIT_SCAN_REV(unit[i], w);
2531 freq[w + 1]++;
2532 } else {
2533 freq[0]++;
2534 }
2535 }
2536 data->offset = output - data->output;
2537 output = pack(unit, n_values, freq, output);
2538 }
2539 return output;
2540 }
2541
2542 static inline const uint8_t *
2543 grn_dec_p_for(grn_ctx *ctx, grn_codec_data *data)
2544 {
2545 const uint8_t *input = data->input;
2546 const uint8_t *input_end = input + data->size;
2547 uint32_t *values = data->values;
2548 uint32_t n_values = data->n_values;
2549 for (; n_values >= UNIT_SIZE; n_values -= UNIT_SIZE) {
2550 data->offset = input - data->input;
2551 const uint8_t *next_input =
2552 unpack(ctx, data, input, input_end, UNIT_SIZE, values);
2553 if (!next_input) {
2554 grn_codec_error(ctx,
2555 GRN_FILE_CORRUPT,
2556 data,
2557 "[ii][dec][p-for] "
2558 "failed to unpack PFor encoded fixed size data",
2559 __FILE__,
2560 __LINE__,
2561 __FUNCTION__);
2562 return NULL;
2563 }
2564 input = next_input;
2565 values += UNIT_SIZE;
2566 }
2567 if (n_values > 0) {
2568 data->offset = input - data->input;
2569 const uint8_t *next_input =
2570 unpack(ctx, data, input, input_end, n_values, values);
2571 if (!next_input) {
2572 grn_codec_error(
2573 ctx,
2574 GRN_FILE_CORRUPT,
2575 data,
2576 "[ii][dec][p-for] failed to unpack PFor encoded rest data",
2577 __FILE__,
2578 __LINE__,
2579 __FUNCTION__);
2580 return NULL;
2581 }
2582 input = next_input;
2583 values += n_values;
2584 }
2585 return input;
2586 }
2587 /* PFor implementation: end */
2588
2589 /* Binary format used in grn_encv()/grn_decv().
2590 *
2591 * df: Data Frequency: The number of postings
2592 *
2593 * The uint32_t value encoded by GRN_B_ENC:
2594 * +========+========+========+========+
2595 * |12345678|12345678|12345678|12345678|
2596 * +========+========+========+========+
2597 *
2598 * Case 1: If all data don't use PFor:
2599 *
2600 * +========+========+========+========+
2601 * |AAAAAAAA|BBBBBBBB|CCCCCCCC|DDDDDDD1| The last bit is important!
2602 * +========+========+========+========+
2603 * A = ((df << 1) >> 24) & 0xff
2604 * B = ((df << 1) >> 16) & 0xff
2605 * C = ((df << 1) >> 8) & 0xff
2606 * D = ((df << 1) >> 0) & 0xff
2607 * for (i = 0; i < ii->n_elements; i++) {
2608 * for (j = 0; j < dv[i].data_size; j++) {
2609 * +========+========+========+========+
2610 * |AAAAAAAA|BBBBBBBB|CCCCCCCC|DDDDDDDD| dv[i].data[j]
2611 * +========+========+========+========+
2612 * A = (dv[i].data[j] >> 24) & 0xff
2613 * B = (dv[i].data[j] >> 16) & 0xff
2614 * C = (dv[i].data[j] >> 8) & 0xff
2615 * D = (dv[i].data[j] >> 0) & 0xff
2616 * }
2617 * }
2618 *
2619 * Case 2: If any data use PFor:
2620 *
2621 * use_p_for_flags: It's 32bit flags that show that the i-th data
2622 * uses PFor. For example, 0x02 means that the
2623 * second data only uses PFor.
2624 * positions_gap: the_number_positions - df.
2625 *
2626 * +========+========+========+========+
2627 * |AAAAAAAA|BBBBBBBB|CCCCCCCC|DDDDDDD0| The last bit is important!
2628 * +========+========+========+========+
2629 * A = ((use_p_for_flags << 1) >> 24) & 0xff
2630 * B = ((use_p_for_flags << 1) >> 16) & 0xff
2631 * C = ((use_p_for_flags << 1) >> 8) & 0xff
2632 * D = ((use_p_for_flags << 1) >> 0) & 0xff
2633 * +========+========+========+========+
2634 * |AAAAAAAA|BBBBBBBB|CCCCCCCC|DDDDDDDD| df
2635 * +========+========+========+========+
2636 * A = (df >> 24) & 0xff
2637 * B = (df >> 16) & 0xff
2638 * C = (df >> 8) & 0xff
2639 * D = (df >> 0) & 0xff
2640 * if (ii has positions) {
2641 * +========+========+========+========+
2642 * |AAAAAAAA|BBBBBBBB|CCCCCCCC|DDDDDDDD| positions_gap
2643 * +========+========+========+========+
2644 * A = (pgap >> 24) & 0xff
2645 * B = (pgap >> 16) & 0xff
2646 * C = (pgap >> 8) & 0xff
2647 * D = (pgap >> 0) & 0xff
2648 * }
2649 * for (i = 0; i < ii->n_elements; i++) {
2650 * if (dv[i].flags & DATA_USE_P_FOR_ENC) {
2651 * Encode dv[i].data by PFor (unit size is 128)
2652 * } else {
2653 * Same as case 1
2654 * for (j = 0; j < dv[i].data_size; j++) {
2655 * +========+========+========+========+
2656 * |AAAAAAAA|BBBBBBBB|CCCCCCCC|DDDDDDDD| dv[i].data[j]
2657 * +========+========+========+========+
2658 * A = (dv[i].data[j] >> 24) & 0xff
2659 * B = (dv[i].data[j] >> 16) & 0xff
2660 * C = (dv[i].data[j] >> 8) & 0xff
2661 * D = (dv[i].data[j] >> 0) & 0xff
2662 * }
2663 * }
2664 * }
2665 * */
2666
2667 static ssize_t
2668 grn_encv(grn_ctx *ctx,
2669 grn_ii *ii,
2670 grn_id term_id,
2671 datavec *dv,
2672 uint8_t *res,
2673 size_t res_size)
2674 {
2675 uint8_t *rp = res;
2676 ssize_t estimated = 0;
2677 /* f in df is for frequency */
2678 uint32_t positions_gap, l, df, data_size;
2679 if (!(df = dv[0].data_size)) {
2680 return 0;
2681 }
2682 grn_codec_data codec_data = {};
2683 codec_data.ii = ii;
2684 codec_data.term_id = term_id;
2685 uint32_t use_p_for_enc_flags = 0;
2686 for (data_size = 0, l = 0; l < ii->n_elements; l++) {
2687 uint32_t dl = dv[l].data_size;
2688 if (dl < df || ((dl > df) && (l != ii->n_elements - 1))) {
2689 /* invalid argument */
2690 return -1;
2691 }
2692 if (dv[l].flags & DATA_USE_P_FOR_ENC) {
2693 use_p_for_enc_flags += 1 << l;
2694 }
2695 data_size += dl;
2696 }
2697 positions_gap = data_size - df * ii->n_elements;
2698 if (use_p_for_enc_flags == 0) {
2699 if (rp) {
2700 GRN_B_ENC((df << 1) + 1, rp);
2701 for (l = 0; l < ii->n_elements; l++) {
2702 codec_data.nth_element = l;
2703 codec_data.values = dv[l].data;
2704 codec_data.n_values = dv[l].data_size;
2705 codec_data.flags = dv[l].flags;
2706 codec_data.offset = 0;
2707 codec_data.output = rp;
2708 codec_data.size = res_size - (rp - res);
2709 rp = grn_enc_byte(ctx, &codec_data);
2710 }
2711 } else {
2712 codec_data.n_values = 1;
2713 estimated += grn_enc_estimate_byte(ctx, &codec_data);
2714 for (l = 0; l < ii->n_elements; l++) {
2715 codec_data.nth_element = l;
2716 codec_data.values = dv[l].data;
2717 codec_data.n_values = dv[l].data_size;
2718 codec_data.flags = dv[l].flags;
2719 estimated += grn_enc_estimate_byte(ctx, &codec_data);
2720 }
2721 }
2722 } else {
2723 codec_data.n_values = 2;
2724 codec_data.flags = 0;
2725 if (rp) {
2726 uint32_t values[2];
2727 values[0] = (use_p_for_enc_flags << 1);
2728 values[1] = df;
2729 codec_data.values = values;
2730 codec_data.offset = 0;
2731 codec_data.output = rp;
2732 codec_data.size = res_size - (rp - res);
2733 rp = grn_enc_byte(ctx, &codec_data);
2734 } else {
2735 estimated += grn_enc_estimate_byte(ctx, &codec_data);
2736 }
2737 if (dv[ii->n_elements - 1].flags & DATA_ODD) {
2738 codec_data.n_values = 1;
2739 if (rp) {
2740 codec_data.values = &positions_gap;
2741 codec_data.offset = 0;
2742 codec_data.output = rp;
2743 codec_data.size = res_size - (rp - res);
2744 rp = grn_enc_byte(ctx, &codec_data);
2745 } else {
2746 estimated += grn_enc_estimate_byte(ctx, &codec_data);
2747 }
2748 } else {
2749 GRN_ASSERT(positions_gap == 0);
2750 }
2751 for (l = 0; l < ii->n_elements; l++) {
2752 codec_data.nth_element = l;
2753 codec_data.values = dv[l].data;
2754 codec_data.n_values = dv[l].data_size;
2755 codec_data.flags = dv[l].flags;
2756 codec_data.offset = 0;
2757 codec_data.output = rp;
2758 codec_data.size = res_size - (rp - res);
2759 if (dv[l].flags & DATA_USE_P_FOR_ENC) {
2760 if (rp) {
2761 rp = grn_enc_p_for(ctx, &codec_data);
2762 } else {
2763 estimated += grn_enc_estimate_p_for(ctx, &codec_data);
2764 }
2765 } else {
2766 if (rp) {
2767 rp = grn_enc_byte(ctx, &codec_data);
2768 } else {
2769 estimated += grn_enc_estimate_byte(ctx, &codec_data);
2770 }
2771 }
2772 }
2773 }
2774 if (rp) {
2775 return rp - res;
2776 } else {
2777 return estimated;
2778 }
2779 }
2780
2781 static int
2782 grn_decv(grn_ctx *ctx,
2783 grn_ii *ii,
2784 grn_id term_id,
2785 const uint8_t *data,
2786 uint32_t data_size,
2787 datavec *dv)
2788 {
2789 size_t size;
2790 uint32_t df = 0, l, i, *rp;
2791 const uint8_t *dp = data;
2792 const uint8_t *dpe = data + data_size;
2793 if (!data_size) {
2794 dv[0].data_size = 0;
2795 return 0;
2796 }
2797 grn_codec_data codec_data = {};
2798 codec_data.ii = ii;
2799 codec_data.term_id = term_id;
2800 codec_data.offset = 0;
2801 codec_data.input = dp;
2802 codec_data.size = dpe - dp;
2803 dp = grn_dec_byte_check(ctx, &codec_data, &df, dp, dpe);
2804 if (!dp) {
2805 return 0;
2806 }
2807 if ((df & 1)) {
2808 df >>= 1;
2809 size = data_size;
2810 if (dv[ii->n_elements].data < dv[0].data + size) {
2811 if (dv[0].data) {
2812 GRN_FREE(dv[0].data);
2813 dv[0].data = NULL;
2814 }
2815 if (!(rp =
2816 static_cast<uint32_t *>(GRN_MALLOC(size * sizeof(uint32_t))))) {
2817 grn_obj term;
2818 GRN_DEFINE_NAME(ii);
2819 GRN_TEXT_INIT(&term, 0);
2820 if (term_id != GRN_ID_NIL) {
2821 grn_ii_get_term(ctx, ii, term_id, &term);
2822 }
2823 ERR(GRN_NO_MEMORY_AVAILABLE,
2824 "[ii][decv] failed to extend buffer for data vector: "
2825 "<%.*s>: "
2826 "<%.*s>(%u): "
2827 "%" GRN_FMT_SIZE " -> %" GRN_FMT_SIZE ": "
2828 "PFor(nothing)",
2829 name_size,
2830 name,
2831 (int)GRN_TEXT_LEN(&term),
2832 GRN_TEXT_VALUE(&term),
2833 term_id,
2834 dv[ii->n_elements].data - dv[0].data,
2835 size);
2836 GRN_OBJ_FIN(ctx, &term);
2837 return 0;
2838 }
2839 dv[ii->n_elements].data = rp + size;
2840 } else {
2841 rp = dv[0].data;
2842 }
2843 for (l = 0; l < ii->n_elements; l++) {
2844 dv[l].data = rp;
2845 codec_data.nth_element = l;
2846 codec_data.offset = 0;
2847 codec_data.input = dp;
2848 codec_data.size = dpe - dp;
2849 if (l < ii->n_elements - 1) {
2850 for (i = 0; i < df && dp; i++, rp++) {
2851 dp = grn_dec_byte_check(ctx, &codec_data, rp, dp, dpe);
2852 }
2853 } else {
2854 for (i = 0; dp < dpe && dp; i++, rp++) {
2855 dp = grn_dec_byte_check(ctx, &codec_data, rp, dp, dpe);
2856 }
2857 }
2858 if (!dp) {
2859 return 0;
2860 }
2861 dv[l].data_size = i;
2862 }
2863 } else {
2864 uint32_t n, rest;
2865 uint32_t use_p_for_enc_flags = df >> 1;
2866 codec_data.offset = 0;
2867 codec_data.input = dp;
2868 codec_data.size = dpe - dp;
2869 dp = grn_dec_byte_check(ctx, &codec_data, &df, dp, dpe);
2870 if (!dp) {
2871 return 0;
2872 }
2873 if (dv[ii->n_elements - 1].flags & DATA_ODD) {
2874 codec_data.offset = 0;
2875 codec_data.input = dp;
2876 codec_data.size = dpe - dp;
2877 dp = grn_dec_byte_check(ctx, &codec_data, &rest, dp, dpe);
2878 if (!dp) {
2879 return 0;
2880 }
2881 } else {
2882 rest = 0;
2883 }
2884 codec_data.n_odd_values = rest;
2885 size = df * ii->n_elements + rest;
2886 if (dv[ii->n_elements].data < dv[0].data + size) {
2887 if (dv[0].data) {
2888 GRN_FREE(dv[0].data);
2889 dv[0].data = NULL;
2890 }
2891 if (!(rp =
2892 static_cast<uint32_t *>(GRN_MALLOC(size * sizeof(uint32_t))))) {
2893 grn_obj term;
2894 GRN_DEFINE_NAME(ii);
2895 GRN_TEXT_INIT(&term, 0);
2896 if (term_id != GRN_ID_NIL) {
2897 grn_ii_get_term(ctx, ii, term_id, &term);
2898 }
2899 ERR(GRN_NO_MEMORY_AVAILABLE,
2900 "[ii][decv] failed to extend buffer for data vector: "
2901 "<%.*s>: "
2902 "<%.*s>(%u): "
2903 "%" GRN_FMT_SIZE " -> %" GRN_FMT_SIZE ": "
2904 "PFor(%#x)", /* Binary number is better but %b doesn't exist. */
2905 name_size,
2906 name,
2907 (int)GRN_TEXT_LEN(&term),
2908 GRN_TEXT_VALUE(&term),
2909 term_id,
2910 dv[ii->n_elements].data - dv[0].data,
2911 size,
2912 use_p_for_enc_flags);
2913 GRN_OBJ_FIN(ctx, &term);
2914 return 0;
2915 }
2916 dv[ii->n_elements].data = rp + size;
2917 } else {
2918 rp = dv[0].data;
2919 }
2920 for (l = 0; l < ii->n_elements; l++) {
2921 dv[l].data = rp;
2922 dv[l].data_size = n = (l < ii->n_elements - 1) ? df : df + rest;
2923 if (use_p_for_enc_flags & (1 << l)) {
2924 dv[l].flags |= DATA_USE_P_FOR_ENC;
2925 } else {
2926 dv[l].flags &= ~DATA_USE_P_FOR_ENC;
2927 }
2928 codec_data.nth_element = l;
2929 codec_data.values = dv[l].data;
2930 codec_data.n_values = dv[l].data_size;
2931 codec_data.flags = dv[l].flags;
2932 codec_data.offset = 0;
2933 codec_data.input = dp;
2934 codec_data.size = dpe - dp;
2935 if (codec_data.flags & DATA_USE_P_FOR_ENC) {
2936 dp = grn_dec_p_for(ctx, &codec_data);
2937 } else {
2938 dp = grn_dec_byte(ctx, &codec_data);
2939 }
2940 if (!dp) {
2941 return 0;
2942 }
2943 rp += dv[l].data_size;
2944 }
2945 if (dp != dpe) {
2946 codec_data.n_values = df;
2947 codec_data.offset = dp - data;
2948 codec_data.input = data;
2949 codec_data.size = data_size;
2950 grn_codec_error(ctx,
2951 GRN_FILE_CORRUPT,
2952 &codec_data,
2953 "[ii][decv] input size and used size aren't matched",
2954 __FILE__,
2955 __LINE__,
2956 __FUNCTION__);
2957 return 0;
2958 }
2959 }
2960 return rp - dv[0].data;
2961 }
2962
2963 extern "C" int
2964 grn_b_enc(grn_ctx *ctx, uint32_t *data, uint32_t data_size, uint8_t **res)
2965 {
2966 uint8_t *rp;
2967 uint32_t *dp, i;
2968 *res = rp =
2969 static_cast<uint8_t *>(GRN_MALLOC(data_size * sizeof(uint32_t) * 2));
2970 GRN_B_ENC(data_size, rp);
2971 for (i = data_size, dp = data; i; i--, dp++) {
2972 GRN_B_ENC(*dp, rp);
2973 }
2974 return rp - *res;
2975 }
2976
2977 extern "C" int
2978 grn_b_dec(grn_ctx *ctx, uint8_t *data, uint32_t data_size, uint32_t **res)
2979 {
2980 uint32_t i, *rp, orig_size;
2981 uint8_t *dp = data;
2982 GRN_B_DEC(orig_size, dp);
2983 *res = rp = static_cast<uint32_t *>(GRN_MALLOC(orig_size * sizeof(uint32_t)));
2984 for (i = orig_size; i; i--, rp++) {
2985 GRN_B_DEC(*rp, dp);
2986 }
2987 return orig_size;
2988 }
2989
2990 /* buffer */
2991
2992 typedef struct {
2993 uint32_t tid;
2994 uint32_t size_in_chunk;
2995 uint32_t pos_in_chunk;
2996 uint16_t size_in_buffer;
2997 uint16_t pos_in_buffer;
2998 } buffer_term;
2999
3000 typedef struct {
3001 uint16_t step;
3002 uint16_t jump;
3003 } buffer_rec;
3004
3005 typedef struct {
3006 uint32_t chunk;
3007 uint32_t chunk_size;
3008 uint32_t buffer_free;
3009 uint16_t nterms;
3010 uint16_t nterms_void;
3011 } buffer_header;
3012
3013 typedef struct {
3014 buffer_header header;
3015 buffer_term terms[(S_SEGMENT - sizeof(buffer_header)) / sizeof(buffer_term)];
3016 } buffer;
3017
3018 #define GRN_II_POS_LSEG_SHIFT_SIZE (32 - GRN_II_W_LSEG)
3019 #define GRN_II_POS_LSEG_SHIFT_SIZE_LARGE (32 - GRN_II_W_LSEG_LARGE)
3020 #define GRN_II_POS_LOFFSET_SHIFT_SIZE ((16 - GRN_II_W_LOFFSET) + 2)
3021 #define GRN_II_POS_LOFFSET_SHIFT_SIZE_LARGE ((16 - GRN_II_W_LOFFSET_LARGE) + 2)
3022
3023 static inline uint32_t
3024 grn_ii_pos_lseg(grn_ii *ii, uint32_t pos)
3025 {
3026 if (ii->header.common->flags & GRN_OBJ_INDEX_LARGE) {
3027 return pos >> GRN_II_POS_LSEG_SHIFT_SIZE_LARGE;
3028 } else {
3029 return pos >> GRN_II_POS_LSEG_SHIFT_SIZE;
3030 }
3031 }
3032
3033 static inline uint32_t
3034 grn_ii_pos_loffset(grn_ii *ii, uint32_t pos)
3035 {
3036 if (ii->header.common->flags & GRN_OBJ_INDEX_LARGE) {
3037 return (pos & ((1 << GRN_II_W_LOFFSET_LARGE) - 1))
3038 << GRN_II_POS_LOFFSET_SHIFT_SIZE_LARGE;
3039 } else {
3040 return (pos & ((1 << GRN_II_W_LOFFSET) - 1))
3041 << GRN_II_POS_LOFFSET_SHIFT_SIZE;
3042 }
3043 }
3044
3045 static inline uint32_t
3046 grn_ii_pos_pack(grn_ii *ii, uint32_t lseg, uint32_t loffset)
3047 {
3048 if (ii->header.common->flags & GRN_OBJ_INDEX_LARGE) {
3049 return (lseg << GRN_II_POS_LSEG_SHIFT_SIZE_LARGE) +
3050 (loffset >> GRN_II_POS_LOFFSET_SHIFT_SIZE_LARGE);
3051 } else {
3052 return (lseg << GRN_II_POS_LSEG_SHIFT_SIZE) +
3053 (loffset >> GRN_II_POS_LOFFSET_SHIFT_SIZE);
3054 }
3055 }
3056
3057 #define POS_LOFFSET_HEADER sizeof(buffer_header)
3058 #define POS_LOFFSET_TERM sizeof(buffer_term)
3059
3060 static inline bool
3061 grn_ii_pos_is_available(grn_ctx *ctx, uint32_t flags, const char *context)
3062 {
3063 if (flags & GRN_OBJ_INDEX_LARGE) {
3064 if ((POS_LOFFSET_HEADER % 4) != 0) {
3065 ERR(GRN_OPERATION_NOT_SUPPORTED,
3066 "%s INDEX_LARGE requires 32bit aligned offset header: "
3067 "<%" GRN_FMT_SIZE ">",
3068 context,
3069 POS_LOFFSET_HEADER);
3070 return false;
3071 }
3072 if ((POS_LOFFSET_TERM % 4) != 0) {
3073 ERR(GRN_OPERATION_NOT_SUPPORTED,
3074 "%s INDEX_LARGE requires 32bit aligned offset term: "
3075 "<%" GRN_FMT_SIZE ">",
3076 context,
3077 POS_LOFFSET_TERM);
3078 return false;
3079 }
3080 }
3081 return true;
3082 }
3083
3084 #define POS_IS_EMBED(pos) ((pos) & 1)
3085 #define POS_EMBED_RID(rid) (((rid) << 1) | 1)
3086 #define POS_EMBED_RID_SID(rid, sid) ((((rid) << 12) + ((sid) << 1)) | 1)
3087 #define POS_RID_EXTRACT(pos) ((pos) >> 1)
3088 #define POS_RID_SID_EXTRACT_RID(pos) BIT31_12((pos))
3089 #define POS_RID_SID_EXTRACT_SID(pos) BIT11_01((pos))
3090
3091 static inline uint32_t
3092 buffer_open(
3093 grn_ctx *ctx, grn_ii *ii, uint32_t pos, buffer_term **bt, buffer **b)
3094 {
3095 const uint32_t lseg = grn_ii_pos_lseg(ii, pos);
3096 const uint32_t pseg = grn_ii_get_buffer_pseg_inline(ii, lseg);
3097 if (pseg != GRN_II_PSEG_NOT_ASSIGNED) {
3098 auto p = static_cast<byte *>(grn_io_seg_ref(ctx, ii->seg, pseg));
3099 if (!p) {
3100 return GRN_II_PSEG_NOT_ASSIGNED;
3101 }
3102 if (b) {
3103 *b = (buffer *)p;
3104 }
3105 if (bt) {
3106 *bt = (buffer_term *)(p + grn_ii_pos_loffset(ii, pos));
3107 }
3108 }
3109 return pseg;
3110 }
3111
3112 static inline grn_rc
3113 buffer_close(grn_ctx *ctx, grn_ii *ii, uint32_t pseg)
3114 {
3115 if (pseg >= ii->seg->header->max_segment) {
3116 GRN_LOG(ctx, GRN_LOG_NOTICE, "invalid pseg buffer_close(%d)", pseg);
3117 return GRN_INVALID_ARGUMENT;
3118 }
3119 grn_io_seg_unref(ctx, ii->seg, pseg);
3120 return GRN_SUCCESS;
3121 }
3122
3123 typedef struct {
3124 uint32_t rid;
3125 uint32_t sid;
3126 } docid;
3127
3128 #define BUFFER_REC_DEL(r) ((r)->jump = 1)
3129 #define BUFFER_REC_DELETED(r) ((r)->jump == 1)
3130
3131 #define BUFFER_REC_AT(b, pos) ((buffer_rec *)(b) + (pos))
3132 #define BUFFER_REC_POS(b, rec) ((uint16_t)((rec) - (buffer_rec *)(b)))
3133
3134 static inline void
3135 buffer_term_dump(grn_ctx *ctx, grn_ii *ii, buffer *b, buffer_term *bt)
3136 {
3137 int pos, rid, sid;
3138 uint8_t *p;
3139 buffer_rec *r;
3140
3141 if (!grn_logger_pass(ctx, GRN_LOG_DEBUG)) {
3142 return;
3143 }
3144
3145 GRN_LOG(ctx,
3146 GRN_LOG_DEBUG,
3147 "b=(%x %u %u %u)",
3148 b->header.chunk,
3149 b->header.chunk_size,
3150 b->header.buffer_free,
3151 b->header.nterms);
3152 GRN_LOG(ctx,
3153 GRN_LOG_DEBUG,
3154 "bt=(%u %u %u %u %u)",
3155 bt->tid,
3156 bt->size_in_chunk,
3157 bt->pos_in_chunk,
3158 bt->size_in_buffer,
3159 bt->pos_in_buffer);
3160 for (pos = bt->pos_in_buffer; pos; pos = r->step) {
3161 r = BUFFER_REC_AT(b, pos);
3162 p = GRN_NEXT_ADDR(r);
3163 GRN_B_DEC(rid, p);
3164 if ((ii->header.common->flags & GRN_OBJ_WITH_SECTION)) {
3165 GRN_B_DEC(sid, p);
3166 } else {
3167 sid = 1;
3168 }
3169 GRN_LOG(ctx,
3170 GRN_LOG_DEBUG,
3171 "%d=(%d:%d),(%d:%d)",
3172 pos,
3173 r->jump,
3174 r->step,
3175 rid,
3176 sid);
3177 }
3178 }
3179
3180 static inline grn_rc
3181 check_jump(grn_ctx *ctx, grn_ii *ii, buffer *b, buffer_rec *r, int j)
3182 {
3183 uint16_t i = BUFFER_REC_POS(b, r);
3184 uint8_t *p;
3185 buffer_rec *r2;
3186 docid id, id2;
3187 if (!j) {
3188 return GRN_SUCCESS;
3189 }
3190 p = GRN_NEXT_ADDR(r);
3191 GRN_B_DEC(id.rid, p);
3192 if ((ii->header.common->flags & GRN_OBJ_WITH_SECTION)) {
3193 GRN_B_DEC(id.sid, p);
3194 } else {
3195 id.sid = 1;
3196 }
3197 if (j == 1) {
3198 GRN_LOG(ctx, GRN_LOG_DEBUG, "deleting! %d(%d:%d)", i, id.rid, id.sid);
3199 return GRN_SUCCESS;
3200 }
3201 r2 = BUFFER_REC_AT(b, j);
3202 p = GRN_NEXT_ADDR(r2);
3203 GRN_B_DEC(id2.rid, p);
3204 if ((ii->header.common->flags & GRN_OBJ_WITH_SECTION)) {
3205 GRN_B_DEC(id2.sid, p);
3206 } else {
3207 id2.sid = 1;
3208 }
3209 if (r2->step == i) {
3210 GRN_LOG(ctx,
3211 GRN_LOG_EMERG,
3212 "cycle! %d(%d:%d)<->%d(%d:%d)",
3213 i,
3214 id.rid,
3215 id.sid,
3216 j,
3217 id2.rid,
3218 id2.sid);
3219 return GRN_FILE_CORRUPT;
3220 }
3221 if (id2.rid < id.rid || (id2.rid == id.rid && id2.sid <= id.sid)) {
3222 GRN_LOG(ctx,
3223 GRN_LOG_CRIT,
3224 "invalid jump! %d(%d:%d)(%d:%d)->%d(%d:%d)(%d:%d)",
3225 i,
3226 r->jump,
3227 r->step,
3228 id.rid,
3229 id.sid,
3230 j,
3231 r2->jump,
3232 r2->step,
3233 id2.rid,
3234 id2.sid);
3235 return GRN_FILE_CORRUPT;
3236 }
3237 return GRN_SUCCESS;
3238 }
3239
3240 static inline grn_rc
3241 set_jump_r(grn_ctx *ctx, grn_ii *ii, buffer *b, buffer_rec *from, int to)
3242 {
3243 int i, j, max_jump = 100;
3244 buffer_rec *r, *r2;
3245 for (r = from, j = to; j > 1 && max_jump--; r = BUFFER_REC_AT(b, r->step)) {
3246 r2 = BUFFER_REC_AT(b, j);
3247 if (r == r2) {
3248 break;
3249 }
3250 if (BUFFER_REC_DELETED(r2)) {
3251 break;
3252 }
3253 if (j == (i = r->jump)) {
3254 break;
3255 }
3256 if (j == r->step) {
3257 break;
3258 }
3259 if (check_jump(ctx, ii, b, r, j)) {
3260 ERR(GRN_FILE_CORRUPT, "check_jump failed");
3261 return ctx->rc;
3262 }
3263 r->jump = j;
3264 j = i;
3265 if (!r->step) {
3266 return GRN_FILE_CORRUPT;
3267 }
3268 }
3269 return GRN_SUCCESS;
3270 }
3271
3272 #define GET_NUM_BITS(x, n) \
3273 do { \
3274 n = x; \
3275 n = (n & 0x55555555) + ((n >> 1) & 0x55555555); \
3276 n = (n & 0x33333333) + ((n >> 2) & 0x33333333); \
3277 n = (n & 0x0F0F0F0F) + ((n >> 4) & 0x0F0F0F0F); \
3278 n = (n & 0x00FF00FF) + ((n >> 8) & 0x00FF00FF); \
3279 n = (n & 0x0000FFFF) + ((n >> 16) & 0x0000FFFF); \
3280 } while (0)
3281
3282 static inline grn_rc
3283 buffer_put(grn_ctx *ctx,
3284 grn_ii *ii,
3285 buffer *b,
3286 buffer_term *bt,
3287 buffer_rec *rnew,
3288 uint8_t *bs,
3289 grn_ii_updspec *u,
3290 int size)
3291 {
3292 uint8_t *p;
3293 docid id_curr = {0, 0}, id_start = {0, 0}, id_post = {0, 0};
3294 buffer_rec *r_curr, *r_start = NULL;
3295 uint16_t last = 0, *lastp = &bt->pos_in_buffer, pos = BUFFER_REC_POS(b, rnew);
3296 int vdelta = 0, delta, delta0 = 0, vhops = 0, nhops = 0, reset = 1;
3297 grn_memcpy(GRN_NEXT_ADDR(rnew), bs, size - sizeof(buffer_rec));
3298 for (;;) {
3299 if (!*lastp) {
3300 rnew->step = 0;
3301 rnew->jump = 0;
3302 // smb_wmb();
3303 *lastp = pos;
3304 if (bt->size_in_buffer++ > 1) {
3305 buffer_rec *rhead = BUFFER_REC_AT(b, bt->pos_in_buffer);
3306 rhead->jump = pos;
3307 if (!(bt->size_in_buffer & 1)) {
3308 int n;
3309 buffer_rec *r = BUFFER_REC_AT(b, rhead->step), *r2;
3310 GET_NUM_BITS(bt->size_in_buffer, n);
3311 while (n-- && (r->jump > 1)) {
3312 r2 = BUFFER_REC_AT(b, r->jump);
3313 if (BUFFER_REC_DELETED(r2)) {
3314 break;
3315 }
3316 r = r2;
3317 }
3318 if (r != rnew) {
3319 set_jump_r(ctx, ii, b, r, last);
3320 if (ctx->rc != GRN_SUCCESS) {
3321 break;
3322 }
3323 }
3324 }
3325 }
3326 break;
3327 }
3328 r_curr = BUFFER_REC_AT(b, *lastp);
3329 p = GRN_NEXT_ADDR(r_curr);
3330 GRN_B_DEC(id_curr.rid, p);
3331 if ((ii->header.common->flags & GRN_OBJ_WITH_SECTION)) {
3332 GRN_B_DEC(id_curr.sid, p);
3333 } else {
3334 id_curr.sid = 1;
3335 }
3336 if (id_curr.rid < id_post.rid ||
3337 (id_curr.rid == id_post.rid && id_curr.sid < id_post.sid)) {
3338 {
3339 GRN_DEFINE_NAME(ii);
3340 CRIT(GRN_FILE_CORRUPT,
3341 "[ii][buffer][put] loop is found: "
3342 "<%.*s>: "
3343 "(%d:%d)->(%d:%d)",
3344 name_size,
3345 name,
3346 id_post.rid,
3347 id_post.sid,
3348 id_curr.rid,
3349 id_curr.sid);
3350 }
3351 buffer_term_dump(ctx, ii, b, bt);
3352 bt->pos_in_buffer = 0;
3353 bt->size_in_buffer = 0;
3354 lastp = &bt->pos_in_buffer;
3355 continue;
3356 }
3357 id_post.rid = id_curr.rid;
3358 id_post.sid = id_curr.sid;
3359 if (u->rid < id_curr.rid ||
3360 (u->rid == id_curr.rid && u->sid <= id_curr.sid)) {
3361 uint16_t step = *lastp, jump = r_curr->jump;
3362 if (u->rid == id_curr.rid) {
3363 if (u->sid == 0) {
3364 while (id_curr.rid == u->rid) {
3365 BUFFER_REC_DEL(r_curr);
3366 if (!(step = r_curr->step)) {
3367 break;
3368 }
3369 r_curr = BUFFER_REC_AT(b, step);
3370 p = GRN_NEXT_ADDR(r_curr);
3371 GRN_B_DEC(id_curr.rid, p);
3372 if ((ii->header.common->flags & GRN_OBJ_WITH_SECTION)) {
3373 GRN_B_DEC(id_curr.sid, p);
3374 } else {
3375 id_curr.sid = 1;
3376 }
3377 }
3378 } else if (u->sid == id_curr.sid) {
3379 BUFFER_REC_DEL(r_curr);
3380 step = r_curr->step;
3381 }
3382 }
3383 rnew->step = step;
3384 rnew->jump = check_jump(ctx, ii, b, rnew, jump) ? 0 : jump;
3385 // smb_wmb();
3386 *lastp = pos;
3387 break;
3388 }
3389
3390 if (reset) {
3391 r_start = r_curr;
3392 id_start.rid = id_curr.rid;
3393 id_start.sid = id_curr.sid;
3394 if (!(delta0 = u->rid - id_start.rid)) {
3395 delta0 = u->sid - id_start.sid;
3396 }
3397 nhops = 0;
3398 vhops = 1;
3399 vdelta = delta0 >> 1;
3400 } else {
3401 if (!(delta = id_curr.rid - id_start.rid)) {
3402 delta = id_curr.sid - id_start.sid;
3403 }
3404 if (vdelta < delta) {
3405 vdelta += (delta0 >> ++vhops);
3406 r_start = r_curr;
3407 }
3408 if (nhops > vhops) {
3409 set_jump_r(ctx, ii, b, r_start, *lastp);
3410 if (ctx->rc != GRN_SUCCESS) {
3411 break;
3412 }
3413 } else {
3414 nhops++;
3415 }
3416 }
3417
3418 last = *lastp;
3419 lastp = &r_curr->step;
3420 reset = 0;
3421 {
3422 uint16_t posj = r_curr->jump;
3423 if (posj > 1) {
3424 buffer_rec *rj = BUFFER_REC_AT(b, posj);
3425 if (!BUFFER_REC_DELETED(rj)) {
3426 docid idj;
3427 p = GRN_NEXT_ADDR(rj);
3428 GRN_B_DEC(idj.rid, p);
3429 if ((ii->header.common->flags & GRN_OBJ_WITH_SECTION)) {
3430 GRN_B_DEC(idj.sid, p);
3431 } else {
3432 idj.sid = 1;
3433 }
3434 if (idj.rid < u->rid || (idj.rid == u->rid && idj.sid < u->sid)) {
3435 last = posj;
3436 lastp = &rj->step;
3437 } else {
3438 reset = 1;
3439 }
3440 }
3441 }
3442 }
3443 }
3444 return ctx->rc;
3445 }
3446
3447 /* array */
3448
3449 static inline uint32_t *
3450 array_at(grn_ctx *ctx, grn_ii *ii, uint32_t id)
3451 {
3452 if (id > GRN_ID_MAX) {
3453 return NULL;
3454 }
3455 const uint16_t seg = id >> W_ARRAY;
3456 const uint32_t pseg = grn_ii_get_array_pseg_inline(ii, seg);
3457 if (pseg == GRN_II_PSEG_NOT_ASSIGNED) {
3458 return NULL;
3459 }
3460 auto p = static_cast<byte *>(grn_io_seg_ref(ctx, ii->seg, pseg));
3461 if (!p) {
3462 return NULL;
3463 }
3464 return (uint32_t *)(p + (id & ARRAY_MASK_IN_A_SEGMENT) * S_ARRAY_ELEMENT);
3465 }
3466
3467 static inline uint32_t *
3468 array_get(grn_ctx *ctx, grn_ii *ii, uint32_t id)
3469 {
3470 byte *p = NULL;
3471 if (id > GRN_ID_MAX) {
3472 return NULL;
3473 }
3474 const uint16_t seg = id >> W_ARRAY;
3475 uint32_t pseg = grn_ii_get_array_pseg_inline(ii, seg);
3476 if (pseg == GRN_II_PSEG_NOT_ASSIGNED) {
3477 if (segment_get_clear(ctx, ii, &pseg)) {
3478 return NULL;
3479 }
3480 grn_ii_set_array_pseg_inline(ii, seg, pseg);
3481 if (seg >= ii->header.common->amax) {
3482 ii->header.common->amax = seg + 1;
3483 }
3484 }
3485 p = static_cast<byte *>(grn_io_seg_ref(ctx, ii->seg, pseg));
3486 if (!p) {
3487 return NULL;
3488 }
3489 return (uint32_t *)(p + (id & ARRAY_MASK_IN_A_SEGMENT) * S_ARRAY_ELEMENT);
3490 }
3491
3492 static inline void
3493 array_unref(grn_ctx *ctx, grn_ii *ii, uint32_t id)
3494 {
3495 const uint32_t pseg = grn_ii_get_array_pseg_inline(ii, id >> W_ARRAY);
3496 grn_io_seg_unref(ctx, ii->seg, pseg);
3497 }
3498
3499 /* updspec */
3500
3501 extern "C" grn_ii_updspec *
3502 grn_ii_updspec_open(grn_ctx *ctx, uint32_t rid, uint32_t sid)
3503 {
3504 auto u = static_cast<grn_ii_updspec *>(GRN_CALLOC(sizeof(grn_ii_updspec)));
3505 if (!u) {
3506 return NULL;
3507 }
3508 u->rid = rid;
3509 u->sid = sid;
3510 u->weight = 0;
3511 u->tf = 0;
3512 u->atf = 0;
3513 u->pos = NULL;
3514 u->tail = NULL;
3515 // u->vnodes = NULL;
3516 return u;
3517 }
3518
3519 extern "C" grn_rc
3520 grn_ii_updspec_add(grn_ctx *ctx, grn_ii_updspec *u, int pos, int32_t weight)
3521 {
3522 u->atf++;
3523 if (u->tf >= GRN_II_MAX_TF) {
3524 return GRN_SUCCESS;
3525 }
3526 auto p = static_cast<_grn_ii_pos *>(GRN_CALLOC(sizeof(struct _grn_ii_pos)));
3527 if (!p) {
3528 return GRN_NO_MEMORY_AVAILABLE;
3529 }
3530 u->weight += weight;
3531 p->pos = pos;
3532 p->next = NULL;
3533 if (u->tail) {
3534 u->tail->next = p;
3535 } else {
3536 u->pos = p;
3537 }
3538 u->tail = p;
3539 u->tf++;
3540 return GRN_SUCCESS;
3541 }
3542
3543 extern "C" int
3544 grn_ii_updspec_cmp(grn_ii_updspec *a, grn_ii_updspec *b)
3545 {
3546 struct _grn_ii_pos *pa, *pb;
3547 if (a->rid != b->rid) {
3548 return a->rid - b->rid;
3549 }
3550 if (a->sid != b->sid) {
3551 return a->sid - b->sid;
3552 }
3553 if (a->weight != b->weight) {
3554 return a->weight - b->weight;
3555 }
3556 if (a->tf != b->tf) {
3557 return a->tf - b->tf;
3558 }
3559 for (pa = a->pos, pb = b->pos; pa && pb; pa = pa->next, pb = pb->next) {
3560 if (pa->pos != pb->pos) {
3561 return pa->pos - pb->pos;
3562 }
3563 }
3564 if (pa) {
3565 return 1;
3566 }
3567 if (pb) {
3568 return -1;
3569 }
3570 return 0;
3571 }
3572
3573 extern "C" grn_rc
3574 grn_ii_updspec_close(grn_ctx *ctx, grn_ii_updspec *u)
3575 {
3576 struct _grn_ii_pos *p = u->pos, *q;
3577 while (p) {
3578 q = p->next;
3579 GRN_FREE(p);
3580 p = q;
3581 }
3582 GRN_FREE(u);
3583 return GRN_SUCCESS;
3584 }
3585
3586 static inline uint8_t *
3587 encode_rec(
3588 grn_ctx *ctx, grn_ii *ii, grn_ii_updspec *u, unsigned int *size, int deletep)
3589 {
3590 struct _grn_ii_pos *pp;
3591 uint32_t lpos, tf, weight;
3592 if (deletep) {
3593 tf = 0;
3594 weight = 0;
3595 } else {
3596 tf = u->tf;
3597 weight = u->weight;
3598 }
3599 auto br = static_cast<uint8_t *>(GRN_MALLOC((tf + 4) * 5));
3600 if (!br) {
3601 return NULL;
3602 }
3603 auto p = br;
3604 GRN_B_ENC(u->rid, p);
3605 if ((ii->header.common->flags & GRN_OBJ_WITH_SECTION)) {
3606 GRN_B_ENC(u->sid, p);
3607 } else {
3608 u->sid = 1;
3609 }
3610 GRN_B_ENC(tf, p);
3611 if ((ii->header.common->flags & GRN_OBJ_WITH_WEIGHT)) {
3612 GRN_B_ENC(weight, p);
3613 }
3614 if ((ii->header.common->flags & GRN_OBJ_WITH_POSITION)) {
3615 for (lpos = 0, pp = u->pos; pp && tf--; lpos = pp->pos, pp = pp->next) {
3616 GRN_B_ENC(pp->pos - lpos, p);
3617 }
3618 }
3619 while (((intptr_t)p & 0x03)) {
3620 *p++ = 0;
3621 }
3622 *size = (unsigned int)((p - br) + sizeof(buffer_rec));
3623 return br;
3624 }
3625
3626 typedef struct {
3627 grn_ii *ii;
3628 grn_hash *h;
3629 } lexicon_deletable_arg;
3630
3631 #ifdef CASCADE_DELETE_LEXICON
3632 static int
3633 lexicon_deletable(grn_ctx *ctx, grn_obj *lexicon, grn_id tid, void *arg)
3634 {
3635 uint32_t *a;
3636 grn_hash *h = ((lexicon_deletable_arg *)arg)->h;
3637 grn_ii *ii = ((lexicon_deletable_arg *)arg)->ii;
3638 if (!h) {
3639 return 0;
3640 }
3641 if ((a = array_at(ctx, ii, tid))) {
3642 if (a[0]) {
3643 array_unref(ctx, ii, tid);
3644 return 0;
3645 }
3646 array_unref(ctx, ii, tid);
3647 }
3648 {
3649 grn_ii_updspec **u;
3650 if (!grn_hash_get(ctx, h, &tid, sizeof(grn_id), (void **)&u)) {
3651 return (ERRP(ctx, GRN_ERROR)) ? 0 : 1;
3652 }
3653 if (!(*u)->tf || !(*u)->sid) {
3654 return 1;
3655 }
3656 return 0;
3657 }
3658 }
3659 #endif /* CASCADE_DELETE_LEXICON */
3660
3661 static inline void
3662 lexicon_delete(grn_ctx *ctx, grn_ii *ii, uint32_t tid, grn_hash *h)
3663 {
3664 #ifdef CASCADE_DELETE_LEXICON
3665 lexicon_deletable_arg arg = {ii, h};
3666 grn_table_delete_optarg optarg = {0, lexicon_deletable, &arg};
3667 grn_table_delete_data data;
3668 grn_table_delete_data_init(ctx, &data, ii->lexicon);
3669 data.id = tid;
3670 data.optarg = &optarg;
3671 grn_table_delete_by_id_without_lock(ctx, &data);
3672 grn_table_delete_data_fin(ctx, &data);
3673 #endif /* CASCADE_DELETE_LEXICON */
3674 }
3675
3676 typedef struct {
3677 grn_id rid;
3678 uint32_t sid;
3679 uint32_t tf;
3680 uint32_t weight;
3681 uint32_t flags;
3682 } docinfo;
3683
3684 static docinfo null_docinfo = {};
3685
3686 typedef struct {
3687 uint32_t segno;
3688 uint32_t size;
3689 uint32_t dgap;
3690 } chunk_info;
3691
3692 typedef struct {
3693 grn_log_level log_level;
3694 const char *tag;
3695 grn_ii *ii;
3696 const uint8_t *chunk;
3697 buffer_term *term;
3698 uint16_t nth_term;
3699 uint16_t n_terms;
3700 uint32_t nth_chunk;
3701 uint32_t n_chunks;
3702 datavec data_vector[MAX_N_ELEMENTS + 1];
3703 char name[GRN_TABLE_MAX_KEY_SIZE];
3704 int name_size;
3705 grn_obj inspected_term;
3706 grn_obj inspected_entries;
3707 uint32_t n_inspected_entries;
3708 } merge_dump_source_data;
3709
3710 #define MERGE_DUMP_SOURCE_BATCH_SIZE 10
3711
3712 typedef enum {
3713 MERGE_DUMP_SOURCE_ENTRY_BUFFER,
3714 MERGE_DUMP_SOURCE_ENTRY_CHUNK,
3715 } merge_dump_source_entry_type;
3716
3717 static void
3718 merge_dump_source_flush_entries(grn_ctx *ctx, merge_dump_source_data *data)
3719 {
3720 if (GRN_TEXT_LEN(&(data->inspected_entries)) == 0) {
3721 return;
3722 }
3723
3724 GRN_LOG(ctx,
3725 data->log_level,
3726 "%.*s",
3727 (int)GRN_TEXT_LEN(&(data->inspected_entries)),
3728 GRN_TEXT_VALUE(&(data->inspected_entries)));
3729 GRN_BULK_REWIND(&(data->inspected_entries));
3730 data->n_inspected_entries = 0;
3731 }
3732
3733 static void
3734 merge_dump_source_add_entry(grn_ctx *ctx,
3735 merge_dump_source_data *data,
3736 merge_dump_source_entry_type type,
3737 docinfo *info,
3738 uint8_t *position_gaps)
3739 {
3740 if (GRN_TEXT_LEN(&(data->inspected_entries)) > 0) {
3741 GRN_TEXT_PUTC(ctx, &(data->inspected_entries), ' ');
3742 }
3743 grn_text_printf(ctx,
3744 &(data->inspected_entries),
3745 "(%u:%u:%u:%u)",
3746 info->rid,
3747 info->sid,
3748 info->tf,
3749 info->weight);
3750 if (data->ii->header.common->flags & GRN_OBJ_WITH_POSITION) {
3751 uint32_t i;
3752 uint32_t position = 0;
3753
3754 GRN_TEXT_PUTC(ctx, &(data->inspected_entries), '[');
3755 for (i = 0; i < info->tf; i++) {
3756 uint32_t position_gap;
3757
3758 if (i > 0) {
3759 GRN_TEXT_PUTC(ctx, &(data->inspected_entries), ',');
3760 }
3761 if (type == MERGE_DUMP_SOURCE_ENTRY_BUFFER) {
3762 GRN_B_DEC(position_gap, position_gaps);
3763 } else {
3764 position_gap = ((uint32_t *)position_gaps)[i];
3765 }
3766 position += position_gap;
3767 grn_text_printf(ctx, &(data->inspected_entries), "%u", position);
3768 }
3769 GRN_TEXT_PUTC(ctx, &(data->inspected_entries), ']');
3770 }
3771 data->n_inspected_entries++;
3772 if (data->n_inspected_entries == MERGE_DUMP_SOURCE_BATCH_SIZE) {
3773 merge_dump_source_flush_entries(ctx, data);
3774 }
3775 }
3776
3777 static void
3778 merge_dump_source_chunk_raw(grn_ctx *ctx,
3779 merge_dump_source_data *data,
3780 const uint8_t *chunk_start,
3781 const uint8_t *chunk_end)
3782 {
3783 const uint8_t *chunk_current = chunk_start;
3784 int decoded_size;
3785
3786 if ((chunk_end - chunk_current) == 0) {
3787 GRN_LOG(ctx,
3788 data->log_level,
3789 "%s[%.*s][%d/%d] <%.*s>(%u): %u/%u: no data",
3790 data->tag,
3791 data->name_size,
3792 data->name,
3793 data->nth_term,
3794 data->n_terms,
3795 (int)GRN_TEXT_LEN(&(data->inspected_term)),
3796 GRN_TEXT_VALUE(&(data->inspected_term)),
3797 CHUNK_SPLIT_OFF(data->term->tid),
3798 data->nth_chunk,
3799 data->n_chunks);
3800 return;
3801 }
3802
3803 decoded_size = grn_decv(ctx,
3804 data->ii,
3805 CHUNK_SPLIT_OFF(data->term->tid),
3806 chunk_current,
3807 chunk_end - chunk_current,
3808 data->data_vector);
3809 if (decoded_size == 0) {
3810 GRN_LOG(ctx,
3811 data->log_level,
3812 "%s[%.*s][%d/%d] <%.*s>(%u): %u/%u: failed to decode",
3813 data->tag,
3814 data->name_size,
3815 data->name,
3816 data->nth_term,
3817 data->n_terms,
3818 (int)GRN_TEXT_LEN(&(data->inspected_term)),
3819 GRN_TEXT_VALUE(&(data->inspected_term)),
3820 CHUNK_SPLIT_OFF(data->term->tid),
3821 data->nth_chunk,
3822 data->n_chunks);
3823 return;
3824 }
3825
3826 {
3827 uint32_t n_documents;
3828 const uint32_t *record_id_gaps;
3829 const uint32_t *section_id_gaps = NULL;
3830 const uint32_t *n_terms_list;
3831 const uint32_t *weights = NULL;
3832 const uint32_t *position_gaps = NULL;
3833
3834 {
3835 int i = 0;
3836 n_documents = data->data_vector[i].data_size;
3837 record_id_gaps = data->data_vector[i++].data;
3838 if (data->ii->header.common->flags & GRN_OBJ_WITH_SECTION) {
3839 section_id_gaps = data->data_vector[i++].data;
3840 }
3841 n_terms_list = data->data_vector[i++].data;
3842 if (data->ii->header.common->flags & GRN_OBJ_WITH_WEIGHT) {
3843 weights = data->data_vector[i++].data;
3844 }
3845 if (data->ii->header.common->flags & GRN_OBJ_WITH_POSITION) {
3846 position_gaps = data->data_vector[i++].data;
3847 }
3848 }
3849
3850 {
3851 uint32_t i;
3852 grn_id record_id = GRN_ID_NIL;
3853 uint32_t section_id = 0;
3854
3855 for (i = 0; i < n_documents; i++) {
3856 uint32_t record_id_gap = record_id_gaps[i];
3857 docinfo info;
3858
3859 record_id += record_id_gap;
3860 info.rid = record_id;
3861 if (data->ii->header.common->flags & GRN_OBJ_WITH_SECTION) {
3862 if (record_id_gap > 0) {
3863 section_id = 0;
3864 }
3865 section_id += 1 + section_id_gaps[i];
3866 } else {
3867 section_id = 1;
3868 }
3869 info.sid = section_id;
3870 info.tf = 1 + n_terms_list[i];
3871 if (data->ii->header.common->flags & GRN_OBJ_WITH_WEIGHT) {
3872 info.weight = weights[i];
3873 } else {
3874 info.weight = 0;
3875 }
3876
3877 merge_dump_source_add_entry(ctx,
3878 data,
3879 MERGE_DUMP_SOURCE_ENTRY_CHUNK,
3880 &info,
3881 (uint8_t *)position_gaps);
3882 }
3883 merge_dump_source_flush_entries(ctx, data);
3884 }
3885 }
3886 }
3887
3888 static void
3889 merge_dump_source_chunk(grn_ctx *ctx, merge_dump_source_data *data)
3890 {
3891 const uint8_t *chunk_start = data->chunk + data->term->pos_in_chunk;
3892 const uint8_t *chunk_end = chunk_start + data->term->size_in_chunk;
3893
3894 if (data->term->tid & CHUNK_SPLIT) {
3895 const uint8_t *chunk_current = chunk_start;
3896
3897 GRN_B_DEC(data->n_chunks, chunk_current);
3898 GRN_LOG(ctx,
3899 data->log_level,
3900 "%s[%.*s][%d/%d] <%.*s>(%u): chunk: %u",
3901 data->tag,
3902 data->name_size,
3903 data->name,
3904 data->nth_term,
3905 data->n_terms,
3906 (int)GRN_TEXT_LEN(&(data->inspected_term)),
3907 GRN_TEXT_VALUE(&(data->inspected_term)),
3908 CHUNK_SPLIT_OFF(data->term->tid),
3909 data->n_chunks);
3910
3911 for (data->nth_chunk = 0; data->nth_chunk < data->n_chunks;
3912 data->nth_chunk++) {
3913 chunk_info info;
3914
3915 if (!(chunk_current < chunk_end)) {
3916 GRN_LOG(ctx,
3917 data->log_level,
3918 "%s[%.*s][%d/%d] <%.*s>(%u): chunk: %u/%u: no data",
3919 data->tag,
3920 data->name_size,
3921 data->name,
3922 data->nth_term,
3923 data->n_terms,
3924 (int)GRN_TEXT_LEN(&(data->inspected_term)),
3925 GRN_TEXT_VALUE(&(data->inspected_term)),
3926 CHUNK_SPLIT_OFF(data->term->tid),
3927 data->nth_chunk,
3928 data->n_chunks);
3929 return;
3930 }
3931
3932 GRN_B_DEC(info.segno, chunk_current);
3933 GRN_B_DEC(info.size, chunk_current);
3934 GRN_B_DEC(info.dgap, chunk_current);
3935
3936 GRN_LOG(ctx,
3937 data->log_level,
3938 "%s[%.*s][%d/%d] <%.*s>(%u): chunk: %u/%u: "
3939 "segment:<%d>, size:<%d>, gap:<%d>",
3940 data->tag,
3941 data->name_size,
3942 data->name,
3943 data->nth_term,
3944 data->n_terms,
3945 (int)GRN_TEXT_LEN(&(data->inspected_term)),
3946 GRN_TEXT_VALUE(&(data->inspected_term)),
3947 CHUNK_SPLIT_OFF(data->term->tid),
3948 data->nth_chunk,
3949 data->n_chunks,
3950 info.segno,
3951 info.size,
3952 info.dgap);
3953 if (info.size == 0) {
3954 continue;
3955 }
3956 {
3957 grn_io_win iw;
3958 auto sub_chunk = static_cast<uint8_t *>(WIN_MAP(ctx,
3959 data->ii->chunk,
3960 &iw,
3961 info.segno,
3962 0,
3963 info.size,
3964 GRN_IO_RDONLY));
3965 if (!sub_chunk) {
3966 GRN_LOG(ctx,
3967 data->log_level,
3968 "%s[%.*s][%d/%d] <%.*s>(%u): chunk: "
3969 "%u/%u: failed to open sub chunk",
3970 data->tag,
3971 data->name_size,
3972 data->name,
3973 data->nth_term,
3974 data->n_terms,
3975 (int)GRN_TEXT_LEN(&(data->inspected_term)),
3976 GRN_TEXT_VALUE(&(data->inspected_term)),
3977 CHUNK_SPLIT_OFF(data->term->tid),
3978 data->nth_chunk,
3979 data->n_chunks);
3980 continue;
3981 }
3982 merge_dump_source_chunk_raw(ctx,
3983 data,
3984 sub_chunk,
3985 sub_chunk + info.size);
3986 grn_io_win_unmap(ctx, &iw);
3987 }
3988 }
3989 if (chunk_current < chunk_end) {
3990 GRN_LOG(ctx,
3991 data->log_level,
3992 "%s[%.*s][%d/%d] <%.*s>(%u): chunk: %u",
3993 data->tag,
3994 data->name_size,
3995 data->name,
3996 data->nth_term,
3997 data->n_terms,
3998 (int)GRN_TEXT_LEN(&(data->inspected_term)),
3999 GRN_TEXT_VALUE(&(data->inspected_term)),
4000 CHUNK_SPLIT_OFF(data->term->tid),
4001 data->n_chunks);
4002 merge_dump_source_chunk_raw(ctx, data, chunk_current, chunk_end);
4003 }
4004 } else {
4005 data->nth_chunk = 0;
4006 data->n_chunks = 0;
4007 GRN_LOG(ctx,
4008 data->log_level,
4009 "%s[%.*s][%d/%d] <%.*s>(%u): chunk: %u",
4010 data->tag,
4011 data->name_size,
4012 data->name,
4013 data->nth_term,
4014 data->n_terms,
4015 (int)GRN_TEXT_LEN(&(data->inspected_term)),
4016 GRN_TEXT_VALUE(&(data->inspected_term)),
4017 data->term->tid,
4018 data->n_chunks);
4019 merge_dump_source_chunk_raw(ctx, data, chunk_start, chunk_end);
4020 }
4021 }
4022
4023 static void
4024 merge_dump_source(grn_ctx *ctx,
4025 grn_ii *ii,
4026 buffer *buf,
4027 const uint8_t *chunk,
4028 grn_log_level log_level)
4029 {
4030 merge_dump_source_data data;
4031
4032 if (!grn_logger_pass(ctx, log_level)) {
4033 return;
4034 }
4035
4036 data.log_level = log_level;
4037 data.tag = "[ii][merge][source]";
4038 data.ii = ii;
4039 data.chunk = chunk;
4040 data.term = NULL;
4041 data.nth_term = 0;
4042 data.n_terms = buf->header.nterms;
4043 data.nth_chunk = 0;
4044 data.n_chunks = 0;
4045 datavec_init(ctx, ii, data.data_vector, 0, 0);
4046 {
4047 GRN_DEFINE_NAME(ii);
4048 grn_memcpy(data.name, name, name_size);
4049 data.name_size = name_size;
4050 }
4051 GRN_TEXT_INIT(&(data.inspected_term), 0);
4052 GRN_TEXT_INIT(&(data.inspected_entries), 0);
4053 data.n_inspected_entries = 0;
4054
4055 GRN_LOG(ctx,
4056 data.log_level,
4057 "%s[%.*s] %u",
4058 data.tag,
4059 data.name_size,
4060 data.name,
4061 data.n_terms);
4062 for (data.nth_term = 0; data.nth_term < data.n_terms; data.nth_term++) {
4063 uint16_t position;
4064
4065 data.term = buf->terms + data.nth_term;
4066 if (data.term->tid == 0) {
4067 GRN_LOG(ctx,
4068 data.log_level,
4069 "%s[%.*s][%d] void",
4070 data.tag,
4071 data.name_size,
4072 data.name,
4073 data.nth_term);
4074 continue;
4075 }
4076
4077 GRN_BULK_REWIND(&(data.inspected_term));
4078 grn_ii_get_term(ctx,
4079 ii,
4080 CHUNK_SPLIT_OFF(data.term->tid),
4081 &(data.inspected_term));
4082 GRN_LOG(ctx,
4083 data.log_level,
4084 "%s[%.*s][%d/%d] <%.*s>(%u): chunk:<%u:%u>, buffer:<%u:%u>",
4085 data.tag,
4086 data.name_size,
4087 data.name,
4088 data.nth_term,
4089 data.n_terms,
4090 (int)GRN_TEXT_LEN(&(data.inspected_term)),
4091 GRN_TEXT_VALUE(&(data.inspected_term)),
4092 CHUNK_SPLIT_OFF(data.term->tid),
4093 data.term->pos_in_chunk,
4094 data.term->size_in_chunk,
4095 data.term->pos_in_buffer,
4096 data.term->size_in_buffer);
4097
4098 position = data.term->pos_in_buffer;
4099 while (position > 0) {
4100 buffer_rec *record = BUFFER_REC_AT(buf, position);
4101 uint8_t *record_data = GRN_NEXT_ADDR(record);
4102 docinfo info;
4103
4104 grn_text_printf(ctx,
4105 &(data.inspected_entries),
4106 "record: %u: <%u:%u%s>",
4107 position,
4108 record->step,
4109 record->jump,
4110 BUFFER_REC_DELETED(record) ? ":deleted" : "");
4111
4112 position = record->step;
4113
4114 if (BUFFER_REC_DELETED(record)) {
4115 merge_dump_source_flush_entries(ctx, &data);
4116 continue;
4117 }
4118
4119 GRN_TEXT_PUTC(ctx, &(data.inspected_entries), ':');
4120
4121 GRN_B_DEC(info.rid, record_data);
4122 if (ii->header.common->flags & GRN_OBJ_WITH_SECTION) {
4123 GRN_B_DEC(info.sid, record_data);
4124 } else {
4125 info.sid = 1;
4126 }
4127 GRN_B_DEC(info.tf, record_data);
4128 if (ii->header.common->flags & GRN_OBJ_WITH_WEIGHT) {
4129 GRN_B_DEC(info.weight, record_data);
4130 } else {
4131 info.weight = 0;
4132 }
4133 merge_dump_source_add_entry(ctx,
4134 &data,
4135 MERGE_DUMP_SOURCE_ENTRY_BUFFER,
4136 &info,
4137 record_data);
4138 merge_dump_source_flush_entries(ctx, &data);
4139 }
4140
4141 if (chunk && data.term->size_in_chunk > 0) {
4142 merge_dump_source_chunk(ctx, &data);
4143 }
4144 }
4145
4146 datavec_fin(ctx, data.data_vector);
4147 GRN_OBJ_FIN(ctx, &(data.inspected_term));
4148 GRN_OBJ_FIN(ctx, &(data.inspected_entries));
4149 }
4150
4151 typedef struct {
4152 grn_ii *ii;
4153 bool succeeded;
4154 grn_obj source_chunks;
4155 grn_obj dest_chunks;
4156 } grn_merging_data;
4157
4158 static void
4159 grn_merging_data_init(grn_ctx *ctx, grn_merging_data *data, grn_ii *ii)
4160 {
4161 data->ii = ii;
4162 data->succeeded = false;
4163 GRN_UINT32_INIT(&(data->source_chunks), GRN_OBJ_VECTOR);
4164 GRN_UINT32_INIT(&(data->dest_chunks), GRN_OBJ_VECTOR);
4165 }
4166
4167 static void
4168 grn_merging_data_fin(grn_ctx *ctx, grn_merging_data *data)
4169 {
4170 grn_obj *target_chunks;
4171 if (data->succeeded) {
4172 target_chunks = &(data->source_chunks);
4173 } else {
4174 target_chunks = &(data->dest_chunks);
4175 }
4176 const size_t n_target_chunks = GRN_UINT32_VECTOR_SIZE(target_chunks) / 2;
4177 size_t i;
4178 for (i = 0; i < n_target_chunks; i++) {
4179 const uint32_t segno = GRN_UINT32_VALUE_AT(target_chunks, i * 2);
4180 const uint32_t size = GRN_UINT32_VALUE_AT(target_chunks, i * 2 + 1);
4181 chunk_free(ctx, data->ii, segno, size);
4182 }
4183 GRN_OBJ_FIN(ctx, &(data->source_chunks));
4184 GRN_OBJ_FIN(ctx, &(data->dest_chunks));
4185 }
4186
4187 static void
4188 grn_merging_data_add_source_chunk(grn_ctx *ctx,
4189 grn_merging_data *data,
4190 uint32_t segno,
4191 uint32_t size)
4192 {
4193 GRN_UINT32_PUT(ctx, &(data->source_chunks), segno);
4194 GRN_UINT32_PUT(ctx, &(data->source_chunks), size);
4195 }
4196
4197 static void
4198 grn_merging_data_add_dest_chunk(grn_ctx *ctx,
4199 grn_merging_data *data,
4200 uint32_t segno,
4201 uint32_t size)
4202 {
4203 GRN_UINT32_PUT(ctx, &(data->dest_chunks), segno);
4204 GRN_UINT32_PUT(ctx, &(data->dest_chunks), size);
4205 }
4206
4207 typedef struct {
4208 buffer *buf;
4209 const uint8_t *data;
4210 docinfo id;
4211 uint16_t next_position;
4212 } merger_buffer_data;
4213
4214 typedef struct {
4215 const uint8_t *data_start;
4216 const uint8_t *data_end;
4217 const uint8_t *data;
4218 docinfo id;
4219 uint32_t n_documents;
4220 const uint32_t *record_id_gaps;
4221 const uint32_t *section_id_gaps;
4222 const uint32_t *tfs;
4223 const uint32_t *weights;
4224 const uint32_t *position_gaps;
4225 const uint32_t *position_gaps_end;
4226 } merger_chunk_data;
4227
4228 typedef struct {
4229 grn_ii *ii;
4230 grn_id term_id;
4231 docinfo last_id;
4232 uint64_t position;
4233 uint64_t max_position;
4234 grn_merging_data *merging_data;
4235 struct {
4236 merger_buffer_data buffer;
4237 merger_chunk_data chunk;
4238 } source;
4239 struct {
4240 uint32_t *record_id_gaps;
4241 uint32_t *section_id_gaps;
4242 uint32_t *tfs;
4243 uint32_t *weights;
4244 uint32_t *position_gaps;
4245 uint32_t *position_gaps_end;
4246 } dest;
4247 } merger_data;
4248
4249 static inline void
4250 merger_init_chunk_data(grn_ctx *ctx, merger_data *data, datavec *rdv)
4251 {
4252 merger_chunk_data *chunk_data = &(data->source.chunk);
4253 grn_ii *ii = data->ii;
4254 int j = 0;
4255 memset(&(chunk_data->id), 0, sizeof(docinfo));
4256 chunk_data->n_documents = rdv[j].data_size;
4257 chunk_data->record_id_gaps = rdv[j++].data;
4258 if ((ii->header.common->flags & GRN_OBJ_WITH_SECTION)) {
4259 chunk_data->section_id_gaps = rdv[j++].data;
4260 }
4261 chunk_data->tfs = rdv[j++].data;
4262 if ((ii->header.common->flags & GRN_OBJ_WITH_WEIGHT)) {
4263 chunk_data->weights = rdv[j++].data;
4264 }
4265 chunk_data->position_gaps = rdv[j].data;
4266 chunk_data->position_gaps_end = chunk_data->position_gaps + rdv[j].data_size;
4267 }
4268
4269 static inline void
4270 merger_report_error(grn_ctx *ctx,
4271 merger_data *data,
4272 const char *message,
4273 docinfo *posting1,
4274 docinfo *posting2)
4275 {
4276 merger_buffer_data *buffer_data = &(data->source.buffer);
4277 merger_chunk_data *chunk_data = &(data->source.chunk);
4278 grn_obj term;
4279 GRN_DEFINE_NAME(data->ii);
4280 GRN_TEXT_INIT(&term, 0);
4281 grn_ii_get_term(ctx, data->ii, CHUNK_SPLIT_OFF(data->term_id), &term);
4282 if (posting1 && posting2) {
4283 CRIT(GRN_FILE_CORRUPT,
4284 "[ii][broken] %s: <%.*s>: <%.*s>(%u): (%u:%u) -> (%u:%u)",
4285 message,
4286 name_size,
4287 name,
4288 (int)GRN_TEXT_LEN(&term),
4289 GRN_TEXT_VALUE(&term),
4290 CHUNK_SPLIT_OFF(data->term_id),
4291 posting1->rid,
4292 posting1->sid,
4293 posting2->rid,
4294 posting2->sid);
4295 } else {
4296 CRIT(GRN_FILE_CORRUPT,
4297 "[ii][broken] %s: <%.*s>: <%.*s>(%u): (%u:%u)",
4298 message,
4299 name_size,
4300 name,
4301 (int)GRN_TEXT_LEN(&term),
4302 GRN_TEXT_VALUE(&term),
4303 CHUNK_SPLIT_OFF(data->term_id),
4304 posting1->rid,
4305 posting1->sid);
4306 }
4307 GRN_OBJ_FIN(ctx, &term);
4308 merge_dump_source(ctx,
4309 data->ii,
4310 buffer_data->buf,
4311 chunk_data->data_start,
4312 GRN_LOG_CRIT);
4313 }
4314
4315 static inline void
4316 merger_get_next_chunk(grn_ctx *ctx, merger_data *data)
4317 {
4318 merger_chunk_data *chunk_data = &(data->source.chunk);
4319 if (chunk_data->n_documents == 0) {
4320 chunk_data->id.rid = 0;
4321 } else {
4322 uint32_t record_id_gap = *chunk_data->record_id_gaps;
4323 chunk_data->record_id_gaps++;
4324 chunk_data->id.rid += record_id_gap;
4325 if (record_id_gap > 0) {
4326 chunk_data->id.sid = 0;
4327 }
4328 chunk_data->position_gaps += chunk_data->id.tf;
4329 chunk_data->id.tf = 1 + *chunk_data->tfs;
4330 chunk_data->tfs++;
4331 if ((data->ii->header.common->flags & GRN_OBJ_WITH_WEIGHT)) {
4332 chunk_data->id.weight = *chunk_data->weights;
4333 chunk_data->weights++;
4334 }
4335 if ((data->ii->header.common->flags & GRN_OBJ_WITH_SECTION)) {
4336 chunk_data->id.sid += 1 + *chunk_data->section_id_gaps;
4337 chunk_data->section_id_gaps++;
4338 } else {
4339 chunk_data->id.sid = 1;
4340 }
4341 chunk_data->n_documents--;
4342 }
4343 }
4344
4345 static inline void
4346 merger_put_next_id(grn_ctx *ctx, merger_data *data, docinfo *id)
4347 {
4348 uint32_t record_id_gap = id->rid - data->last_id.rid;
4349 *(data->dest.record_id_gaps) = record_id_gap;
4350 data->dest.record_id_gaps++;
4351 if ((data->ii->header.common->flags & GRN_OBJ_WITH_SECTION)) {
4352 uint32_t section_id_gap;
4353 if (record_id_gap > 0) {
4354 section_id_gap = id->sid - 1;
4355 } else {
4356 section_id_gap = id->sid - data->last_id.sid - 1;
4357 }
4358 *(data->dest.section_id_gaps) = section_id_gap;
4359 data->dest.section_id_gaps++;
4360 }
4361 *(data->dest.tfs) = id->tf - 1;
4362 data->dest.tfs++;
4363 if ((data->ii->header.common->flags & GRN_OBJ_WITH_WEIGHT)) {
4364 *(data->dest.weights) = id->weight;
4365 data->dest.weights++;
4366 }
4367 data->last_id.rid = id->rid;
4368 data->last_id.sid = id->sid;
4369 }
4370
4371 static inline void
4372 merger_put_next_chunk(grn_ctx *ctx, merger_data *data)
4373 {
4374 merger_chunk_data *chunk_data = &(data->source.chunk);
4375 if (chunk_data->id.rid > 0) {
4376 if (chunk_data->id.tf > 0) {
4377 if (data->last_id.rid > chunk_data->id.rid ||
4378 (data->last_id.rid == chunk_data->id.rid &&
4379 data->last_id.sid >= chunk_data->id.sid)) {
4380 merger_report_error(ctx,
4381 data,
4382 "the last posting is larger than "
4383 "the next posting in chunk",
4384 &(data->last_id),
4385 &(chunk_data->id));
4386 return;
4387 }
4388 merger_put_next_id(ctx, data, &(chunk_data->id));
4389 if ((data->ii->header.common->flags & GRN_OBJ_WITH_POSITION)) {
4390 uint32_t i;
4391 uint32_t rest_n_positions =
4392 (uint32_t)(chunk_data->position_gaps_end - chunk_data->position_gaps);
4393 uint32_t rest_n_dest_positions =
4394 (uint32_t)(data->dest.position_gaps_end - data->dest.position_gaps);
4395 if (chunk_data->id.tf > rest_n_positions) {
4396 grn_obj term;
4397 GRN_DEFINE_NAME(data->ii);
4398 GRN_TEXT_INIT(&term, 0);
4399 grn_ii_get_term(ctx, data->ii, CHUNK_SPLIT_OFF(data->term_id), &term);
4400 GRN_LOG(
4401 ctx,
4402 GRN_LOG_WARNING,
4403 "[ii][merge][put][chunk] "
4404 "the number of terms are larger than the number of positions: "
4405 "<%.*s>: <%.*s>(%u): (%u:%u): (%u:%u)",
4406 name_size,
4407 name,
4408 (int)GRN_TEXT_LEN(&term),
4409 GRN_TEXT_VALUE(&term),
4410 CHUNK_SPLIT_OFF(data->term_id),
4411 chunk_data->id.rid,
4412 chunk_data->id.sid,
4413 chunk_data->id.tf,
4414 rest_n_positions);
4415 GRN_OBJ_FIN(ctx, &term);
4416 }
4417 if (chunk_data->id.tf > rest_n_dest_positions) {
4418 /* TODO: Make this case error. */
4419 grn_obj term;
4420 GRN_DEFINE_NAME(data->ii);
4421 GRN_TEXT_INIT(&term, 0);
4422 grn_ii_get_term(ctx, data->ii, CHUNK_SPLIT_OFF(data->term_id), &term);
4423 GRN_LOG(ctx,
4424 GRN_LOG_WARNING,
4425 "[ii][merge][put][chunk] "
4426 "the number of terms are larger than "
4427 "the rest destination number of positions: "
4428 "<%.*s>: <%.*s>(%u): (%u:%u): (%u:%u)",
4429 name_size,
4430 name,
4431 (int)GRN_TEXT_LEN(&term),
4432 GRN_TEXT_VALUE(&term),
4433 CHUNK_SPLIT_OFF(data->term_id),
4434 chunk_data->id.rid,
4435 chunk_data->id.sid,
4436 chunk_data->id.tf,
4437 rest_n_dest_positions);
4438 GRN_OBJ_FIN(ctx, &term);
4439 }
4440 for (i = 0; i < chunk_data->id.tf; i++) {
4441 *(data->dest.position_gaps) = chunk_data->position_gaps[i];
4442 data->dest.position_gaps++;
4443 data->position += chunk_data->position_gaps[i];
4444 }
4445 if (data->position > data->max_position) {
4446 data->max_position = data->position;
4447 }
4448 }
4449 } else {
4450 merger_report_error(ctx,
4451 data,
4452 "invalid posting in chunk",
4453 &(chunk_data->id),
4454 NULL);
4455 return;
4456 }
4457 }
4458 merger_get_next_chunk(ctx, data);
4459 }
4460
4461 static inline void
4462 merger_get_next_buffer(grn_ctx *ctx, merger_data *data)
4463 {
4464 merger_buffer_data *buffer_data = &(data->source.buffer);
4465 if (buffer_data->next_position == 0) {
4466 buffer_data->id.rid = 0;
4467 } else {
4468 docinfo last_id = {buffer_data->id.rid, buffer_data->id.sid, 0, 0, 0};
4469 buffer_rec *record =
4470 BUFFER_REC_AT(buffer_data->buf, buffer_data->next_position);
4471 buffer_data->data = GRN_NEXT_ADDR(record);
4472 GRN_B_DEC(buffer_data->id.rid, buffer_data->data);
4473 if ((data->ii->header.common->flags & GRN_OBJ_WITH_SECTION)) {
4474 GRN_B_DEC(buffer_data->id.sid, buffer_data->data);
4475 } else {
4476 buffer_data->id.sid = 1;
4477 }
4478 if (last_id.rid > buffer_data->id.rid ||
4479 (last_id.rid == buffer_data->id.rid &&
4480 last_id.sid >= buffer_data->id.sid)) {
4481 merger_report_error(ctx,
4482 data,
4483 "postings in block aren't sorted",
4484 &last_id,
4485 &(buffer_data->id));
4486 return;
4487 }
4488 buffer_data->next_position = record->step;
4489 }
4490 }
4491
4492 static inline void
4493 merger_put_next_buffer(grn_ctx *ctx, merger_data *data)
4494 {
4495 merger_buffer_data *buffer_data = &(data->source.buffer);
4496 if (buffer_data->id.rid > 0 && buffer_data->id.sid > 0) {
4497 GRN_B_DEC(buffer_data->id.tf, buffer_data->data);
4498 if (buffer_data->id.tf > 0) {
4499 if (data->last_id.rid > buffer_data->id.rid ||
4500 (data->last_id.rid == buffer_data->id.rid &&
4501 data->last_id.sid >= buffer_data->id.sid)) {
4502 merger_report_error(ctx,
4503 data,
4504 "the last posting is larger than "
4505 "the next posting in buffer",
4506 &(data->last_id),
4507 &(buffer_data->id));
4508 return;
4509 }
4510 if ((data->ii->header.common->flags & GRN_OBJ_WITH_WEIGHT)) {
4511 GRN_B_DEC(buffer_data->id.weight, buffer_data->data);
4512 }
4513 merger_put_next_id(ctx, data, &(buffer_data->id));
4514 if ((data->ii->header.common->flags & GRN_OBJ_WITH_POSITION)) {
4515 uint32_t rest_n_dest_positiongs =
4516 (uint32_t)(data->dest.position_gaps_end - data->dest.position_gaps);
4517 if (buffer_data->id.tf > rest_n_dest_positiongs) {
4518 /* TODO: Make this case error. */
4519 merger_buffer_data *buffer_data = &(data->source.buffer);
4520 grn_obj term;
4521 GRN_DEFINE_NAME(data->ii);
4522 GRN_TEXT_INIT(&term, 0);
4523 grn_ii_get_term(ctx, data->ii, CHUNK_SPLIT_OFF(data->term_id), &term);
4524 GRN_LOG(ctx,
4525 GRN_LOG_WARNING,
4526 "[ii][merge][put][buffer] "
4527 "the number of terms are larger than "
4528 "the rest destination number of positions: "
4529 "<%.*s>: <%.*s>(%u): (%u:%u): (%u:%u)",
4530 name_size,
4531 name,
4532 (int)GRN_TEXT_LEN(&term),
4533 GRN_TEXT_VALUE(&term),
4534 CHUNK_SPLIT_OFF(data->term_id),
4535 buffer_data->id.rid,
4536 buffer_data->id.sid,
4537 buffer_data->id.tf,
4538 rest_n_dest_positiongs);
4539 GRN_OBJ_FIN(ctx, &term);
4540 }
4541 while (buffer_data->id.tf--) {
4542 GRN_B_DEC(*(data->dest.position_gaps), buffer_data->data);
4543 data->position += *(data->dest.position_gaps);
4544 data->dest.position_gaps++;
4545 }
4546 if (data->position > data->max_position) {
4547 data->max_position = data->position;
4548 }
4549 }
4550 }
4551 }
4552 merger_get_next_buffer(ctx, data);
4553 }
4554
4555 static inline bool
4556 merger_merge(grn_ctx *ctx, merger_data *data)
4557 {
4558 merger_buffer_data *buffer_data = &(data->source.buffer);
4559 merger_chunk_data *chunk_data = &(data->source.chunk);
4560 if (buffer_data->id.rid > 0) {
4561 if (chunk_data->id.rid > 0) {
4562 if (chunk_data->id.rid < buffer_data->id.rid) {
4563 merger_put_next_chunk(ctx, data);
4564 if (ctx->rc != GRN_SUCCESS) {
4565 return false;
4566 }
4567 } else {
4568 if (buffer_data->id.rid < chunk_data->id.rid) {
4569 merger_put_next_buffer(ctx, data);
4570 if (ctx->rc != GRN_SUCCESS) {
4571 return false;
4572 }
4573 } else {
4574 if (buffer_data->id.sid > 0) {
4575 if (chunk_data->id.sid < buffer_data->id.sid) {
4576 merger_put_next_chunk(ctx, data);
4577 if (ctx->rc != GRN_SUCCESS) {
4578 return false;
4579 }
4580 } else {
4581 if (buffer_data->id.sid == chunk_data->id.sid) {
4582 merger_get_next_chunk(ctx, data);
4583 if (ctx->rc != GRN_SUCCESS) {
4584 return false;
4585 }
4586 }
4587 merger_put_next_buffer(ctx, data);
4588 if (ctx->rc != GRN_SUCCESS) {
4589 return false;
4590 }
4591 }
4592 } else {
4593 merger_get_next_chunk(ctx, data);
4594 if (ctx->rc != GRN_SUCCESS) {
4595 return false;
4596 }
4597 }
4598 }
4599 }
4600 } else {
4601 merger_put_next_buffer(ctx, data);
4602 if (ctx->rc != GRN_SUCCESS) {
4603 return false;
4604 }
4605 }
4606 } else {
4607 if (chunk_data->id.rid > 0) {
4608 merger_put_next_chunk(ctx, data);
4609 if (ctx->rc != GRN_SUCCESS) {
4610 return false;
4611 }
4612 } else {
4613 return false;
4614 }
4615 }
4616 return true;
4617 }
4618
4619 static grn_rc
4620 chunk_flush(
4621 grn_ctx *ctx, grn_ii *ii, chunk_info *cinfo, uint8_t *enc, uint32_t encsize)
4622 {
4623 uint32_t dcn;
4624 grn_io_win dw;
4625 if (encsize) {
4626 chunk_new(ctx, ii, &dcn, encsize);
4627 if (ctx->rc == GRN_SUCCESS) {
4628 auto dc = static_cast<uint8_t *>(
4629 WIN_MAP(ctx, ii->chunk, &dw, dcn, 0, encsize, GRN_IO_WRONLY));
4630 if (dc) {
4631 grn_memcpy(dc, enc, encsize);
4632 grn_io_win_unmap(ctx, &dw);
4633 cinfo->segno = dcn;
4634 cinfo->size = encsize;
4635 } else {
4636 chunk_free(ctx, ii, dcn, encsize);
4637 {
4638 GRN_DEFINE_NAME(ii);
4639 MERR("[ii][chunk][flush] failed to allocate a destination chunk: "
4640 "<%.*s>:"
4641 "segment:<%u>, size:<%u>",
4642 name_size,
4643 name,
4644 dcn,
4645 encsize);
4646 }
4647 }
4648 }
4649 } else {
4650 cinfo->segno = 0;
4651 cinfo->size = 0;
4652 }
4653 return ctx->rc;
4654 }
4655
4656 static grn_rc
4657 chunk_merge(grn_ctx *ctx,
4658 merger_data *data,
4659 chunk_info *cinfo,
4660 grn_id rid,
4661 datavec *dv,
4662 int32_t *balance)
4663 {
4664 merger_buffer_data *buffer_data = &(data->source.buffer);
4665 merger_chunk_data *chunk_data = &(data->source.chunk);
4666 grn_ii *ii = data->ii;
4667 grn_id term_id = CHUNK_SPLIT_OFF(data->term_id);
4668 grn_io_win sw;
4669 uint32_t segno = cinfo->segno;
4670 uint32_t size = cinfo->size;
4671 uint32_t ndf = 0;
4672 auto scp = static_cast<const uint8_t *>(
4673 WIN_MAP(ctx, ii->chunk, &sw, segno, 0, size, GRN_IO_RDONLY));
4674 datavec rdv[MAX_N_ELEMENTS + 1];
4675 size_t bufsize = S_SEGMENT * ii->n_elements;
4676
4677 if (!scp) {
4678 grn_obj term;
4679 GRN_DEFINE_NAME(ii);
4680 GRN_TEXT_INIT(&term, 0);
4681 grn_ii_get_term(ctx, ii, term_id, &term);
4682 MERR("[ii][chunk][merge] failed to allocate a source chunk: "
4683 "<%.*s>: "
4684 "<%.*s>(%u): "
4685 "record:<%u>, segment:<%u>, size:<%u>",
4686 name_size,
4687 name,
4688 (int)GRN_TEXT_LEN(&term),
4689 GRN_TEXT_VALUE(&term),
4690 term_id,
4691 rid,
4692 segno,
4693 size);
4694 GRN_OBJ_FIN(ctx, &term);
4695 return ctx->rc;
4696 }
4697
4698 data->last_id = null_docinfo;
4699 chunk_data->section_id_gaps = NULL;
4700 chunk_data->weights = NULL;
4701
4702 datavec_init(ctx, ii, rdv, 0, 0);
4703 if (ctx->rc != GRN_SUCCESS) {
4704 grn_io_win_unmap(ctx, &sw);
4705 {
4706 GRN_DEFINE_NAME(ii);
4707 ERR(ctx->rc,
4708 "[ii][chunk][merge] failed to initialize data vector: <%.*s>",
4709 name_size,
4710 name);
4711 }
4712 return ctx->rc;
4713 }
4714
4715 {
4716 int decoded_size;
4717 decoded_size = grn_decv(ctx, ii, term_id, scp, cinfo->size, rdv);
4718 if (decoded_size == 0) {
4719 grn_obj term;
4720 grn_rc rc = ctx->rc;
4721 GRN_DEFINE_NAME(ii);
4722 GRN_TEXT_INIT(&term, 0);
4723 grn_ii_get_term(ctx, ii, term_id, &term);
4724 if (rc == GRN_SUCCESS) {
4725 rc = GRN_UNKNOWN_ERROR;
4726 }
4727 ERR(rc,
4728 "[ii][chunk][merge] failed to decode: "
4729 "<%.*s>: "
4730 "<%.*s>(%u): "
4731 "<%u>: "
4732 "<%u>",
4733 name_size,
4734 name,
4735 (int)GRN_TEXT_LEN(&term),
4736 GRN_TEXT_VALUE(&term),
4737 term_id,
4738 rid,
4739 cinfo->size);
4740 GRN_OBJ_FIN(ctx, &term);
4741 goto exit;
4742 }
4743 bufsize += decoded_size;
4744 }
4745 merger_init_chunk_data(ctx, data, rdv);
4746 /* (df in chunk list) = a[1] - chunk_data->n_documents; */
4747 datavec_reset(ctx, ii, dv, chunk_data->n_documents + S_SEGMENT, bufsize);
4748 if (ctx->rc != GRN_SUCCESS) {
4749 grn_obj term;
4750 GRN_DEFINE_NAME(ii);
4751 GRN_TEXT_INIT(&term, 0);
4752 grn_ii_get_term(ctx, ii, term_id, &term);
4753 ERR(ctx->rc,
4754 "[ii][chunk][merge] failed to reset data vector: "
4755 "<%.*s>: "
4756 "<%.*s>(%u)",
4757 name_size,
4758 name,
4759 (int)GRN_TEXT_LEN(&term),
4760 GRN_TEXT_VALUE(&term),
4761 term_id);
4762 GRN_OBJ_FIN(ctx, &term);
4763 goto exit;
4764 }
4765 {
4766 int j = 0;
4767 data->dest.record_id_gaps = dv[j++].data;
4768 if ((ii->header.common->flags & GRN_OBJ_WITH_SECTION)) {
4769 data->dest.section_id_gaps = dv[j++].data;
4770 }
4771 data->dest.tfs = dv[j++].data;
4772 if ((ii->header.common->flags & GRN_OBJ_WITH_WEIGHT)) {
4773 data->dest.weights = dv[j++].data;
4774 }
4775 data->dest.position_gaps = dv[j++].data;
4776 data->dest.position_gaps_end = dv[j].data;
4777 }
4778 merger_get_next_chunk(ctx, data);
4779 if (ctx->rc != GRN_SUCCESS) {
4780 grn_obj term;
4781 GRN_DEFINE_NAME(ii);
4782 GRN_TEXT_INIT(&term, 0);
4783 grn_ii_get_term(ctx, ii, term_id, &term);
4784 ERR(ctx->rc,
4785 "[ii][chunk][merge] failed to get the next chunk posting: "
4786 "<%.*s>: "
4787 "<%.*s>(%u)",
4788 name_size,
4789 name,
4790 (int)GRN_TEXT_LEN(&term),
4791 GRN_TEXT_VALUE(&term),
4792 term_id);
4793 GRN_OBJ_FIN(ctx, &term);
4794 goto exit;
4795 }
4796 data->position = 0;
4797 do {
4798 if (!merger_merge(ctx, data)) {
4799 break;
4800 }
4801 } while (buffer_data->id.rid <= rid || chunk_data->id.rid);
4802 if (ctx->rc != GRN_SUCCESS) {
4803 grn_obj term;
4804 GRN_DEFINE_NAME(ii);
4805 GRN_TEXT_INIT(&term, 0);
4806 grn_ii_get_term(ctx, ii, term_id, &term);
4807 ERR(ctx->rc,
4808 "[ii][chunk][merge] failed to merge: "
4809 "<%.*s>: "
4810 "<%.*s>(%u)",
4811 name_size,
4812 name,
4813 (int)GRN_TEXT_LEN(&term),
4814 GRN_TEXT_VALUE(&term),
4815 term_id);
4816 GRN_OBJ_FIN(ctx, &term);
4817 goto exit;
4818 }
4819 ndf = data->dest.record_id_gaps - dv[0].data;
4820 {
4821 const uint32_t n_positions =
4822 data->dest.position_gaps - dv[ii->n_elements - 1].data;
4823 datavec_set_data_size(ctx,
4824 ii,
4825 dv,
4826 ndf,
4827 data->last_id.rid,
4828 n_positions,
4829 data->max_position);
4830 const ssize_t encsize_estimated = grn_encv(ctx, ii, term_id, dv, NULL, 0);
4831 if (encsize_estimated == -1) {
4832 grn_obj term;
4833 GRN_DEFINE_NAME(ii);
4834 GRN_TEXT_INIT(&term, 0);
4835 grn_ii_get_term(ctx, ii, term_id, &term);
4836 MERR("[ii][chunk][merge] failed to estimate encode buffer size: "
4837 "<%.*s>: "
4838 "<%.*s>(%u): "
4839 "record:<%u>, "
4840 "segment:<%u>, "
4841 "size:<%u>, "
4842 "estimated-buffer-size: <%" GRN_FMT_SSIZE ">",
4843 name_size,
4844 name,
4845 (int)GRN_TEXT_LEN(&term),
4846 GRN_TEXT_VALUE(&term),
4847 term_id,
4848 rid,
4849 segno,
4850 size,
4851 encsize_estimated);
4852 GRN_OBJ_FIN(ctx, &term);
4853 goto exit;
4854 }
4855 if (encsize_estimated == 0) {
4856 chunk_flush(ctx, ii, cinfo, NULL, 0);
4857 } else {
4858 auto enc = static_cast<uint8_t *>(GRN_MALLOC(encsize_estimated));
4859 if (!enc) {
4860 grn_obj term;
4861 GRN_DEFINE_NAME(ii);
4862 GRN_TEXT_INIT(&term, 0);
4863 grn_ii_get_term(ctx, ii, term_id, &term);
4864 MERR("[ii][chunk][merge] failed to allocate a encode buffer: "
4865 "<%.*s>: "
4866 "<%.*s>(%u): "
4867 "record:<%u>, "
4868 "segment:<%u>, "
4869 "size:<%u>, "
4870 "estimated-buffer-size: <%" GRN_FMT_SSIZE ">",
4871 name_size,
4872 name,
4873 (int)GRN_TEXT_LEN(&term),
4874 GRN_TEXT_VALUE(&term),
4875 term_id,
4876 rid,
4877 segno,
4878 size,
4879 encsize_estimated);
4880 GRN_OBJ_FIN(ctx, &term);
4881 goto exit;
4882 }
4883 const ssize_t encsize =
4884 grn_encv(ctx, ii, term_id, dv, enc, encsize_estimated);
4885 if (encsize == -1) {
4886 grn_obj term;
4887 GRN_DEFINE_NAME(ii);
4888 GRN_TEXT_INIT(&term, 0);
4889 grn_ii_get_term(ctx, ii, term_id, &term);
4890 MERR("[ii][chunk][merge] failed to encode: "
4891 "<%.*s>: "
4892 "<%.*s>(%u): "
4893 "record:<%u>, "
4894 "segment:<%u>, "
4895 "size:<%u>, "
4896 "estimated-buffer-size: <%" GRN_FMT_SSIZE ">",
4897 name_size,
4898 name,
4899 (int)GRN_TEXT_LEN(&term),
4900 GRN_TEXT_VALUE(&term),
4901 term_id,
4902 rid,
4903 segno,
4904 size,
4905 encsize_estimated);
4906 GRN_OBJ_FIN(ctx, &term);
4907 GRN_FREE(enc);
4908 goto exit;
4909 }
4910 chunk_flush(ctx, ii, cinfo, enc, encsize);
4911 if (ctx->rc == GRN_SUCCESS) {
4912 grn_merging_data_add_dest_chunk(ctx,
4913 data->merging_data,
4914 cinfo->segno,
4915 cinfo->size);
4916 }
4917 GRN_FREE(enc);
4918 }
4919 if (ctx->rc != GRN_SUCCESS) {
4920 goto exit;
4921 }
4922 grn_merging_data_add_source_chunk(ctx, data->merging_data, segno, size);
4923 }
4924 *balance += (ndf - chunk_data->n_documents);
4925
4926 exit:
4927 datavec_fin(ctx, rdv);
4928 grn_io_win_unmap(ctx, &sw);
4929
4930 return ctx->rc;
4931 }
4932
4933 static void
4934 buffer_merge_dump_datavec(grn_ctx *ctx, grn_ii *ii, datavec *dv, datavec *rdv)
4935 {
4936 uint32_t i, j;
4937 grn_obj buffer;
4938
4939 GRN_TEXT_INIT(&buffer, 0);
4940 for (i = 0; i < ii->n_elements; i++) {
4941 GRN_LOG(ctx,
4942 GRN_LOG_DEBUG,
4943 "rdv[%d] data_size=%d, flags=%d",
4944 i,
4945 rdv[i].data_size,
4946 rdv[i].flags);
4947 GRN_BULK_REWIND(&buffer);
4948 for (j = 0; j < rdv[i].data_size;) {
4949 grn_text_printf(ctx, &buffer, " %d", rdv[i].data[j]);
4950 j++;
4951 if (!(j % 32) || j == rdv[i].data_size) {
4952 GRN_LOG(ctx,
4953 GRN_LOG_DEBUG,
4954 "rdv[%d].data[%d]%.*s",
4955 i,
4956 j,
4957 (int)GRN_TEXT_LEN(&buffer),
4958 GRN_TEXT_VALUE(&buffer));
4959 GRN_BULK_REWIND(&buffer);
4960 }
4961 }
4962 }
4963
4964 for (i = 0; i < ii->n_elements; i++) {
4965 GRN_LOG(ctx,
4966 GRN_LOG_DEBUG,
4967 "dv[%d] data_size=%d, flags=%d",
4968 i,
4969 dv[i].data_size,
4970 dv[i].flags);
4971 GRN_BULK_REWIND(&buffer);
4972 for (j = 0; j < dv[i].data_size;) {
4973 grn_text_printf(ctx, &buffer, " %d", dv[i].data[j]);
4974 j++;
4975 if (!(j % 32) || j == dv[i].data_size) {
4976 GRN_LOG(ctx,
4977 GRN_LOG_DEBUG,
4978 "dv[%d].data[%d]%.*s",
4979 i,
4980 j,
4981 (int)GRN_TEXT_LEN(&buffer),
4982 GRN_TEXT_VALUE(&buffer));
4983 GRN_BULK_REWIND(&buffer);
4984 }
4985 }
4986 }
4987
4988 GRN_OBJ_FIN(ctx, &buffer);
4989 }
4990
4991 static void
4992 buffer_merge_ensure_dc(grn_ctx *ctx,
4993 grn_ii *ii,
4994 uint8_t **dc,
4995 uint8_t **dcp,
4996 size_t *dc_size,
4997 size_t required_size,
4998 const char *tag)
4999 {
5000 size_t dc_used_size = *dcp - *dc;
5001 if (required_size <= (*dc_size - dc_used_size)) {
5002 return;
5003 }
5004
5005 size_t new_dc_size = *dc_size * 2;
5006 while (required_size > (new_dc_size - dc_used_size)) {
5007 new_dc_size *= 2;
5008 }
5009 auto new_dc = static_cast<uint8_t *>(GRN_REALLOC(*dc, new_dc_size));
5010 if (new_dc) {
5011 GRN_DEFINE_NAME(ii);
5012 GRN_LOG(ctx,
5013 GRN_LOG_INFO,
5014 "[ii][buffer][merge]%s destination chunk is expanded: "
5015 "<%.*s>: "
5016 "<%" GRN_FMT_SIZE "> -> <%" GRN_FMT_SIZE ">",
5017 tag,
5018 name_size,
5019 name,
5020 *dc_size,
5021 new_dc_size);
5022 *dcp = new_dc + dc_used_size;
5023 *dc = new_dc;
5024 *dc_size = new_dc_size;
5025 } else {
5026 grn_rc rc = ctx->rc;
5027 if (rc == GRN_SUCCESS) {
5028 rc = GRN_NO_MEMORY_AVAILABLE;
5029 }
5030 GRN_DEFINE_NAME(ii);
5031 ERR(rc,
5032 "[ii][buffer][merge]%s failed to expand destination chunk: "
5033 "<%.*s>: "
5034 "<%" GRN_FMT_SIZE "> -> <%" GRN_FMT_SIZE ">",
5035 tag,
5036 name_size,
5037 name,
5038 *dc_size,
5039 new_dc_size);
5040 }
5041 }
5042
5043 static inline grn_rc
5044 buffer_merge_internal(grn_ctx *ctx,
5045 grn_ii *ii,
5046 uint32_t seg,
5047 grn_hash *h,
5048 buffer *sb,
5049 const uint8_t *sc,
5050 buffer *db,
5051 uint8_t **dc_output,
5052 grn_merging_data *merging_data)
5053 {
5054 buffer_term *bt;
5055 uint8_t *dcp = NULL;
5056 datavec dv[MAX_N_ELEMENTS + 1];
5057 datavec rdv[MAX_N_ELEMENTS + 1];
5058 uint16_t n = db->header.nterms, nterms_void = 0;
5059 size_t unitsize = (S_SEGMENT + sb->header.chunk_size / sb->header.nterms) * 2;
5060 // size_t unitsize = (S_SEGMENT + sb->header.chunk_size) * 2 + (1<<24);
5061 size_t totalsize = unitsize * ii->n_elements;
5062
5063 // todo : realloc
5064 datavec_init(ctx, ii, dv, unitsize, totalsize);
5065 if (ctx->rc != GRN_SUCCESS) {
5066 GRN_DEFINE_NAME(ii);
5067 ERR(ctx->rc,
5068 "[ii][buffer][merge] failed to initialize data vector: "
5069 "<%.*s>: "
5070 "unit-size:<%" GRN_FMT_SIZE ">, "
5071 "total-size:<%" GRN_FMT_SIZE ">",
5072 name_size,
5073 name,
5074 unitsize,
5075 totalsize);
5076 return ctx->rc;
5077 }
5078 datavec_init(ctx, ii, rdv, 0, 0);
5079 if (ctx->rc != GRN_SUCCESS) {
5080 datavec_fin(ctx, dv);
5081 GRN_DEFINE_NAME(ii);
5082 ERR(ctx->rc,
5083 "[ii][buffer][merge] failed to initialize data vector for read: "
5084 "<%.*s>",
5085 name_size,
5086 name);
5087 return ctx->rc;
5088 }
5089
5090 size_t dc_size = (sb->header.chunk_size + S_SEGMENT) * 2;
5091 auto dc = static_cast<uint8_t *>(GRN_MALLOC(dc_size));
5092 if (!dc) {
5093 grn_rc rc = ctx->rc;
5094 if (rc == GRN_SUCCESS) {
5095 rc = GRN_NO_MEMORY_AVAILABLE;
5096 }
5097 GRN_DEFINE_NAME(ii);
5098 ERR(rc,
5099 "[ii][buffer][merge] failed to allocate destination chunk: "
5100 "<%.*s>: <%" GRN_FMT_SIZE ">",
5101 name_size,
5102 name,
5103 dc_size);
5104 goto exit;
5105 }
5106 dcp = dc;
5107
5108 for (bt = db->terms; n; n--, bt++) {
5109 merger_data data = {};
5110 merger_buffer_data *buffer_data = &(data.source.buffer);
5111 merger_chunk_data *chunk_data = &(data.source.chunk);
5112 int32_t balance = 0;
5113 uint32_t nchunks = 0;
5114 uint32_t nvchunks = 0;
5115 chunk_info *cinfo = NULL;
5116 grn_id crid = GRN_ID_NIL;
5117
5118 if (!bt->tid) {
5119 nterms_void++;
5120 continue;
5121 }
5122
5123 data.ii = ii;
5124 data.term_id = bt->tid;
5125 data.merging_data = merging_data;
5126 buffer_data->buf = sb;
5127 chunk_data->data_start = sc;
5128
5129 if (bt->pos_in_buffer == 0) {
5130 if (bt->size_in_buffer > 0) {
5131 grn_obj term;
5132 GRN_DEFINE_NAME(ii);
5133 GRN_TEXT_INIT(&term, 0);
5134 grn_ii_get_term(ctx, ii, CHUNK_SPLIT_OFF(bt->tid), &term);
5135 GRN_LOG(ctx,
5136 GRN_WARN,
5137 "[ii][buffer][merge] invalid size for buffer term: "
5138 "<%.*s>: "
5139 "<%.*s>(%u): "
5140 "size:<%u>",
5141 name_size,
5142 name,
5143 (int)GRN_TEXT_LEN(&term),
5144 GRN_TEXT_VALUE(&term),
5145 CHUNK_SPLIT_OFF(bt->tid),
5146 bt->size_in_buffer);
5147 GRN_OBJ_FIN(ctx, &term);
5148 goto exit;
5149 }
5150 if (bt->size_in_chunk > 0) {
5151 buffer_merge_ensure_dc(ctx,
5152 ii,
5153 &dc,
5154 &dcp,
5155 &dc_size,
5156 bt->size_in_chunk,
5157 "[copy-chunk]");
5158 if (ctx->rc != GRN_SUCCESS) {
5159 goto exit;
5160 }
5161 grn_memcpy(dcp,
5162 chunk_data->data_start + bt->pos_in_chunk,
5163 bt->size_in_chunk);
5164 bt->pos_in_chunk = (uint32_t)(dcp - dc);
5165 dcp += bt->size_in_chunk;
5166 }
5167 continue;
5168 }
5169
5170 buffer_data->next_position = bt->pos_in_buffer;
5171 merger_get_next_buffer(ctx, &data);
5172 if (ctx->rc != GRN_SUCCESS) {
5173 goto exit;
5174 }
5175 if (chunk_data->data_start && bt->size_in_chunk > 0) {
5176 size_t size = S_SEGMENT * ii->n_elements;
5177 chunk_data->data = chunk_data->data_start + bt->pos_in_chunk;
5178 chunk_data->data_end = chunk_data->data + bt->size_in_chunk;
5179 if ((bt->tid & CHUNK_SPLIT)) {
5180 uint32_t i;
5181 GRN_B_DEC(nchunks, chunk_data->data);
5182 if (!(cinfo = GRN_MALLOCN(chunk_info, nchunks + 1))) {
5183 grn_obj term;
5184 GRN_DEFINE_NAME(ii);
5185 GRN_TEXT_INIT(&term, 0);
5186 grn_ii_get_term(ctx, ii, CHUNK_SPLIT_OFF(bt->tid), &term);
5187 MERR("[ii][buffer][merge] failed to allocate chunk info: "
5188 "<%.*s>: "
5189 "<%.*s>(%u): "
5190 "segment:<%u>, "
5191 "n-chunks:<%u>, "
5192 "unit-size:<%" GRN_FMT_SIZE ">, "
5193 "total-size:<%" GRN_FMT_SIZE ">",
5194 name_size,
5195 name,
5196 (int)GRN_TEXT_LEN(&term),
5197 GRN_TEXT_VALUE(&term),
5198 CHUNK_SPLIT_OFF(bt->tid),
5199 seg,
5200 nchunks,
5201 unitsize,
5202 totalsize);
5203 GRN_OBJ_FIN(ctx, &term);
5204 goto exit;
5205 }
5206 grn_id dgap_keep = GRN_ID_NIL;
5207 for (i = 0; i < nchunks; i++) {
5208 GRN_B_DEC(cinfo[i].segno, chunk_data->data);
5209 GRN_B_DEC(cinfo[i].size, chunk_data->data);
5210 GRN_B_DEC(cinfo[i].dgap, chunk_data->data);
5211 crid += cinfo[i].dgap;
5212 if (buffer_data->id.rid <= crid) {
5213 chunk_merge(ctx, &data, &cinfo[i], crid, dv, &balance);
5214 if (ctx->rc != GRN_SUCCESS) {
5215 if (cinfo) {
5216 GRN_FREE(cinfo);
5217 }
5218 {
5219 grn_obj term;
5220 GRN_DEFINE_NAME(ii);
5221 GRN_TEXT_INIT(&term, 0);
5222 grn_ii_get_term(ctx, ii, CHUNK_SPLIT_OFF(bt->tid), &term);
5223 ERR(ctx->rc,
5224 "[ii][buffer][merge] failed to merge chunk: "
5225 "<%.*s>: "
5226 "<%.*s>(%u): "
5227 "chunk:<%u>, "
5228 "n-chunks:<%u>",
5229 name_size,
5230 name,
5231 (int)GRN_TEXT_LEN(&term),
5232 GRN_TEXT_VALUE(&term),
5233 CHUNK_SPLIT_OFF(bt->tid),
5234 i,
5235 nchunks);
5236 GRN_OBJ_FIN(ctx, &term);
5237 }
5238 goto exit;
5239 }
5240 }
5241 if (cinfo[i].size == 0) {
5242 dgap_keep += cinfo[i].dgap;
5243 } else {
5244 cinfo[i].dgap += dgap_keep;
5245 dgap_keep = GRN_ID_NIL;
5246 nvchunks++;
5247 }
5248 }
5249 }
5250 if (chunk_data->data_end > chunk_data->data) {
5251 int decoded_size;
5252 decoded_size = grn_decv(ctx,
5253 ii,
5254 CHUNK_SPLIT_OFF(bt->tid),
5255 chunk_data->data,
5256 chunk_data->data_end - chunk_data->data,
5257 rdv);
5258 if (decoded_size == 0) {
5259 if (cinfo) {
5260 GRN_FREE(cinfo);
5261 }
5262 {
5263 grn_obj term;
5264 grn_rc rc = ctx->rc;
5265 GRN_DEFINE_NAME(ii);
5266 GRN_TEXT_INIT(&term, 0);
5267 grn_ii_get_term(ctx, ii, CHUNK_SPLIT_OFF(bt->tid), &term);
5268 if (rc == GRN_SUCCESS) {
5269 rc = GRN_UNKNOWN_ERROR;
5270 }
5271 ERR(rc,
5272 "[ii][buffer][merge] failed to decode: "
5273 "<%.*s>: "
5274 "<%.*s>(%u): "
5275 "n-chunks:<%u>",
5276 name_size,
5277 name,
5278 (int)GRN_TEXT_LEN(&term),
5279 GRN_TEXT_VALUE(&term),
5280 CHUNK_SPLIT_OFF(bt->tid),
5281 nvchunks);
5282 GRN_OBJ_FIN(ctx, &term);
5283 }
5284 goto exit;
5285 }
5286 size += decoded_size;
5287 merger_init_chunk_data(ctx, &data, rdv);
5288 datavec_reset(ctx, ii, dv, chunk_data->n_documents + S_SEGMENT, size);
5289 if (ctx->rc != GRN_SUCCESS) {
5290 if (cinfo) {
5291 GRN_FREE(cinfo);
5292 }
5293 {
5294 grn_obj term;
5295 GRN_DEFINE_NAME(ii);
5296 GRN_TEXT_INIT(&term, 0);
5297 grn_ii_get_term(ctx, ii, CHUNK_SPLIT_OFF(bt->tid), &term);
5298 ERR(ctx->rc,
5299 "[ii][buffer][merge] failed to reset data vector: "
5300 "<%.*s>: "
5301 "<%.*s>(%u): "
5302 "unit-size:<%" GRN_FMT_SIZE ">, "
5303 "total-size:<%" GRN_FMT_SIZE ">",
5304 name_size,
5305 name,
5306 (int)GRN_TEXT_LEN(&term),
5307 GRN_TEXT_VALUE(&term),
5308 CHUNK_SPLIT_OFF(bt->tid),
5309 (size_t)(chunk_data->n_documents + S_SEGMENT),
5310 size);
5311 GRN_OBJ_FIN(ctx, &term);
5312 }
5313 goto exit;
5314 }
5315 }
5316 }
5317 {
5318 int j = 0;
5319 data.dest.record_id_gaps = dv[j++].data;
5320 if ((ii->header.common->flags & GRN_OBJ_WITH_SECTION)) {
5321 data.dest.section_id_gaps = dv[j++].data;
5322 }
5323 data.dest.tfs = dv[j++].data;
5324 if ((ii->header.common->flags & GRN_OBJ_WITH_WEIGHT)) {
5325 data.dest.weights = dv[j++].data;
5326 }
5327 data.dest.position_gaps = dv[j++].data;
5328 data.dest.position_gaps_end = dv[j].data;
5329 }
5330 data.last_id = null_docinfo;
5331 merger_get_next_chunk(ctx, &data);
5332 if (ctx->rc != GRN_SUCCESS) {
5333 if (cinfo) {
5334 GRN_FREE(cinfo);
5335 }
5336 goto exit;
5337 }
5338 data.position = 0;
5339 while (merger_merge(ctx, &data)) {
5340 }
5341 if (ctx->rc != GRN_SUCCESS) {
5342 if (cinfo) {
5343 GRN_FREE(cinfo);
5344 }
5345 {
5346 grn_obj term;
5347 GRN_DEFINE_NAME(ii);
5348 GRN_TEXT_INIT(&term, 0);
5349 grn_ii_get_term(ctx, ii, CHUNK_SPLIT_OFF(bt->tid), &term);
5350 ERR(ctx->rc,
5351 "[ii][buffer][merge] failed to merge chunk: "
5352 "<%.*s>: "
5353 "<%.*s>(%u)",
5354 name_size,
5355 name,
5356 (int)GRN_TEXT_LEN(&term),
5357 GRN_TEXT_VALUE(&term),
5358 CHUNK_SPLIT_OFF(bt->tid));
5359 GRN_OBJ_FIN(ctx, &term);
5360 }
5361 goto exit;
5362 }
5363 {
5364 /* TODO: Is n_documents better? */
5365 uint32_t ndf = data.dest.record_id_gaps - dv[0].data;
5366 grn_id tid = CHUNK_SPLIT_OFF(bt->tid);
5367 uint32_t *a = array_at(ctx, ii, tid);
5368 if (!a) {
5369 /* TODO: warning */
5370 GRN_LOG(ctx, GRN_LOG_DEBUG, "array_entry not found tid=%d", tid);
5371 memset(bt, 0, sizeof(buffer_term));
5372 nterms_void++;
5373 } else {
5374 if (!ndf && !nvchunks) {
5375 a[0] = 0;
5376 a[1] = 0;
5377 lexicon_delete(ctx, ii, tid, h);
5378 memset(bt, 0, sizeof(buffer_term));
5379 nterms_void++;
5380 } else if ((ii->header.common->flags & GRN_OBJ_WITH_SECTION) &&
5381 !nvchunks && ndf == 1 && data.last_id.rid < 0x100000 &&
5382 data.last_id.sid < 0x800 && data.last_id.tf == 1 &&
5383 data.last_id.weight == 0) {
5384 a[0] = POS_EMBED_RID_SID(data.last_id.rid, data.last_id.sid);
5385 if (ii->header.common->flags & GRN_OBJ_WITH_POSITION) {
5386 a[1] = data.dest.position_gaps[-1];
5387 } else {
5388 a[1] = 0;
5389 }
5390 memset(bt, 0, sizeof(buffer_term));
5391 nterms_void++;
5392 } else if (!(ii->header.common->flags & GRN_OBJ_WITH_SECTION) &&
5393 !nvchunks && ndf == 1 && data.last_id.tf == 1 &&
5394 data.last_id.weight == 0) {
5395 a[0] = POS_EMBED_RID(data.last_id.rid);
5396 if (ii->header.common->flags & GRN_OBJ_WITH_POSITION) {
5397 a[1] = data.dest.position_gaps[-1];
5398 } else {
5399 a[1] = 0;
5400 }
5401 memset(bt, 0, sizeof(buffer_term));
5402 nterms_void++;
5403 } else {
5404 const uint32_t n_positions =
5405 data.dest.position_gaps - dv[ii->n_elements - 1].data;
5406 datavec_set_data_size(ctx,
5407 ii,
5408 dv,
5409 ndf,
5410 data.last_id.rid,
5411 n_positions,
5412 data.max_position);
5413 const size_t dc_offset = dcp - dc;
5414 a[1] = (bt->size_in_chunk ? a[1] : 0) +
5415 (ndf - chunk_data->n_documents) + balance;
5416 if (nvchunks) {
5417 buffer_merge_ensure_dc(ctx,
5418 ii,
5419 &dc,
5420 &dcp,
5421 &dc_size,
5422 GRN_B_ENC_MAX_SIZE * (1 + 3 * nchunks),
5423 "[encode-chunk-metadata]");
5424 if (ctx->rc != GRN_SUCCESS) {
5425 if (cinfo) {
5426 GRN_FREE(cinfo);
5427 }
5428 array_unref(ctx, ii, tid);
5429 goto exit;
5430 }
5431 GRN_B_ENC(nvchunks, dcp);
5432 for (uint32_t i = 0; i < nchunks; i++) {
5433 if (cinfo[i].size) {
5434 GRN_B_ENC(cinfo[i].segno, dcp);
5435 GRN_B_ENC(cinfo[i].size, dcp);
5436 GRN_B_ENC(cinfo[i].dgap, dcp);
5437 }
5438 }
5439 }
5440 const ssize_t estimated_encsize = grn_encv(ctx, ii, tid, dv, NULL, 0);
5441 if (estimated_encsize == -1) {
5442 grn_obj term;
5443 GRN_DEFINE_NAME(ii);
5444 GRN_TEXT_INIT(&term, 0);
5445 grn_ii_get_term(ctx, ii, tid, &term);
5446 ERR(ctx->rc,
5447 "[ii][buffer][merge] failed to estimate encode buffer size: "
5448 "<%.*s>: "
5449 "<%.*s>(%u)",
5450 name_size,
5451 name,
5452 (int)GRN_TEXT_LEN(&term),
5453 GRN_TEXT_VALUE(&term),
5454 tid);
5455 GRN_OBJ_FIN(ctx, &term);
5456 buffer_merge_dump_datavec(ctx, ii, dv, rdv);
5457 if (cinfo) {
5458 GRN_FREE(cinfo);
5459 }
5460 array_unref(ctx, ii, tid);
5461 goto exit;
5462 }
5463 buffer_merge_ensure_dc(ctx,
5464 ii,
5465 &dc,
5466 &dcp,
5467 &dc_size,
5468 estimated_encsize,
5469 "[encode-data-vector]");
5470 if (ctx->rc != GRN_SUCCESS) {
5471 buffer_merge_dump_datavec(ctx, ii, dv, rdv);
5472 if (cinfo) {
5473 GRN_FREE(cinfo);
5474 }
5475 array_unref(ctx, ii, tid);
5476 goto exit;
5477 }
5478
5479 const ssize_t encsize =
5480 grn_encv(ctx, ii, tid, dv, dcp, dc_size - (dcp - dc));
5481 if (encsize == -1) {
5482 grn_obj term;
5483 GRN_DEFINE_NAME(ii);
5484 GRN_TEXT_INIT(&term, 0);
5485 grn_ii_get_term(ctx, ii, tid, &term);
5486 ERR(ctx->rc,
5487 "[ii][buffer][merge] failed to encode: "
5488 "<%.*s>: "
5489 "<%.*s>(%u): "
5490 "<%" GRN_FMT_SSIZE ">",
5491 name_size,
5492 name,
5493 (int)GRN_TEXT_LEN(&term),
5494 GRN_TEXT_VALUE(&term),
5495 tid,
5496 estimated_encsize);
5497 GRN_OBJ_FIN(ctx, &term);
5498 buffer_merge_dump_datavec(ctx, ii, dv, rdv);
5499 if (cinfo) {
5500 GRN_FREE(cinfo);
5501 }
5502 array_unref(ctx, ii, tid);
5503 goto exit;
5504 }
5505
5506 if (encsize > CHUNK_SPLIT_THRESHOLD &&
5507 (cinfo || (cinfo = GRN_MALLOCN(chunk_info, nchunks + 1))) &&
5508 !chunk_flush(ctx, ii, &cinfo[nchunks], dcp, encsize)) {
5509 uint32_t i;
5510 cinfo[nchunks].dgap = data.last_id.rid - crid;
5511 nvchunks++;
5512 dcp = dc + dc_offset;
5513 GRN_B_ENC(nvchunks, dcp);
5514 for (i = 0; i <= nchunks; i++) {
5515 if (cinfo[i].size) {
5516 GRN_B_ENC(cinfo[i].segno, dcp);
5517 GRN_B_ENC(cinfo[i].size, dcp);
5518 GRN_B_ENC(cinfo[i].dgap, dcp);
5519 }
5520 }
5521 /* TODO: format */
5522 GRN_LOG(ctx,
5523 GRN_LOG_DEBUG,
5524 "split (%d) encsize=%" GRN_FMT_SSIZE,
5525 tid,
5526 encsize);
5527 bt->tid |= CHUNK_SPLIT;
5528 } else {
5529 dcp += encsize;
5530 if (!nvchunks) {
5531 bt->tid &= ~CHUNK_SPLIT;
5532 }
5533 }
5534 bt->pos_in_chunk = (uint32_t)dc_offset;
5535 bt->size_in_chunk = (uint32_t)(dcp - (dc + dc_offset));
5536 bt->size_in_buffer = 0;
5537 bt->pos_in_buffer = 0;
5538 }
5539 array_unref(ctx, ii, tid);
5540 }
5541 }
5542 if (cinfo) {
5543 GRN_FREE(cinfo);
5544 }
5545 }
5546 db->header.chunk_size = (uint32_t)(dcp - dc);
5547 db->header.buffer_free =
5548 S_SEGMENT - sizeof(buffer_header) - db->header.nterms * sizeof(buffer_term);
5549 db->header.nterms_void = nterms_void;
5550
5551 if (grn_ii_dump_index_source_on_merge) {
5552 merge_dump_source(ctx, ii, sb, sc, GRN_LOG_DEBUG);
5553 }
5554
5555 exit:
5556 if (ctx->rc == GRN_SUCCESS) {
5557 *dc_output = dc;
5558 } else {
5559 if (dc) {
5560 GRN_FREE(dc);
5561 }
5562 }
5563 datavec_fin(ctx, dv);
5564 datavec_fin(ctx, rdv);
5565 return ctx->rc;
5566 }
5567
5568 static grn_rc
5569 buffer_merge(grn_ctx *ctx,
5570 grn_ii *ii,
5571 uint32_t seg,
5572 grn_hash *h,
5573 buffer *sb,
5574 const uint8_t *sc,
5575 buffer *db,
5576 uint8_t **dc_output,
5577 grn_merging_data *merging_data)
5578 {
5579 GRN_SLOW_LOG_PUSH(ctx, GRN_LOG_DEBUG);
5580 grn_rc rc =
5581 buffer_merge_internal(ctx, ii, seg, h, sb, sc, db, dc_output, merging_data);
5582 GRN_SLOW_LOG_POP_BEGIN(ctx, GRN_LOG_DEBUG, elapsed_time)
5583 {
5584 GRN_DEFINE_NAME(ii);
5585 GRN_LOG(ctx,
5586 GRN_LOG_DEBUG,
5587 "[ii][buffer][merge][slow][%f] "
5588 "<%.*s>: "
5589 "physical-segment:<%u>, "
5590 "logical-segment:<%u>",
5591 elapsed_time,
5592 name_size,
5593 name,
5594 grn_ii_get_buffer_pseg_inline(ii, seg),
5595 seg);
5596 }
5597 GRN_SLOW_LOG_POP_END(ctx);
5598 return rc;
5599 }
5600
5601 static void
5602 fake_map(grn_ctx *ctx,
5603 grn_io *io,
5604 grn_io_win *iw,
5605 void *addr,
5606 uint32_t seg,
5607 uint32_t size)
5608 {
5609 iw->ctx = ctx;
5610 iw->diff = 0;
5611 iw->io = io;
5612 iw->mode = GRN_IO_WRONLY;
5613 iw->segment = ((seg) >> GRN_II_N_CHUNK_VARIATION);
5614 iw->offset =
5615 (((seg) & ((1 << GRN_II_N_CHUNK_VARIATION) - 1)) << GRN_II_W_LEAST_CHUNK);
5616 iw->size = size;
5617 iw->cached = 0;
5618 iw->addr = addr;
5619 }
5620
5621 static inline grn_rc
5622 buffer_flush_internal(grn_ctx *ctx, grn_ii *ii, uint32_t lseg, grn_hash *h)
5623 {
5624 grn_io_win sw, dw;
5625 buffer *sb;
5626 uint32_t ds, pseg, scn, dcn = 0;
5627 if (grn_ii_get_buffer_pseg_inline(ii, lseg) == GRN_II_PSEG_NOT_ASSIGNED) {
5628 GRN_DEFINE_NAME(ii);
5629 CRIT(GRN_FILE_CORRUPT,
5630 "[ii][buffer][flush] invalid segment: "
5631 "<%.*s>: "
5632 "request:<%u>, max:<%u>",
5633 name_size,
5634 name,
5635 lseg,
5636 ii->seg->header->max_segment);
5637 return ctx->rc;
5638 }
5639 ds = segment_get(ctx, ii);
5640 if (ds == ii->seg->header->max_segment) {
5641 GRN_DEFINE_NAME(ii);
5642 MERR("[ii][buffer][flush] segment is full: "
5643 "<%.*s>: "
5644 "request:<%u>, max:<%u>",
5645 name_size,
5646 name,
5647 lseg,
5648 ii->seg->header->max_segment);
5649 return ctx->rc;
5650 }
5651 if (ds == GRN_II_PSEG_NOT_ASSIGNED) {
5652 GRN_DEFINE_NAME(ii);
5653 MERR("[ii][buffer][flush] couldn't assign a segment: "
5654 "<%.*s>: "
5655 "request:<%u>, max:<%u>",
5656 name_size,
5657 name,
5658 lseg,
5659 ii->seg->header->max_segment);
5660 return ctx->rc;
5661 }
5662 pseg = buffer_open(ctx, ii, grn_ii_pos_pack(ii, lseg, 0), NULL, &sb);
5663 if (pseg == GRN_II_PSEG_NOT_ASSIGNED) {
5664 GRN_DEFINE_NAME(ii);
5665 MERR("[ii][buffer][flush] failed to open buffer: "
5666 "<%.*s>: "
5667 "segment:<%u>, position:<%u>, max:<%u>",
5668 name_size,
5669 name,
5670 lseg,
5671 grn_ii_pos_pack(ii, lseg, 0),
5672 ii->seg->header->max_segment);
5673 return ctx->rc;
5674 }
5675 {
5676 auto db = static_cast<buffer *>(grn_io_seg_ref(ctx, ii->seg, ds));
5677 if (db) {
5678 const uint8_t *sc = NULL;
5679 if ((scn = sb->header.chunk) == GRN_II_PSEG_NOT_ASSIGNED ||
5680 (sc = static_cast<const uint8_t *>(WIN_MAP(ctx,
5681 ii->chunk,
5682 &sw,
5683 scn,
5684 0,
5685 sb->header.chunk_size,
5686 GRN_IO_RDONLY)))) {
5687 uint16_t n = sb->header.nterms;
5688 memset(db, 0, S_SEGMENT);
5689 grn_memcpy(db->terms, sb->terms, n * sizeof(buffer_term));
5690 db->header.nterms = n;
5691 uint8_t *dc = NULL;
5692 grn_merging_data merging_data;
5693 grn_merging_data_init(ctx, &merging_data, ii);
5694 buffer_merge(ctx, ii, lseg, h, sb, sc, db, &dc, &merging_data);
5695 if (ctx->rc == GRN_SUCCESS) {
5696 const uint32_t actual_chunk_size = db->header.chunk_size;
5697 bool need_chunk_free = true;
5698 if (actual_chunk_size > 0) {
5699 chunk_new(ctx, ii, &dcn, actual_chunk_size);
5700 if (ctx->rc == GRN_SUCCESS) {
5701 need_chunk_free = true;
5702 }
5703 }
5704 if (ctx->rc == GRN_SUCCESS) {
5705 grn_rc rc;
5706 db->header.chunk =
5707 (actual_chunk_size > 0) ? dcn : GRN_II_PSEG_NOT_ASSIGNED;
5708 fake_map(ctx, ii->chunk, &dw, dc, dcn, actual_chunk_size);
5709 rc = grn_io_win_unmap(ctx, &dw);
5710 if (rc == GRN_SUCCESS) {
5711 dc = NULL;
5712 buffer_segment_update(ii, lseg, ds);
5713 ii->header.common->total_chunk_size += actual_chunk_size;
5714 need_chunk_free = false;
5715 merging_data.succeeded = true;
5716 if (scn != GRN_II_PSEG_NOT_ASSIGNED) {
5717 chunk_free(ctx, ii, scn, sb->header.chunk_size);
5718 ii->header.common->total_chunk_size -= sb->header.chunk_size;
5719 }
5720 } else {
5721 GRN_DEFINE_NAME(ii);
5722 ERR(rc,
5723 "[ii][buffer][flush] failed to unmap a destination chunk: "
5724 "<%.*s> : "
5725 "segment:<%u>, destination-segment:<%u>, actual-size:<%u>",
5726 name_size,
5727 name,
5728 lseg,
5729 dcn,
5730 actual_chunk_size);
5731 }
5732 }
5733 if (need_chunk_free) {
5734 chunk_free(ctx, ii, dcn, actual_chunk_size);
5735 }
5736 if (dc) {
5737 GRN_FREE(dc);
5738 }
5739 }
5740 grn_merging_data_fin(ctx, &merging_data);
5741 if (scn != GRN_II_PSEG_NOT_ASSIGNED) {
5742 grn_io_win_unmap(ctx, &sw);
5743 }
5744 } else {
5745 GRN_DEFINE_NAME(ii);
5746 MERR("[ii][buffer][flush] failed to map a source chunk: "
5747 "<%.*s>: "
5748 "segment:<%u>, source-segment:<%u>, chunk-size:<%u>",
5749 name_size,
5750 name,
5751 lseg,
5752 scn,
5753 sb->header.chunk_size);
5754 }
5755 grn_io_seg_unref(ctx, ii->seg, ds);
5756 } else {
5757 GRN_DEFINE_NAME(ii);
5758 MERR("[ii][buffer][flush] failed to allocate a destination segment: "
5759 "<%.*s>: "
5760 "segment:<%u>, destination-segment:<%u>",
5761 name_size,
5762 name,
5763 lseg,
5764 ds);
5765 }
5766 buffer_close(ctx, ii, pseg);
5767 }
5768 return ctx->rc;
5769 }
5770
5771 static grn_rc
5772 buffer_flush(grn_ctx *ctx, grn_ii *ii, uint32_t lseg, grn_hash *h)
5773 {
5774 GRN_SLOW_LOG_PUSH(ctx, GRN_LOG_DEBUG);
5775 grn_rc rc = buffer_flush_internal(ctx, ii, lseg, h);
5776 GRN_SLOW_LOG_POP_BEGIN(ctx, GRN_LOG_DEBUG, elapsed_time)
5777 {
5778 GRN_DEFINE_NAME(ii);
5779 GRN_LOG(ctx,
5780 GRN_LOG_DEBUG,
5781 "[ii][buffer][flush][slow][%f] "
5782 "<%.*s>: "
5783 "physical-segment:<%u>, "
5784 "logical-segment:<%u>",
5785 elapsed_time,
5786 name_size,
5787 name,
5788 grn_ii_get_buffer_pseg_inline(ii, lseg),
5789 lseg);
5790 }
5791 GRN_SLOW_LOG_POP_END(ctx);
5792 return rc;
5793 }
5794
5795 extern "C" void
5796 grn_ii_buffer_check(grn_ctx *ctx, grn_ii *ii, uint32_t lseg)
5797 {
5798 grn_io_win sw;
5799 buffer *sb;
5800 uint8_t *sc = NULL;
5801 uint32_t pseg, scn, nterms_with_corrupt_chunk = 0, nterm_with_chunk = 0;
5802 uint32_t ndeleted_terms_with_value = 0;
5803 buffer_term *bt;
5804 datavec rdv[MAX_N_ELEMENTS + 1];
5805 uint16_t n;
5806 int nterms_void = 0;
5807 int size_in_buffer = 0;
5808 grn_obj buf;
5809 size_t lower_bound;
5810 int64_t nloops = 0, nviolations = 0;
5811 if (grn_ii_get_buffer_pseg_inline(ii, lseg) == GRN_II_PSEG_NOT_ASSIGNED) {
5812 GRN_OUTPUT_BOOL(false);
5813 return;
5814 }
5815 pseg = buffer_open(ctx, ii, grn_ii_pos_pack(ii, lseg, 0), NULL, &sb);
5816 if (pseg == GRN_II_PSEG_NOT_ASSIGNED) {
5817 GRN_OUTPUT_BOOL(false);
5818 return;
5819 }
5820 lower_bound =
5821 (sb->header.buffer_free + sizeof(buffer_term) * sb->header.nterms) /
5822 sizeof(buffer_rec);
5823 datavec_init(ctx, ii, rdv, 0, 0);
5824 GRN_OUTPUT_MAP_OPEN("BUFFER", -1);
5825 GRN_OUTPUT_CSTR("buffer id");
5826 GRN_OUTPUT_INT64(lseg);
5827 if ((scn = sb->header.chunk) == GRN_II_PSEG_NOT_ASSIGNED) {
5828 GRN_OUTPUT_CSTR("void chunk size");
5829 GRN_OUTPUT_INT64(sb->header.chunk_size);
5830 } else {
5831 if ((sc = static_cast<uint8_t *>(WIN_MAP(ctx,
5832 ii->chunk,
5833 &sw,
5834 scn,
5835 0,
5836 sb->header.chunk_size,
5837 GRN_IO_RDONLY)))) {
5838 GRN_OUTPUT_CSTR("chunk size");
5839 GRN_OUTPUT_INT64(sb->header.chunk_size);
5840 } else {
5841 GRN_OUTPUT_CSTR("unmappable chunk size");
5842 GRN_OUTPUT_INT64(sb->header.chunk_size);
5843 }
5844 }
5845 GRN_OUTPUT_CSTR("buffer term");
5846 GRN_OUTPUT_ARRAY_OPEN("TERMS", sb->header.nterms);
5847
5848 GRN_OBJ_INIT(&buf, GRN_BULK, 0, ii->lexicon->header.domain);
5849 for (bt = sb->terms, n = sb->header.nterms; n; n--, bt++) {
5850 grn_id tid, tid_;
5851 char key[GRN_TABLE_MAX_KEY_SIZE];
5852 int key_size;
5853 uint32_t nchunks = 0;
5854 chunk_info *cinfo = NULL;
5855 grn_id crid = GRN_ID_NIL;
5856 merger_data data = {};
5857 merger_chunk_data *chunk_data = &(data.source.chunk);
5858
5859 if (!bt->tid && !bt->pos_in_buffer && !bt->size_in_buffer) {
5860 nterms_void++;
5861 continue;
5862 }
5863 GRN_OUTPUT_ARRAY_OPEN("TERM", -1);
5864 tid = CHUNK_SPLIT_OFF(bt->tid);
5865 key_size =
5866 grn_table_get_key(ctx, ii->lexicon, tid, key, GRN_TABLE_MAX_KEY_SIZE);
5867 tid_ = grn_table_get(ctx, ii->lexicon, key, key_size);
5868 GRN_TEXT_SET(ctx, &buf, key, key_size);
5869 GRN_OUTPUT_OBJ(&buf, NULL);
5870 GRN_OUTPUT_INT64(bt->tid);
5871 GRN_OUTPUT_INT64(tid_);
5872
5873 size_in_buffer += bt->size_in_buffer;
5874 if (tid != tid_ && (bt->size_in_buffer || bt->size_in_chunk)) {
5875 ndeleted_terms_with_value++;
5876 }
5877 GRN_OUTPUT_INT64(bt->size_in_buffer);
5878 GRN_OUTPUT_INT64(bt->size_in_chunk);
5879
5880 data.ii = ii;
5881 data.term_id = bt->tid;
5882 data.source.buffer.buf = sb;
5883 data.source.buffer.next_position = bt->pos_in_buffer;
5884 chunk_data->data_start = sc;
5885 merger_get_next_buffer(ctx, &data);
5886 if (sc && bt->size_in_chunk) {
5887 size_t size = S_SEGMENT * ii->n_elements;
5888 chunk_data->data = chunk_data->data_start + bt->pos_in_chunk;
5889 chunk_data->data_end = chunk_data->data + bt->size_in_chunk;
5890 if ((bt->tid & CHUNK_SPLIT)) {
5891 uint32_t i;
5892 GRN_B_DEC(nchunks, chunk_data->data);
5893 if (!(cinfo = GRN_MALLOCN(chunk_info, nchunks + 1))) {
5894 datavec_fin(ctx, rdv);
5895 GRN_OBJ_FIN(ctx, &buf);
5896 return;
5897 }
5898 for (i = 0; i < nchunks; i++) {
5899 GRN_B_DEC(cinfo[i].segno, chunk_data->data);
5900 GRN_B_DEC(cinfo[i].size, chunk_data->data);
5901 GRN_B_DEC(cinfo[i].dgap, chunk_data->data);
5902 crid += cinfo[i].dgap;
5903 }
5904 }
5905 if (chunk_data->data_end > chunk_data->data) {
5906 size += grn_decv(ctx,
5907 ii,
5908 crid,
5909 chunk_data->data,
5910 chunk_data->data_end - chunk_data->data,
5911 rdv);
5912 merger_init_chunk_data(ctx, &data, rdv);
5913 GRN_OUTPUT_INT64(chunk_data->n_documents);
5914 GRN_OUTPUT_INT64(chunk_data->position_gaps_end -
5915 chunk_data->position_gaps);
5916 {
5917 int j = 0;
5918 j++;
5919 if ((ii->header.common->flags & GRN_OBJ_WITH_SECTION)) {
5920 j++;
5921 }
5922 if (chunk_data->n_documents != rdv[j].data_size) {
5923 nterms_with_corrupt_chunk++;
5924 }
5925 j++;
5926 if ((ii->header.common->flags & GRN_OBJ_WITH_WEIGHT)) {
5927 j++;
5928 }
5929 }
5930 nterm_with_chunk++;
5931 }
5932 }
5933 {
5934 uint16_t pos;
5935 grn_id rid, sid, rid_ = 0, sid_ = 0;
5936 uint8_t *p;
5937 buffer_rec *r;
5938 for (pos = bt->pos_in_buffer; pos; pos = r->step) {
5939 if (pos < lower_bound) {
5940 nviolations++;
5941 }
5942 r = BUFFER_REC_AT(sb, pos);
5943 p = GRN_NEXT_ADDR(r);
5944 GRN_B_DEC(rid, p);
5945 if ((ii->header.common->flags & GRN_OBJ_WITH_SECTION)) {
5946 GRN_B_DEC(sid, p);
5947 } else {
5948 sid = 1;
5949 }
5950 if (rid < rid_ || (rid == rid_ && sid < sid_)) {
5951 nloops++;
5952 }
5953 rid_ = rid;
5954 sid_ = sid;
5955 }
5956 }
5957 GRN_OUTPUT_ARRAY_CLOSE();
5958 if (cinfo) {
5959 GRN_FREE(cinfo);
5960 }
5961 }
5962 GRN_OBJ_FIN(ctx, &buf);
5963
5964 GRN_OUTPUT_ARRAY_CLOSE();
5965 GRN_OUTPUT_CSTR("buffer free");
5966 GRN_OUTPUT_INT64(sb->header.buffer_free);
5967 GRN_OUTPUT_CSTR("size in buffer");
5968 GRN_OUTPUT_INT64(size_in_buffer);
5969 GRN_OUTPUT_CSTR("nterms");
5970 GRN_OUTPUT_INT64(sb->header.nterms);
5971 if (nterms_void != sb->header.nterms_void) {
5972 GRN_OUTPUT_CSTR("nterms void gap");
5973 GRN_OUTPUT_INT64(nterms_void - sb->header.nterms_void);
5974 }
5975 GRN_OUTPUT_CSTR("nterms with chunk");
5976 GRN_OUTPUT_INT64(nterm_with_chunk);
5977 if (nterms_with_corrupt_chunk) {
5978 GRN_OUTPUT_CSTR("nterms with corrupt chunk");
5979 GRN_OUTPUT_INT64(nterms_with_corrupt_chunk);
5980 }
5981 if (ndeleted_terms_with_value) {
5982 GRN_OUTPUT_CSTR("number of deleted terms with value");
5983 GRN_OUTPUT_INT64(ndeleted_terms_with_value);
5984 }
5985 if (nloops) {
5986 GRN_OUTPUT_CSTR("number of loops");
5987 GRN_OUTPUT_INT64(nloops);
5988 }
5989 if (nviolations) {
5990 GRN_OUTPUT_CSTR("number of violations");
5991 GRN_OUTPUT_INT64(nviolations);
5992 }
5993 GRN_OUTPUT_MAP_CLOSE();
5994 datavec_fin(ctx, rdv);
5995 if (sc) {
5996 grn_io_win_unmap(ctx, &sw);
5997 }
5998 buffer_close(ctx, ii, pseg);
5999 }
6000
6001 typedef struct {
6002 buffer_term *bt;
6003 const char *key;
6004 uint32_t key_size;
6005 } term_sort;
6006
6007 static int
6008 term_compar(const void *t1, const void *t2)
6009 {
6010 int r;
6011 const term_sort *x = (term_sort *)t1, *y = (term_sort *)t2;
6012 if (x->key_size > y->key_size) {
6013 r = memcmp(x->key, y->key, y->key_size);
6014 return r ? r : (int)(x->key_size - y->key_size);
6015 } else {
6016 r = memcmp(x->key, y->key, x->key_size);
6017 return r ? r : (int)(x->key_size - y->key_size);
6018 }
6019 }
6020
6021 static grn_rc
6022 term_split(grn_ctx *ctx, grn_obj *lexicon, buffer *sb, buffer *db0, buffer *db1)
6023 {
6024 uint16_t i, n, *nt;
6025 buffer_term *bt;
6026 uint32_t s, th = (sb->header.chunk_size + sb->header.nterms) >> 1;
6027 auto ts =
6028 static_cast<term_sort *>(GRN_MALLOC(sb->header.nterms * sizeof(term_sort)));
6029 if (!ts) {
6030 return GRN_NO_MEMORY_AVAILABLE;
6031 }
6032 for (i = 0, n = sb->header.nterms, bt = sb->terms; n; bt++, n--) {
6033 if (bt->tid) {
6034 grn_id tid = CHUNK_SPLIT_OFF(bt->tid);
6035 ts[i].key = _grn_table_key(ctx, lexicon, tid, &ts[i].key_size);
6036 ts[i].bt = bt;
6037 i++;
6038 }
6039 }
6040 qsort(ts, i, sizeof(term_sort), term_compar);
6041 memset(db0, 0, S_SEGMENT);
6042 bt = db0->terms;
6043 nt = &db0->header.nterms;
6044 for (s = 0; n + 1 < i && s <= th; n++, bt++) {
6045 grn_memcpy(bt, ts[n].bt, sizeof(buffer_term));
6046 (*nt)++;
6047 s += ts[n].bt->size_in_chunk + 1;
6048 }
6049 memset(db1, 0, S_SEGMENT);
6050 bt = db1->terms;
6051 nt = &db1->header.nterms;
6052 for (; n < i; n++, bt++) {
6053 grn_memcpy(bt, ts[n].bt, sizeof(buffer_term));
6054 (*nt)++;
6055 }
6056 GRN_FREE(ts);
6057 GRN_LOG(ctx,
6058 GRN_LOG_DEBUG,
6059 "d0=%d d1=%d",
6060 db0->header.nterms,
6061 db1->header.nterms);
6062 return GRN_SUCCESS;
6063 }
6064
6065 static void
6066 array_update(grn_ctx *ctx, grn_ii *ii, uint32_t dls, buffer *db)
6067 {
6068 uint16_t n;
6069 buffer_term *bt;
6070 uint32_t loffset = POS_LOFFSET_HEADER;
6071 uint32_t *a;
6072 for (n = db->header.nterms, bt = db->terms; n; n--, bt++) {
6073 if (bt->tid) {
6074 grn_id tid = CHUNK_SPLIT_OFF(bt->tid);
6075 if ((a = array_at(ctx, ii, tid))) {
6076 a[0] = grn_ii_pos_pack(ii, dls, loffset);
6077 array_unref(ctx, ii, tid);
6078 } else {
6079 GRN_LOG(ctx, GRN_LOG_WARNING, "array_at failed (%d)", tid);
6080 }
6081 }
6082 loffset += POS_LOFFSET_HEADER;
6083 }
6084 }
6085
6086 static inline grn_rc
6087 buffer_split_internal(grn_ctx *ctx, grn_ii *ii, uint32_t lseg, grn_hash *h)
6088 {
6089 grn_io_win sw, dw0, dw1;
6090 buffer *sb, *db0 = NULL, *db1 = NULL;
6091 uint32_t dps0 = 0, dps1 = 0, dls0 = 0, dls1 = 0, sps, scn, dcn0 = 0, dcn1 = 0;
6092 if (grn_ii_get_buffer_pseg_inline(ii, lseg) == GRN_II_PSEG_NOT_ASSIGNED) {
6093 GRN_DEFINE_NAME(ii);
6094 CRIT(GRN_FILE_CORRUPT,
6095 "[ii][buffer][split] invalid segment: "
6096 "<%.*s> :"
6097 "request:<%u>, max:<%u>",
6098 name_size,
6099 name,
6100 lseg,
6101 ii->seg->header->max_segment);
6102 return ctx->rc;
6103 }
6104 buffer_segment_reserve(ctx, ii, &dls0, &dps0, &dls1, &dps1);
6105 if (ctx->rc != GRN_SUCCESS) {
6106 GRN_DEFINE_NAME(ii);
6107 ERR(ctx->rc,
6108 "[ii][buffer][split] failed to reserve buffer segments: "
6109 "<%.*s> :"
6110 "request:<%u>, max:<%u>",
6111 name_size,
6112 name,
6113 lseg,
6114 ii->seg->header->max_segment);
6115 return ctx->rc;
6116 }
6117 sps = buffer_open(ctx, ii, grn_ii_pos_pack(ii, lseg, 0), NULL, &sb);
6118 if (sps == GRN_II_PSEG_NOT_ASSIGNED) {
6119 GRN_DEFINE_NAME(ii);
6120 MERR("[ii][buffer][split] failed to open buffer: "
6121 "<%.*s> :"
6122 "segment:<%u>, position:<%u>, max-segment:<%u>",
6123 name_size,
6124 name,
6125 lseg,
6126 grn_ii_pos_pack(ii, lseg, 0),
6127 ii->seg->header->max_segment);
6128 } else {
6129 db0 = static_cast<buffer *>(grn_io_seg_ref(ctx, ii->seg, dps0));
6130 if (db0) {
6131 db1 = static_cast<buffer *>(grn_io_seg_ref(ctx, ii->seg, dps1));
6132 if (db1) {
6133 const uint8_t *sc = NULL;
6134 if ((scn = sb->header.chunk) == GRN_II_PSEG_NOT_ASSIGNED ||
6135 (sc = static_cast<const uint8_t *>(WIN_MAP(ctx,
6136 ii->chunk,
6137 &sw,
6138 scn,
6139 0,
6140 sb->header.chunk_size,
6141 GRN_IO_RDONLY)))) {
6142 term_split(ctx, ii->lexicon, sb, db0, db1);
6143 uint8_t *dc0 = NULL;
6144 grn_merging_data merging_data;
6145 grn_merging_data_init(ctx, &merging_data, ii);
6146 buffer_merge(ctx, ii, lseg, h, sb, sc, db0, &dc0, &merging_data);
6147 if (ctx->rc == GRN_SUCCESS) {
6148 const uint32_t actual_db0_chunk_size = db0->header.chunk_size;
6149 bool need_db0_chunk_free = false;
6150 if (actual_db0_chunk_size > 0) {
6151 chunk_new(ctx, ii, &dcn0, actual_db0_chunk_size);
6152 if (ctx->rc == GRN_SUCCESS) {
6153 need_db0_chunk_free = true;
6154 }
6155 }
6156 if (ctx->rc == GRN_SUCCESS) {
6157 grn_rc rc;
6158 db0->header.chunk =
6159 actual_db0_chunk_size ? dcn0 : GRN_II_PSEG_NOT_ASSIGNED;
6160 fake_map(ctx, ii->chunk, &dw0, dc0, dcn0, actual_db0_chunk_size);
6161 rc = grn_io_win_unmap(ctx, &dw0);
6162 if (rc == GRN_SUCCESS) {
6163 dc0 = NULL;
6164 uint8_t *dc1 = NULL;
6165 buffer_merge(ctx,
6166 ii,
6167 lseg,
6168 h,
6169 sb,
6170 sc,
6171 db1,
6172 &dc1,
6173 &merging_data);
6174 if (ctx->rc == GRN_SUCCESS) {
6175 const uint32_t actual_db1_chunk_size = db1->header.chunk_size;
6176 bool need_db1_chunk_free = false;
6177 if (actual_db1_chunk_size > 0) {
6178 chunk_new(ctx, ii, &dcn1, actual_db1_chunk_size);
6179 if (ctx->rc == GRN_SUCCESS) {
6180 need_db1_chunk_free = true;
6181 }
6182 }
6183 if (ctx->rc == GRN_SUCCESS) {
6184 fake_map(ctx,
6185 ii->chunk,
6186 &dw1,
6187 dc1,
6188 dcn1,
6189 actual_db1_chunk_size);
6190 rc = grn_io_win_unmap(ctx, &dw1);
6191 if (rc == GRN_SUCCESS) {
6192 dc1 = NULL;
6193 db1->header.chunk = (actual_db1_chunk_size > 0)
6194 ? dcn1
6195 : GRN_II_PSEG_NOT_ASSIGNED;
6196 buffer_segment_update(ii, dls0, dps0);
6197 buffer_segment_update(ii, dls1, dps1);
6198 array_update(ctx, ii, dls0, db0);
6199 array_update(ctx, ii, dls1, db1);
6200 buffer_segment_clear(ii, lseg);
6201 ii->header.common->total_chunk_size +=
6202 actual_db0_chunk_size + actual_db1_chunk_size;
6203 need_db0_chunk_free = false;
6204 need_db1_chunk_free = false;
6205 merging_data.succeeded = true;
6206 if (scn != GRN_II_PSEG_NOT_ASSIGNED) {
6207 chunk_free(ctx, ii, scn, sb->header.chunk_size);
6208 ii->header.common->total_chunk_size -=
6209 sb->header.chunk_size;
6210 }
6211 } else {
6212 GRN_DEFINE_NAME(ii);
6213 ERR(rc,
6214 "[ii][buffer][merge] "
6215 "failed to unmap a destination chunk2: "
6216 "<%.*s>: "
6217 "segment:<%u>, "
6218 "destination-chunk1:<%u>, "
6219 "destination-chunk2:<%u>, "
6220 "actual-size1:<%u>, "
6221 "actual-size2:<%u>",
6222 name_size,
6223 name,
6224 lseg,
6225 dcn0,
6226 dcn1,
6227 actual_db0_chunk_size,
6228 actual_db1_chunk_size);
6229 }
6230 }
6231 if (need_db1_chunk_free) {
6232 chunk_free(ctx, ii, dcn1, actual_db1_chunk_size);
6233 }
6234 if (dc1) {
6235 GRN_FREE(dc1);
6236 }
6237 }
6238 } else {
6239 GRN_DEFINE_NAME(ii);
6240 ERR(rc,
6241 "[ii][buffer][merge] "
6242 "failed to unmap a destination chunk1: "
6243 "<%.*s> :"
6244 "segment:<%u>, "
6245 "destination-chunk1:<%u>, "
6246 "actual-size1:<%u>",
6247 name_size,
6248 name,
6249 lseg,
6250 dcn0,
6251 actual_db0_chunk_size);
6252 }
6253 }
6254 if (need_db0_chunk_free) {
6255 chunk_free(ctx, ii, dcn0, actual_db0_chunk_size);
6256 }
6257 if (dc0) {
6258 GRN_FREE(dc0);
6259 }
6260 }
6261 grn_merging_data_fin(ctx, &merging_data);
6262 if (scn != GRN_II_PSEG_NOT_ASSIGNED) {
6263 grn_io_win_unmap(ctx, &sw);
6264 }
6265 } else {
6266 GRN_DEFINE_NAME(ii);
6267 MERR("[ii][buffer][split] failed to map a source chunk: "
6268 "<%.*s> :"
6269 "segment:<%u>, "
6270 "source-segment:<%u>, "
6271 "chunk-size:<%u>",
6272 name_size,
6273 name,
6274 lseg,
6275 scn,
6276 sb->header.chunk_size);
6277 }
6278 grn_io_seg_unref(ctx, ii->seg, dps1);
6279 } else {
6280 GRN_DEFINE_NAME(ii);
6281 MERR("[ii][buffer][split] failed to allocate a destination segment2: "
6282 "<%.*s>: "
6283 "segment:<%u>, "
6284 "destination-segment1:<%u>, "
6285 "destination-segment2:<%u>",
6286 name_size,
6287 name,
6288 lseg,
6289 dps0,
6290 dps1);
6291 }
6292 grn_io_seg_unref(ctx, ii->seg, dps0);
6293 } else {
6294 GRN_DEFINE_NAME(ii);
6295 MERR("[ii][buffer][split] failed to allocate a destination segment1: "
6296 "<%.*s>: "
6297 "segment:<%u>, "
6298 "destination-segment1:<%u>, "
6299 "destination-segment2:<%u>",
6300 name_size,
6301 name,
6302 lseg,
6303 dps0,
6304 dps1);
6305 }
6306 buffer_close(ctx, ii, sps);
6307 }
6308 return ctx->rc;
6309 }
6310
6311 static grn_rc
6312 buffer_split(grn_ctx *ctx, grn_ii *ii, uint32_t lseg, grn_hash *h)
6313 {
6314 GRN_SLOW_LOG_PUSH(ctx, GRN_LOG_DEBUG);
6315 grn_rc rc = buffer_split_internal(ctx, ii, lseg, h);
6316 GRN_SLOW_LOG_POP_BEGIN(ctx, GRN_LOG_DEBUG, elapsed_time)
6317 {
6318 GRN_DEFINE_NAME(ii);
6319 GRN_LOG(ctx,
6320 GRN_LOG_DEBUG,
6321 "[ii][buffer][split][slow][%f] "
6322 "<%.*s>: "
6323 "physical-segment:<%u>, "
6324 "logical-segment:<%u>",
6325 elapsed_time,
6326 name_size,
6327 name,
6328 grn_ii_get_buffer_pseg_inline(ii, lseg),
6329 lseg);
6330 }
6331 GRN_SLOW_LOG_POP_END(ctx);
6332 return rc;
6333 }
6334
6335 #define SCALE_FACTOR 2048
6336 #define MAX_NTERMS 8192
6337 #define SPLIT_COND(ii, buffer) \
6338 ((buffer)->header.nterms > 1024 || \
6339 ((buffer)->header.nterms > 1 && (buffer)->header.chunk_size * 100 > \
6340 (ii)->header.common->total_chunk_size))
6341
6342 static inline void
6343 buffer_new_find_segment(grn_ctx *ctx,
6344 grn_ii *ii,
6345 int size,
6346 grn_id tid,
6347 grn_hash *h,
6348 buffer **b,
6349 uint32_t *lseg,
6350 uint32_t *pseg)
6351 {
6352 uint32_t *a;
6353
6354 a = array_at(ctx, ii, tid);
6355 if (!a) {
6356 return;
6357 }
6358
6359 for (;;) {
6360 uint32_t pos = a[0];
6361 if (!pos || POS_IS_EMBED(pos)) {
6362 break;
6363 }
6364 *pseg = buffer_open(ctx, ii, pos, NULL, b);
6365 if (*pseg == GRN_II_PSEG_NOT_ASSIGNED) {
6366 break;
6367 }
6368 if ((*b)->header.buffer_free >= size + sizeof(buffer_term)) {
6369 *lseg = grn_ii_pos_lseg(ii, pos);
6370 break;
6371 }
6372 buffer_close(ctx, ii, *pseg);
6373 if (SPLIT_COND(ii, (*b))) {
6374 /* ((S_SEGMENT - sizeof(buffer_header) + ii->header.common->bmax -
6375 (*b)->header.nterms * sizeof(buffer_term)) * 4 <
6376 (*b)->header.chunk_size) */
6377 GRN_LOG(ctx,
6378 GRN_LOG_DEBUG,
6379 "nterms=%d chunk=%d total=%" GRN_FMT_INT64U,
6380 (*b)->header.nterms,
6381 (*b)->header.chunk_size,
6382 ii->header.common->total_chunk_size >> 10);
6383 if (buffer_split(ctx, ii, grn_ii_pos_lseg(ii, pos), h)) {
6384 break;
6385 }
6386 } else {
6387 if (S_SEGMENT - sizeof(buffer_header) -
6388 (*b)->header.nterms * sizeof(buffer_term) <
6389 size + sizeof(buffer_term)) {
6390 break;
6391 }
6392 if (buffer_flush(ctx, ii, grn_ii_pos_lseg(ii, pos), h)) {
6393 break;
6394 }
6395 }
6396 }
6397
6398 array_unref(ctx, ii, tid);
6399 }
6400
6401 static inline void
6402 buffer_new_lexicon_pat(grn_ctx *ctx,
6403 grn_ii *ii,
6404 int size,
6405 grn_id id,
6406 grn_hash *h,
6407 buffer **b,
6408 uint32_t *lseg,
6409 uint32_t *pseg)
6410 {
6411 grn_pat_cursor *cursor;
6412 char key[GRN_TABLE_MAX_KEY_SIZE];
6413 int key_size;
6414
6415 key_size =
6416 grn_table_get_key(ctx, ii->lexicon, id, key, GRN_TABLE_MAX_KEY_SIZE);
6417 if (ii->lexicon->header.flags & GRN_OBJ_KEY_VAR_SIZE) {
6418 grn_obj *tokenizer = NULL;
6419
6420 grn_table_get_info(ctx, ii->lexicon, NULL, NULL, &tokenizer, NULL, NULL);
6421 if (tokenizer) {
6422 /* For natural language */
6423 cursor = grn_pat_cursor_open(ctx,
6424 (grn_pat *)(ii->lexicon),
6425 key,
6426 key_size,
6427 NULL,
6428 0,
6429 0,
6430 -1,
6431 GRN_CURSOR_ASCENDING | GRN_CURSOR_GT);
6432 if (cursor) {
6433 grn_id tid;
6434 while (ctx->rc == GRN_SUCCESS && *lseg == GRN_II_PSEG_NOT_ASSIGNED &&
6435 (tid = grn_pat_cursor_next(ctx, cursor))) {
6436 buffer_new_find_segment(ctx, ii, size, tid, h, b, lseg, pseg);
6437 }
6438 grn_pat_cursor_close(ctx, cursor);
6439 }
6440 } else {
6441 /* For binary data or text data */
6442 int target_key_size = key_size;
6443 int reduced_key_size = 0;
6444
6445 bool is_binary_data = (ctx->encoding == GRN_ENC_NONE);
6446
6447 while (*lseg == GRN_II_PSEG_NOT_ASSIGNED && target_key_size > 0) {
6448 grn_id tid;
6449
6450 cursor = grn_pat_cursor_open(ctx,
6451 (grn_pat *)(ii->lexicon),
6452 key,
6453 target_key_size,
6454 NULL,
6455 0,
6456 0,
6457 -1,
6458 GRN_CURSOR_PREFIX);
6459 if (!cursor) {
6460 break;
6461 }
6462
6463 if (reduced_key_size == 0) {
6464 while (ctx->rc == GRN_SUCCESS && *lseg == GRN_II_PSEG_NOT_ASSIGNED &&
6465 (tid = grn_pat_cursor_next(ctx, cursor))) {
6466 buffer_new_find_segment(ctx, ii, size, tid, h, b, lseg, pseg);
6467 }
6468 } else {
6469 while (ctx->rc == GRN_SUCCESS && *lseg == GRN_II_PSEG_NOT_ASSIGNED &&
6470 (tid = grn_pat_cursor_next(ctx, cursor))) {
6471 void *current_key;
6472 int current_key_size;
6473
6474 current_key_size =
6475 grn_pat_cursor_get_key(ctx, cursor, &current_key);
6476 if (memcmp(((char *)current_key) + target_key_size,
6477 key + target_key_size,
6478 reduced_key_size) == 0) {
6479 continue;
6480 }
6481 buffer_new_find_segment(ctx, ii, size, tid, h, b, lseg, pseg);
6482 }
6483 }
6484 grn_pat_cursor_close(ctx, cursor);
6485
6486 if (reduced_key_size == 0) {
6487 reduced_key_size = 1;
6488 } else {
6489 if (is_binary_data) {
6490 reduced_key_size *= 2;
6491 }
6492 }
6493 target_key_size -= reduced_key_size;
6494 }
6495 }
6496 } else {
6497 /* For other data */
6498 cursor = grn_pat_cursor_open(ctx,
6499 (grn_pat *)(ii->lexicon),
6500 NULL,
6501 0,
6502 key,
6503 key_size,
6504 0,
6505 -1,
6506 GRN_CURSOR_PREFIX);
6507 if (cursor) {
6508 grn_id tid;
6509 while (ctx->rc == GRN_SUCCESS && *lseg == GRN_II_PSEG_NOT_ASSIGNED &&
6510 (tid = grn_pat_cursor_next(ctx, cursor))) {
6511 buffer_new_find_segment(ctx, ii, size, tid, h, b, lseg, pseg);
6512 }
6513 grn_pat_cursor_close(ctx, cursor);
6514 }
6515 }
6516 }
6517
6518 static inline void
6519 buffer_new_lexicon_other(grn_ctx *ctx,
6520 grn_ii *ii,
6521 int size,
6522 grn_id id,
6523 grn_hash *h,
6524 buffer **b,
6525 uint32_t *lseg,
6526 uint32_t *pseg)
6527 {
6528 GRN_TABLE_EACH_BEGIN(ctx, ii->lexicon, cursor, tid)
6529 {
6530 if (ctx->rc != GRN_SUCCESS || *lseg != GRN_II_PSEG_NOT_ASSIGNED) {
6531 break;
6532 }
6533 buffer_new_find_segment(ctx, ii, size, tid, h, b, lseg, pseg);
6534 }
6535 GRN_TABLE_EACH_END(ctx, cursor);
6536 }
6537
6538 static inline uint32_t
6539 buffer_new_internal(grn_ctx *ctx,
6540 grn_ii *ii,
6541 int size,
6542 uint32_t *pos,
6543 buffer_term **bt,
6544 buffer_rec **br,
6545 buffer **bp,
6546 grn_id id,
6547 grn_hash *h)
6548 {
6549 buffer *b = NULL;
6550 uint16_t offset;
6551 uint32_t lseg = GRN_II_PSEG_NOT_ASSIGNED, pseg = GRN_II_PSEG_NOT_ASSIGNED;
6552 if (S_SEGMENT - sizeof(buffer_header) < size + sizeof(buffer_term)) {
6553 GRN_DEFINE_NAME(ii);
6554 MERR("[ii][buffer][new] requested size is too large: "
6555 "<%.*s> :"
6556 "requested:<%" GRN_FMT_SIZE ">, max:<%" GRN_FMT_SIZE ">",
6557 name_size,
6558 name,
6559 (size_t)(size + sizeof(buffer_term)),
6560 (size_t)(S_SEGMENT - sizeof(buffer_header)));
6561 return GRN_II_PSEG_NOT_ASSIGNED;
6562 }
6563 if (ii->lexicon->header.type == GRN_TABLE_PAT_KEY) {
6564 buffer_new_lexicon_pat(ctx, ii, size, id, h, &b, &lseg, &pseg);
6565 } else {
6566 buffer_new_lexicon_other(ctx, ii, size, id, h, &b, &lseg, &pseg);
6567 }
6568 if (lseg == GRN_II_PSEG_NOT_ASSIGNED) {
6569 if (buffer_segment_new(ctx, ii, &lseg) ||
6570 (pseg = buffer_open(ctx, ii, grn_ii_pos_pack(ii, lseg, 0), NULL, &b)) ==
6571 GRN_II_PSEG_NOT_ASSIGNED) {
6572 return GRN_II_PSEG_NOT_ASSIGNED;
6573 }
6574 memset(b, 0, S_SEGMENT);
6575 b->header.buffer_free = S_SEGMENT - sizeof(buffer_header);
6576 b->header.chunk = GRN_II_PSEG_NOT_ASSIGNED;
6577 }
6578 if (b->header.nterms_void) {
6579 for (offset = 0; offset < b->header.nterms; offset++) {
6580 if (!b->terms[offset].tid) {
6581 break;
6582 }
6583 }
6584 if (offset == b->header.nterms) {
6585 GRN_LOG(ctx, GRN_LOG_DEBUG, "inconsistent buffer(%d)", lseg);
6586 b->header.nterms_void = 0;
6587 b->header.nterms++;
6588 b->header.buffer_free -= size + sizeof(buffer_term);
6589 } else {
6590 b->header.nterms_void--;
6591 b->header.buffer_free -= size;
6592 }
6593 } else {
6594 offset = b->header.nterms++;
6595 b->header.buffer_free -= size + sizeof(buffer_term);
6596 }
6597 *pos =
6598 grn_ii_pos_pack(ii, lseg, POS_LOFFSET_HEADER + POS_LOFFSET_TERM * offset);
6599 *bt = &b->terms[offset];
6600 *br = (buffer_rec *)(((byte *)&b->terms[b->header.nterms]) +
6601 b->header.buffer_free);
6602 *bp = b;
6603 return pseg;
6604 }
6605
6606 static inline uint32_t
6607 buffer_new(grn_ctx *ctx,
6608 grn_ii *ii,
6609 int size,
6610 uint32_t *pos,
6611 buffer_term **bt,
6612 buffer_rec **br,
6613 buffer **bp,
6614 grn_id id,
6615 grn_hash *h)
6616 {
6617 GRN_SLOW_LOG_PUSH(ctx, GRN_LOG_DEBUG);
6618 uint32_t pseg = buffer_new_internal(ctx, ii, size, pos, bt, br, bp, id, h);
6619 GRN_SLOW_LOG_POP_BEGIN(ctx, GRN_LOG_DEBUG, elapsed_time)
6620 {
6621 GRN_DEFINE_NAME(ii);
6622 grn_obj term;
6623 GRN_TEXT_INIT(&term, 0);
6624 grn_ii_get_term(ctx, ii, id, &term);
6625 GRN_LOG(ctx,
6626 GRN_LOG_DEBUG,
6627 "[ii][buffer][new][slow][%f] "
6628 "<%.*s>: "
6629 "<%.*s>(%u): "
6630 "size:<%u>, "
6631 "physical-segment:<%u>",
6632 elapsed_time,
6633 name_size,
6634 name,
6635 (int)GRN_TEXT_LEN(&term),
6636 GRN_TEXT_VALUE(&term),
6637 id,
6638 size,
6639 pseg);
6640 GRN_OBJ_FIN(ctx, &term);
6641 }
6642 GRN_SLOW_LOG_POP_END(ctx);
6643 return pseg;
6644 }
6645
6646 /* ii */
6647
6648 static grn_ii *
6649 _grn_ii_create(
6650 grn_ctx *ctx, grn_ii *ii, const char *path, grn_obj *lexicon, uint32_t flags)
6651 {
6652 int i;
6653 uint32_t header_size;
6654 uint32_t max_n_segments;
6655 uint32_t max_n_chunks;
6656 grn_io *seg, *chunk;
6657 char path2[PATH_MAX];
6658 grn_ii_header_common *header;
6659 grn_table_flags lflags;
6660 grn_encoding encoding;
6661 grn_obj *tokenizer;
6662 /*
6663 for (i = 0; i < 32; i++) {
6664 new_histogram[i] = 0;
6665 free_histogram[i] = 0;
6666 }
6667 */
6668 if (grn_table_get_info(ctx,
6669 lexicon,
6670 &lflags,
6671 &encoding,
6672 &tokenizer,
6673 NULL,
6674 NULL)) {
6675 return NULL;
6676 }
6677 if (path && strlen(path) + 6 >= PATH_MAX) {
6678 return NULL;
6679 }
6680
6681 if (!grn_ii_pos_is_available(ctx, flags, "[ii][create]")) {
6682 return NULL;
6683 }
6684
6685 if (flags & GRN_OBJ_INDEX_SMALL) {
6686 header_size = sizeof(grn_ii_header_normal);
6687 max_n_segments = grn_ii_max_n_segments_small;
6688 max_n_chunks = grn_ii_max_n_chunks_small;
6689 } else if (flags & GRN_OBJ_INDEX_MEDIUM) {
6690 header_size = sizeof(grn_ii_header_normal);
6691 max_n_segments = MAX_PSEG_MEDIUM;
6692 max_n_chunks = GRN_II_MAX_CHUNK_MEDIUM;
6693 } else if (flags & GRN_OBJ_INDEX_LARGE) {
6694 header_size = sizeof(grn_ii_header_large);
6695 max_n_segments = MAX_PSEG_LARGE;
6696 max_n_chunks = GRN_II_MAX_CHUNK;
6697 } else {
6698 header_size = sizeof(grn_ii_header_normal);
6699 max_n_segments = MAX_PSEG;
6700 max_n_chunks = GRN_II_MAX_CHUNK;
6701 }
6702
6703 seg = grn_io_create(ctx,
6704 path,
6705 header_size,
6706 S_SEGMENT,
6707 max_n_segments,
6708 GRN_IO_AUTO,
6709 GRN_IO_EXPIRE_SEGMENT);
6710 if (!seg) {
6711 return NULL;
6712 }
6713 if (path) {
6714 grn_strcpy(path2, PATH_MAX, path);
6715 grn_strcat(path2, PATH_MAX, ".c");
6716 chunk = grn_io_create(ctx,
6717 path2,
6718 0,
6719 S_CHUNK,
6720 max_n_chunks,
6721 GRN_IO_AUTO,
6722 GRN_IO_EXPIRE_SEGMENT);
6723 } else {
6724 chunk = grn_io_create(ctx, NULL, 0, S_CHUNK, max_n_chunks, GRN_IO_AUTO, 0);
6725 }
6726 if (!chunk) {
6727 grn_io_close(ctx, seg);
6728 grn_io_remove(ctx, path);
6729 return NULL;
6730 }
6731 header = static_cast<grn_ii_header_common *>(grn_io_header(seg));
6732 grn_io_set_type(seg, GRN_COLUMN_INDEX);
6733 for (i = 0; i < GRN_II_MAX_LSEG; i++) {
6734 header->ainfo[i] = GRN_II_PSEG_NOT_ASSIGNED;
6735 header->binfo[i] = GRN_II_PSEG_NOT_ASSIGNED;
6736 }
6737 if (flags & GRN_OBJ_INDEX_LARGE) {
6738 grn_ii_header_large *header_large = (grn_ii_header_large *)header;
6739 for (i = 0; i < GRN_II_MAX_LSEG_EXTEND; i++) {
6740 header_large->ainfo_extend[i] = GRN_II_PSEG_NOT_ASSIGNED;
6741 header_large->binfo_extend[i] = GRN_II_PSEG_NOT_ASSIGNED;
6742 }
6743 }
6744 for (i = 0; i <= GRN_II_N_CHUNK_VARIATION; i++) {
6745 header->free_chunks[i] = GRN_II_PSEG_NOT_ASSIGNED;
6746 header->garbages[i] = GRN_II_PSEG_NOT_ASSIGNED;
6747 }
6748 header->flags = flags;
6749 ii->seg = seg;
6750 ii->chunk = chunk;
6751 ii->lexicon = grn_ctx_at(ctx, DB_OBJ(lexicon)->id);
6752 ii->lflags = lflags;
6753 ii->encoding = encoding;
6754 ii->header.common = header;
6755 ii->n_elements = 2;
6756 if ((flags & GRN_OBJ_WITH_SECTION)) {
6757 ii->n_elements++;
6758 }
6759 if ((flags & GRN_OBJ_WITH_WEIGHT)) {
6760 ii->n_elements++;
6761 }
6762 if ((flags & GRN_OBJ_WITH_POSITION)) {
6763 ii->n_elements++;
6764 }
6765 ii->wal_touched = false;
6766 return ii;
6767 }
6768
6769 extern "C" grn_ii *
6770 grn_ii_create(grn_ctx *ctx, const char *path, grn_obj *lexicon, uint32_t flags)
6771 {
6772 auto ii = static_cast<grn_ii *>(GRN_CALLOC(sizeof(grn_ii)));
6773 if (!ii) {
6774 return NULL;
6775 }
6776 GRN_DB_OBJ_SET_TYPE(ii, GRN_COLUMN_INDEX);
6777 if (!_grn_ii_create(ctx, ii, path, lexicon, flags)) {
6778 GRN_FREE(ii);
6779 return NULL;
6780 }
6781 return ii;
6782 }
6783
6784 extern "C" grn_rc
6785 grn_ii_remove(grn_ctx *ctx, const char *path)
6786 {
6787 grn_rc rc;
6788 char buffer[PATH_MAX];
6789 if (!path || strlen(path) > PATH_MAX - 4) {
6790 return GRN_INVALID_ARGUMENT;
6791 }
6792 grn_rc wal_rc = grn_wal_remove(ctx, path, "[ii]");
6793 if ((rc = grn_io_remove(ctx, path))) {
6794 goto exit;
6795 }
6796 grn_snprintf(buffer, PATH_MAX, PATH_MAX, "%s.c", path);
6797 rc = grn_io_remove(ctx, buffer);
6798 if (rc == GRN_SUCCESS) {
6799 rc = wal_rc;
6800 }
6801 exit:
6802 return rc;
6803 }
6804
6805 extern "C" grn_rc
6806 grn_ii_truncate(grn_ctx *ctx, grn_ii *ii)
6807 {
6808 grn_rc rc;
6809 const char *io_segpath;
6810 char *segpath = NULL;
6811 grn_obj *lexicon;
6812 uint32_t flags;
6813 if ((io_segpath = grn_io_path(ii->seg)) && *io_segpath != '\0') {
6814 if (!(segpath = GRN_STRDUP(io_segpath))) {
6815 ERR(GRN_NO_MEMORY_AVAILABLE, "cannot duplicate path: <%s>", io_segpath);
6816 return GRN_NO_MEMORY_AVAILABLE;
6817 }
6818 } else {
6819 segpath = NULL;
6820 }
6821 lexicon = ii->lexicon;
6822 flags = ii->header.common->flags;
6823 if ((rc = grn_io_close(ctx, ii->seg))) {
6824 goto exit;
6825 }
6826 if ((rc = grn_io_close(ctx, ii->chunk))) {
6827 goto exit;
6828 }
6829 ii->seg = NULL;
6830 ii->chunk = NULL;
6831 if (segpath && (rc = grn_ii_remove(ctx, segpath))) {
6832 goto exit;
6833 }
6834 if (!_grn_ii_create(ctx, ii, segpath, lexicon, flags)) {
6835 rc = GRN_UNKNOWN_ERROR;
6836 goto exit;
6837 }
6838 grn_obj_unref(ctx, lexicon);
6839 exit:
6840 if (segpath) {
6841 GRN_FREE(segpath);
6842 }
6843 return rc;
6844 }
6845
6846 extern "C" grn_ii *
6847 grn_ii_open(grn_ctx *ctx, const char *path, grn_obj *lexicon)
6848 {
6849 grn_io *seg, *chunk;
6850 char path2[PATH_MAX];
6851 grn_ii_header_common *header;
6852 uint32_t io_type;
6853 grn_table_flags lflags;
6854 grn_encoding encoding;
6855 grn_obj *tokenizer;
6856 if (grn_table_get_info(ctx,
6857 lexicon,
6858 &lflags,
6859 &encoding,
6860 &tokenizer,
6861 NULL,
6862 NULL)) {
6863 return NULL;
6864 }
6865 if (strlen(path) + 6 >= PATH_MAX) {
6866 return NULL;
6867 }
6868 grn_strcpy(path2, PATH_MAX, path);
6869 grn_strcat(path2, PATH_MAX, ".c");
6870 seg = grn_io_open(ctx, path, GRN_IO_AUTO);
6871 if (!seg) {
6872 return NULL;
6873 }
6874 chunk = grn_io_open(ctx, path2, GRN_IO_AUTO);
6875 if (!chunk) {
6876 grn_io_close(ctx, seg);
6877 return NULL;
6878 }
6879 header = static_cast<grn_ii_header_common *>(grn_io_header(seg));
6880 io_type = grn_io_get_type(seg);
6881 if (io_type != GRN_COLUMN_INDEX) {
6882 ERR(GRN_INVALID_FORMAT,
6883 "[column][index] file type must be %#04x: <%#04x>",
6884 GRN_COLUMN_INDEX,
6885 io_type);
6886 grn_io_close(ctx, seg);
6887 grn_io_close(ctx, chunk);
6888 return NULL;
6889 }
6890 auto ii = static_cast<grn_ii *>(GRN_CALLOC(sizeof(grn_ii)));
6891 if (!ii) {
6892 grn_io_close(ctx, seg);
6893 grn_io_close(ctx, chunk);
6894 return NULL;
6895 }
6896 GRN_DB_OBJ_SET_TYPE(ii, GRN_COLUMN_INDEX);
6897 ii->seg = seg;
6898 ii->chunk = chunk;
6899 ii->lexicon = grn_ctx_at(ctx, DB_OBJ(lexicon)->id);
6900 ii->lflags = lflags;
6901 ii->encoding = encoding;
6902 ii->header.common = header;
6903 ii->n_elements = 2;
6904 if ((header->flags & GRN_OBJ_WITH_SECTION)) {
6905 ii->n_elements++;
6906 }
6907 if ((header->flags & GRN_OBJ_WITH_WEIGHT)) {
6908 ii->n_elements++;
6909 }
6910 if ((header->flags & GRN_OBJ_WITH_POSITION)) {
6911 ii->n_elements++;
6912 }
6913 ii->wal_touched = false;
6914 return ii;
6915 }
6916
6917 extern "C" grn_rc
6918 grn_ii_close(grn_ctx *ctx, grn_ii *ii)
6919 {
6920 grn_rc rc = GRN_SUCCESS;
6921 if (!ii) {
6922 return GRN_INVALID_ARGUMENT;
6923 }
6924 if (ii->seg->path[0] != '\0' &&
6925 GRN_CTX_GET_WAL_ROLE(ctx) == GRN_WAL_ROLE_PRIMARY) {
6926 grn_obj_flush(ctx, (grn_obj *)ii);
6927 }
6928 {
6929 grn_rc sub_rc = grn_io_close(ctx, ii->seg);
6930 if (rc == GRN_SUCCESS) {
6931 rc = sub_rc;
6932 }
6933 }
6934 {
6935 grn_rc sub_rc = grn_io_close(ctx, ii->chunk);
6936 if (rc == GRN_SUCCESS) {
6937 rc = sub_rc;
6938 }
6939 }
6940 grn_obj_unref(ctx, ii->lexicon);
6941 GRN_FREE(ii);
6942 /*
6943 {
6944 int i;
6945 for (i = 0; i < 32; i++) {
6946 GRN_LOG(ctx, GRN_LOG_DEBUG, "new[%d]=%d free[%d]=%d",
6947 i, new_histogram[i],
6948 i, free_histogram[i]);
6949 }
6950 }
6951 */
6952 return rc;
6953 }
6954
6955 extern "C" grn_rc
6956 grn_ii_info(grn_ctx *ctx, grn_ii *ii, uint64_t *seg_size, uint64_t *chunk_size)
6957 {
6958 grn_rc rc;
6959
6960 if (seg_size) {
6961 if ((rc = grn_io_size(ctx, ii->seg, seg_size))) {
6962 return rc;
6963 }
6964 }
6965
6966 if (chunk_size) {
6967 if ((rc = grn_io_size(ctx, ii->chunk, chunk_size))) {
6968 return rc;
6969 }
6970 }
6971
6972 return GRN_SUCCESS;
6973 }
6974
6975 extern "C" grn_column_flags
6976 grn_ii_get_flags(grn_ctx *ctx, grn_ii *ii)
6977 {
6978 if (!ii) {
6979 return 0;
6980 }
6981
6982 return ii->header.common->flags;
6983 }
6984
6985 extern "C" uint32_t
6986 grn_ii_get_n_elements(grn_ctx *ctx, grn_ii *ii)
6987 {
6988 if (!ii) {
6989 return 0;
6990 }
6991
6992 return ii->n_elements;
6993 }
6994
6995 extern "C" grn_obj *
6996 grn_ii_get_lexicon(grn_ctx *ctx, grn_ii *ii)
6997 {
6998 if (!ii) {
6999 return NULL;
7000 }
7001
7002 return ii->lexicon;
7003 }
7004
7005 extern "C" void
7006 grn_ii_expire(grn_ctx *ctx, grn_ii *ii)
7007 {
7008 int64_t threshold = ii->chunk->max_map_seg / 2;
7009 /*
7010 grn_io_expire(ctx, ii->seg, 128, 1000000);
7011 */
7012 if (0 <= grn_ii_reduce_expire_threshold &&
7013 grn_ii_reduce_expire_threshold < threshold) {
7014 threshold = grn_ii_reduce_expire_threshold;
7015 }
7016 if (ii->chunk->nmaps > threshold) {
7017 grn_io_expire(ctx, ii->chunk, 0, 1000000);
7018 }
7019 }
7020
7021 extern "C" grn_rc
7022 grn_ii_flush(grn_ctx *ctx, grn_ii *ii)
7023 {
7024 grn_rc rc;
7025
7026 rc = grn_io_flush(ctx, ii->seg);
7027 if (rc == GRN_SUCCESS) {
7028 rc = grn_io_flush(ctx, ii->chunk);
7029 }
7030
7031 if (rc == GRN_SUCCESS) {
7032 ii->wal_touched = false;
7033 }
7034
7035 return rc;
7036 }
7037
7038 extern "C" size_t
7039 grn_ii_get_disk_usage(grn_ctx *ctx, grn_ii *ii)
7040 {
7041 size_t usage;
7042
7043 usage = grn_io_get_disk_usage(ctx, ii->seg);
7044 usage += grn_io_get_disk_usage(ctx, ii->chunk);
7045
7046 return usage;
7047 }
7048
7049 extern "C" void
7050 grn_ii_set_visibility(grn_ctx *ctx, grn_ii *ii, bool is_visible)
7051 {
7052 if (is_visible) {
7053 ii->header.common->flags &= ~GRN_OBJ_INVISIBLE;
7054 } else {
7055 ii->header.common->flags |= GRN_OBJ_INVISIBLE;
7056 }
7057 }
7058
7059 #define BIT11_01(x) ((x >> 1) & 0x7ff)
7060 #define BIT31_12(x) (x >> 12)
7061
7062 static inline grn_rc
7063 grn_ii_wal_touch(grn_ctx *ctx, grn_ii *ii, const char *tag)
7064 {
7065 if (ii->wal_touched) {
7066 return GRN_SUCCESS;
7067 }
7068
7069 if (GRN_CTX_GET_WAL_ROLE(ctx) == GRN_WAL_ROLE_NONE) {
7070 return GRN_SUCCESS;
7071 }
7072
7073 grn_rc rc = grn_wal_touch(ctx, (grn_obj *)ii, false, tag);
7074 if (rc == GRN_SUCCESS) {
7075 ii->wal_touched = true;
7076 }
7077 return rc;
7078 }
7079
7080 static inline grn_rc
7081 grn_ii_update_one_internal(
7082 grn_ctx *ctx, grn_ii *ii, grn_id tid, grn_ii_updspec *u, grn_hash *h)
7083 {
7084 const char *tag = "[ii][update][one]";
7085 buffer *b;
7086 uint8_t *bs;
7087 buffer_rec *br = NULL;
7088 buffer_term *bt;
7089 uint32_t pseg = 0, pos = 0, size, *a;
7090 if (!tid) {
7091 return ctx->rc;
7092 }
7093 if (!u->tf || !u->sid) {
7094 return grn_ii_delete_one(ctx, ii, tid, u, h);
7095 }
7096 if (u->sid > ii->header.common->smax) {
7097 ii->header.common->smax = u->sid;
7098 }
7099 if (!(a = array_get(ctx, ii, tid))) {
7100 grn_obj term;
7101 GRN_DEFINE_NAME(ii);
7102 GRN_TEXT_INIT(&term, 0);
7103 grn_ii_get_term(ctx, ii, tid, &term);
7104 MERR("%s failed to allocate an array: "
7105 "<%.*s>: "
7106 "<%.*s>(%u): "
7107 "(%u:%u)",
7108 tag,
7109 name_size,
7110 name,
7111 (int)GRN_TEXT_LEN(&term),
7112 GRN_TEXT_VALUE(&term),
7113 tid,
7114 u->rid,
7115 u->sid);
7116 GRN_OBJ_FIN(ctx, &term);
7117 return ctx->rc;
7118 }
7119 if (!(bs = encode_rec(ctx, ii, u, &size, 0))) {
7120 grn_obj term;
7121 GRN_DEFINE_NAME(ii);
7122 GRN_TEXT_INIT(&term, 0);
7123 grn_ii_get_term(ctx, ii, tid, &term);
7124 MERR("%s failed to encode a record: "
7125 "<%.*s>: "
7126 "<%.*s>(%u): "
7127 "(%u:%u)",
7128 tag,
7129 name_size,
7130 name,
7131 (int)GRN_TEXT_LEN(&term),
7132 GRN_TEXT_VALUE(&term),
7133 tid,
7134 u->rid,
7135 u->sid);
7136 GRN_OBJ_FIN(ctx, &term);
7137 goto exit;
7138 }
7139 if (grn_ii_wal_touch(ctx, ii, tag) != GRN_SUCCESS) {
7140 goto exit;
7141 }
7142 for (;;) {
7143 if (a[0]) {
7144 if (!POS_IS_EMBED(a[0])) {
7145 pos = a[0];
7146 if ((pseg = buffer_open(ctx, ii, pos, &bt, &b)) ==
7147 GRN_II_PSEG_NOT_ASSIGNED) {
7148 grn_obj term;
7149 GRN_DEFINE_NAME(ii);
7150 GRN_TEXT_INIT(&term, 0);
7151 grn_ii_get_term(ctx, ii, tid, &term);
7152 MERR("%s failed to allocate a buffer: "
7153 "<%.*s>: "
7154 "<%.*s>(%u): "
7155 "(%u:%u): "
7156 "segment:<%u>, "
7157 "free:<%u>, "
7158 "required:<%u>",
7159 tag,
7160 name_size,
7161 name,
7162 (int)GRN_TEXT_LEN(&term),
7163 GRN_TEXT_VALUE(&term),
7164 tid,
7165 u->rid,
7166 u->sid,
7167 pos,
7168 b->header.buffer_free,
7169 size);
7170 GRN_OBJ_FIN(ctx, &term);
7171 goto exit;
7172 }
7173 if (b->header.buffer_free < size) {
7174 int bfb = b->header.buffer_free;
7175 GRN_LOG(ctx,
7176 GRN_LOG_DEBUG,
7177 "flushing a[0]=%d seg=%d(%p) free=%d",
7178 a[0],
7179 grn_ii_pos_lseg(ii, a[0]),
7180 b,
7181 b->header.buffer_free);
7182 buffer_close(ctx, ii, pseg);
7183 if (SPLIT_COND(ii, b)) {
7184 /*((S_SEGMENT - sizeof(buffer_header) + ii->header.common->bmax -
7185 b->header.nterms * sizeof(buffer_term)) * 4 <
7186 b->header.chunk_size)*/
7187 GRN_LOG(ctx,
7188 GRN_LOG_DEBUG,
7189 "nterms=%d chunk=%d total=%" GRN_FMT_INT64U,
7190 b->header.nterms,
7191 b->header.chunk_size,
7192 ii->header.common->total_chunk_size >> 10);
7193 buffer_split(ctx, ii, grn_ii_pos_lseg(ii, pos), h);
7194 if (ctx->rc != GRN_SUCCESS) {
7195 grn_obj term;
7196 char errbuf[GRN_CTX_MSGSIZE];
7197 GRN_DEFINE_NAME(ii);
7198 GRN_TEXT_INIT(&term, 0);
7199 grn_ii_get_term(ctx, ii, tid, &term);
7200 grn_strcpy(errbuf, GRN_CTX_MSGSIZE, ctx->errbuf);
7201 ERR(ctx->rc,
7202 "%s failed to split a buffer: "
7203 "<%.*s>: "
7204 "<%.*s>(%u): "
7205 "(%u:%u): "
7206 "segment:<%u>, "
7207 "free:<%u>, "
7208 "required:<%u>, "
7209 "%s",
7210 tag,
7211 name_size,
7212 name,
7213 (int)GRN_TEXT_LEN(&term),
7214 GRN_TEXT_VALUE(&term),
7215 tid,
7216 u->rid,
7217 u->sid,
7218 pos,
7219 b->header.buffer_free,
7220 size,
7221 errbuf);
7222 GRN_OBJ_FIN(ctx, &term);
7223 goto exit;
7224 }
7225 continue;
7226 }
7227 buffer_flush(ctx, ii, grn_ii_pos_lseg(ii, pos), h);
7228 if (ctx->rc != GRN_SUCCESS) {
7229 grn_obj term;
7230 char errbuf[GRN_CTX_MSGSIZE];
7231 GRN_DEFINE_NAME(ii);
7232 GRN_TEXT_INIT(&term, 0);
7233 grn_ii_get_term(ctx, ii, tid, &term);
7234 grn_strcpy(errbuf, GRN_CTX_MSGSIZE, ctx->errbuf);
7235 ERR(ctx->rc,
7236 "%s failed to flush a buffer: "
7237 "<%.*s>: "
7238 "<%u>:<%u>:<%u>: "
7239 "term:<%.*s>, "
7240 "segment:<%u>, "
7241 "free:<%u>, "
7242 "required:<%u>: "
7243 "%s",
7244 tag,
7245 name_size,
7246 name,
7247 u->rid,
7248 u->sid,
7249 tid,
7250 (int)GRN_TEXT_LEN(&term),
7251 GRN_TEXT_VALUE(&term),
7252 pos,
7253 b->header.buffer_free,
7254 size,
7255 errbuf);
7256 GRN_OBJ_FIN(ctx, &term);
7257 goto exit;
7258 }
7259 if (a[0] != pos) {
7260 GRN_LOG(ctx,
7261 GRN_LOG_DEBUG,
7262 "grn_ii_update_one: a[0] changed %d->%d",
7263 a[0],
7264 pos);
7265 continue;
7266 }
7267 if ((pseg = buffer_open(ctx, ii, pos, &bt, &b)) ==
7268 GRN_II_PSEG_NOT_ASSIGNED) {
7269 GRN_LOG(ctx, GRN_LOG_CRIT, "buffer not found a[0]=%d", a[0]);
7270 {
7271 grn_obj term;
7272 GRN_DEFINE_NAME(ii);
7273 GRN_TEXT_INIT(&term, 0);
7274 grn_ii_get_term(ctx, ii, tid, &term);
7275 MERR("%s failed to reallocate a buffer: "
7276 "<%.*s>: "
7277 "<%.*s>(%u): "
7278 "(%u:%u): "
7279 "segment:<%u>, "
7280 "new-segment:<%u>, "
7281 "free:<%u>, "
7282 "required:<%u>",
7283 tag,
7284 name_size,
7285 name,
7286 (int)GRN_TEXT_LEN(&term),
7287 GRN_TEXT_VALUE(&term),
7288 tid,
7289 u->rid,
7290 u->sid,
7291 pos,
7292 a[0],
7293 b->header.buffer_free,
7294 size);
7295 GRN_OBJ_FIN(ctx, &term);
7296 }
7297 goto exit;
7298 }
7299 GRN_LOG(ctx,
7300 GRN_LOG_DEBUG,
7301 "flushed a[0]=%d seg=%d(%p) free=%d->%d nterms=%d v=%d",
7302 a[0],
7303 grn_ii_pos_lseg(ii, a[0]),
7304 b,
7305 bfb,
7306 b->header.buffer_free,
7307 b->header.nterms,
7308 b->header.nterms_void);
7309 if (b->header.buffer_free < size) {
7310 grn_obj term;
7311 GRN_DEFINE_NAME(ii);
7312 GRN_TEXT_INIT(&term, 0);
7313 grn_ii_get_term(ctx, ii, tid, &term);
7314 MERR("%s buffer is full: "
7315 "<%.*s>: "
7316 "<%.*s>(%u): "
7317 "(%u:%u): "
7318 "segment:<%u>, "
7319 "new-segment:<%u>, "
7320 "free:<%u>, "
7321 "required:<%u>",
7322 tag,
7323 name_size,
7324 name,
7325 (int)GRN_TEXT_LEN(&term),
7326 GRN_TEXT_VALUE(&term),
7327 tid,
7328 u->rid,
7329 u->sid,
7330 pos,
7331 a[0],
7332 b->header.buffer_free,
7333 size);
7334 GRN_OBJ_FIN(ctx, &term);
7335 buffer_close(ctx, ii, pseg);
7336 /* todo: direct merge */
7337 goto exit;
7338 }
7339 }
7340 b->header.buffer_free -= size;
7341 br = (buffer_rec *)(((byte *)&b->terms[b->header.nterms]) +
7342 b->header.buffer_free);
7343 } else {
7344 grn_ii_updspec u2;
7345 uint32_t size2 = 0, v = a[0];
7346 struct _grn_ii_pos pos2;
7347 pos2.pos = a[1];
7348 pos2.next = NULL;
7349 u2.pos = &pos2;
7350 if ((ii->header.common->flags & GRN_OBJ_WITH_SECTION)) {
7351 u2.rid = POS_RID_SID_EXTRACT_RID(v);
7352 u2.sid = POS_RID_SID_EXTRACT_SID(v);
7353 } else {
7354 u2.rid = POS_RID_EXTRACT(v);
7355 u2.sid = 1;
7356 }
7357 u2.tf = 1;
7358 u2.weight = 0;
7359 if (u2.rid != u->rid || u2.sid != u->sid) {
7360 uint8_t *bs2 = encode_rec(ctx, ii, &u2, &size2, 0);
7361 if (!bs2) {
7362 grn_obj term;
7363 GRN_DEFINE_NAME(ii);
7364 GRN_TEXT_INIT(&term, 0);
7365 grn_ii_get_term(ctx, ii, tid, &term);
7366 MERR("%s failed to encode a record2: "
7367 "<%.*s>: "
7368 "<%.*s>(%u): "
7369 "(%u:%u)",
7370 tag,
7371 name_size,
7372 name,
7373 (int)GRN_TEXT_LEN(&term),
7374 GRN_TEXT_VALUE(&term),
7375 tid,
7376 u2.rid,
7377 u2.sid);
7378 GRN_OBJ_FIN(ctx, &term);
7379 goto exit;
7380 }
7381 pseg = buffer_new(ctx, ii, size + size2, &pos, &bt, &br, &b, tid, h);
7382 if (pseg == GRN_II_PSEG_NOT_ASSIGNED) {
7383 GRN_FREE(bs2);
7384 {
7385 grn_obj term;
7386 GRN_DEFINE_NAME(ii);
7387 GRN_TEXT_INIT(&term, 0);
7388 grn_ii_get_term(ctx, ii, tid, &term);
7389 MERR("%s failed to create a buffer2: "
7390 "<%.*s>: "
7391 "<%.*s>(%u): "
7392 "(%u:%u): "
7393 "size:<%u>",
7394 tag,
7395 name_size,
7396 name,
7397 (int)GRN_TEXT_LEN(&term),
7398 GRN_TEXT_VALUE(&term),
7399 tid,
7400 u2.rid,
7401 u2.sid,
7402 size + size2);
7403 GRN_OBJ_FIN(ctx, &term);
7404 }
7405 goto exit;
7406 }
7407 bt->tid = tid;
7408 bt->size_in_chunk = 0;
7409 bt->pos_in_chunk = 0;
7410 bt->size_in_buffer = 0;
7411 bt->pos_in_buffer = 0;
7412 buffer_put(ctx, ii, b, bt, br, bs2, &u2, size2);
7413 if (ctx->rc != GRN_SUCCESS) {
7414 GRN_FREE(bs2);
7415 buffer_close(ctx, ii, pseg);
7416 {
7417 grn_obj term;
7418 char errbuf[GRN_CTX_MSGSIZE];
7419 GRN_DEFINE_NAME(ii);
7420 GRN_TEXT_INIT(&term, 0);
7421 grn_ii_get_term(ctx, ii, tid, &term);
7422 grn_strcpy(errbuf, GRN_CTX_MSGSIZE, ctx->errbuf);
7423 MERR("%s failed to put to buffer: "
7424 "<%.*s>: "
7425 "<%.*s>(%u): "
7426 "(%u:%u): "
7427 "%s",
7428 tag,
7429 name_size,
7430 name,
7431 (int)GRN_TEXT_LEN(&term),
7432 GRN_TEXT_VALUE(&term),
7433 tid,
7434 u2.rid,
7435 u2.sid,
7436 errbuf);
7437 GRN_OBJ_FIN(ctx, &term);
7438 }
7439 goto exit;
7440 }
7441 br = (buffer_rec *)(((byte *)br) + size2);
7442 GRN_FREE(bs2);
7443 }
7444 }
7445 }
7446 break;
7447 }
7448 if (!br) {
7449 if (u->tf == 1 && u->weight == 0) {
7450 if ((ii->header.common->flags & GRN_OBJ_WITH_SECTION)) {
7451 if (u->rid < 0x100000 && u->sid < 0x800) {
7452 a[0] = (u->rid << 12) + (u->sid << 1) + 1;
7453 a[1] = u->pos->pos;
7454 goto exit;
7455 }
7456 } else {
7457 a[0] = (u->rid << 1) + 1;
7458 a[1] = u->pos->pos;
7459 goto exit;
7460 }
7461 }
7462 pseg = buffer_new(ctx, ii, size, &pos, &bt, &br, &b, tid, h);
7463 if (pseg == GRN_II_PSEG_NOT_ASSIGNED) {
7464 grn_obj term;
7465 GRN_DEFINE_NAME(ii);
7466 GRN_TEXT_INIT(&term, 0);
7467 grn_ii_get_term(ctx, ii, tid, &term);
7468 MERR("%s failed to create a buffer: "
7469 "<%.*s>: "
7470 "<%.*s>(%u): "
7471 "(%u:%u): "
7472 "size:<%u>",
7473 tag,
7474 name_size,
7475 name,
7476 (int)GRN_TEXT_LEN(&term),
7477 GRN_TEXT_VALUE(&term),
7478 tid,
7479 u->rid,
7480 u->sid,
7481 size);
7482 GRN_OBJ_FIN(ctx, &term);
7483 goto exit;
7484 }
7485 bt->tid = tid;
7486 bt->size_in_chunk = 0;
7487 bt->pos_in_chunk = 0;
7488 bt->size_in_buffer = 0;
7489 bt->pos_in_buffer = 0;
7490 }
7491 buffer_put(ctx, ii, b, bt, br, bs, u, size);
7492 buffer_close(ctx, ii, pseg);
7493 if (ctx->rc != GRN_SUCCESS) {
7494 goto exit;
7495 }
7496 if (!a[0] || POS_IS_EMBED(a[0])) {
7497 a[0] = pos;
7498 }
7499 exit:
7500 array_unref(ctx, ii, tid);
7501 if (bs) {
7502 GRN_FREE(bs);
7503 }
7504 if (u->tf != u->atf) {
7505 grn_obj *source_table = grn_ctx_at(ctx, DB_OBJ(ii)->range);
7506 GRN_DEFINE_NAME_CUSTOM(source_table, source_table_name);
7507 grn_obj_unref(ctx, source_table);
7508 GRN_DEFINE_NAME(ii);
7509 grn_obj term;
7510 GRN_TEXT_INIT(&term, 0);
7511 grn_ii_get_term(ctx, ii, tid, &term);
7512 GRN_LOG(ctx,
7513 GRN_LOG_WARNING,
7514 "%s too many postings: "
7515 "<%.*s>: "
7516 "<%.*s>(%u): "
7517 "record:<%.*s>(%u:%u), "
7518 "n-postings:<%d>, "
7519 "n-discarded-postings:<%d>",
7520 tag,
7521 name_size,
7522 name,
7523 (int)GRN_TEXT_LEN(&term),
7524 GRN_TEXT_VALUE(&term),
7525 tid,
7526 source_table_name_size,
7527 source_table_name,
7528 u->rid,
7529 u->sid,
7530 u->atf,
7531 u->atf - u->tf);
7532 GRN_OBJ_FIN(ctx, &term);
7533 }
7534 grn_ii_expire(ctx, ii);
7535 return ctx->rc;
7536 }
7537
7538 extern "C" grn_rc
7539 grn_ii_update_one(
7540 grn_ctx *ctx, grn_ii *ii, grn_id tid, grn_ii_updspec *u, grn_hash *h)
7541 {
7542 GRN_SLOW_LOG_PUSH(ctx, GRN_LOG_DEBUG);
7543 grn_rc rc = grn_ii_update_one_internal(ctx, ii, tid, u, h);
7544 GRN_SLOW_LOG_POP_BEGIN(ctx, GRN_LOG_DEBUG, elapsed_time)
7545 {
7546 GRN_DEFINE_NAME(ii);
7547 grn_obj *source_table = grn_ctx_at(ctx, DB_OBJ(ii)->range);
7548 GRN_DEFINE_NAME_CUSTOM(source_table, source_table_name);
7549 grn_obj_unref(ctx, source_table);
7550 grn_obj term;
7551 GRN_TEXT_INIT(&term, 0);
7552 grn_ii_get_term(ctx, ii, tid, &term);
7553 GRN_LOG(ctx,
7554 GRN_LOG_DEBUG,
7555 "[ii][update][one][slow][%f] "
7556 "<%.*s>: "
7557 "<%.*s>(%u): "
7558 "record:<%.*s>(%u:%u), "
7559 "n-postings:<%d>, "
7560 "n-discarded-postings:<%d>",
7561 elapsed_time,
7562 name_size,
7563 name,
7564 (int)GRN_TEXT_LEN(&term),
7565 GRN_TEXT_VALUE(&term),
7566 tid,
7567 source_table_name_size,
7568 source_table_name,
7569 u->rid,
7570 u->sid,
7571 u->atf,
7572 u->atf - u->tf);
7573 GRN_OBJ_FIN(ctx, &term);
7574 }
7575 GRN_SLOW_LOG_POP_END(ctx);
7576 return rc;
7577 }
7578
7579 static inline grn_rc
7580 grn_ii_delete_one_internal(
7581 grn_ctx *ctx, grn_ii *ii, grn_id tid, grn_ii_updspec *u, grn_hash *h)
7582 {
7583 const char *tag = "[ii][delete][one]";
7584 buffer *b;
7585 uint8_t *bs = NULL;
7586 buffer_rec *br;
7587 buffer_term *bt;
7588 uint32_t pseg, size, *a;
7589 if (!tid) {
7590 return ctx->rc;
7591 }
7592 if (!(a = array_at(ctx, ii, tid))) {
7593 return ctx->rc;
7594 }
7595 if (grn_ii_wal_touch(ctx, ii, tag) != GRN_SUCCESS) {
7596 return ctx->rc;
7597 }
7598 for (;;) {
7599 const uint32_t pos = a[0];
7600 if (pos == 0) {
7601 goto exit;
7602 }
7603 if (POS_IS_EMBED(pos)) {
7604 if ((ii->header.common->flags & GRN_OBJ_WITH_SECTION)) {
7605 const uint32_t rid = POS_RID_SID_EXTRACT_RID(pos);
7606 const uint32_t sid = POS_RID_SID_EXTRACT_SID(pos);
7607 if (u->rid == rid && (!u->sid || u->sid == sid)) {
7608 a[0] = 0;
7609 lexicon_delete(ctx, ii, tid, h);
7610 }
7611 } else {
7612 const uint32_t rid = POS_RID_EXTRACT(pos);
7613 if (u->rid == rid) {
7614 a[0] = 0;
7615 lexicon_delete(ctx, ii, tid, h);
7616 }
7617 }
7618 goto exit;
7619 }
7620 if (!(bs = encode_rec(ctx, ii, u, &size, 1))) {
7621 grn_obj term;
7622 GRN_DEFINE_NAME(ii);
7623 GRN_TEXT_INIT(&term, 0);
7624 grn_ii_get_term(ctx, ii, tid, &term);
7625 MERR("%s failed to encode a record: "
7626 "<%.*s>: "
7627 "<%.*s>(%u): "
7628 "(%u:%u)",
7629 tag,
7630 name_size,
7631 name,
7632 (int)GRN_TEXT_LEN(&term),
7633 GRN_TEXT_VALUE(&term),
7634 tid,
7635 u->rid,
7636 u->sid);
7637 GRN_OBJ_FIN(ctx, &term);
7638 goto exit;
7639 }
7640 if ((pseg = buffer_open(ctx, ii, pos, &bt, &b)) ==
7641 GRN_II_PSEG_NOT_ASSIGNED) {
7642 grn_obj term;
7643 GRN_DEFINE_NAME(ii);
7644 GRN_TEXT_INIT(&term, 0);
7645 grn_ii_get_term(ctx, ii, tid, &term);
7646 MERR("%s failed to allocate a buffer: "
7647 "<%.*s>: "
7648 "<%.*s>(%u): "
7649 "(%u:%u): "
7650 "position:<%u>",
7651 tag,
7652 name_size,
7653 name,
7654 (int)GRN_TEXT_LEN(&term),
7655 GRN_TEXT_VALUE(&term),
7656 tid,
7657 u->rid,
7658 u->sid,
7659 pos);
7660 GRN_OBJ_FIN(ctx, &term);
7661 goto exit;
7662 }
7663 if (b->header.buffer_free < size) {
7664 const uint32_t pos_keep = pos;
7665 GRN_LOG(ctx,
7666 GRN_LOG_DEBUG,
7667 "flushing! b=%p free=%d, seg(%d)",
7668 b,
7669 b->header.buffer_free,
7670 grn_ii_pos_lseg(ii, pos));
7671 buffer_close(ctx, ii, pseg);
7672 buffer_flush(ctx, ii, grn_ii_pos_lseg(ii, pos), h);
7673 if (ctx->rc != GRN_SUCCESS) {
7674 grn_obj term;
7675 char errbuf[GRN_CTX_MSGSIZE];
7676 GRN_DEFINE_NAME(ii);
7677 GRN_TEXT_INIT(&term, 0);
7678 grn_ii_get_term(ctx, ii, tid, &term);
7679 grn_strcpy(errbuf, GRN_CTX_MSGSIZE, ctx->errbuf);
7680 ERR(ctx->rc,
7681 "%s failed to flush a buffer: "
7682 "<%.*s>: "
7683 "<%.*s>(%u): "
7684 "(%u:%u): "
7685 "position:<%u>: "
7686 "%s",
7687 tag,
7688 name_size,
7689 name,
7690 (int)GRN_TEXT_LEN(&term),
7691 GRN_TEXT_VALUE(&term),
7692 tid,
7693 u->rid,
7694 u->sid,
7695 pos,
7696 errbuf);
7697 GRN_OBJ_FIN(ctx, &term);
7698 goto exit;
7699 }
7700 if (a[0] != pos_keep) {
7701 GRN_LOG(ctx,
7702 GRN_LOG_DEBUG,
7703 "grn_ii_delete_one: a[0] changed %d->%d)",
7704 a[0],
7705 pos_keep);
7706 continue;
7707 }
7708 if ((pseg = buffer_open(ctx, ii, a[0], &bt, &b)) ==
7709 GRN_II_PSEG_NOT_ASSIGNED) {
7710 grn_obj term;
7711 GRN_DEFINE_NAME(ii);
7712 GRN_TEXT_INIT(&term, 0);
7713 grn_ii_get_term(ctx, ii, tid, &term);
7714 MERR("%s failed to reallocate a buffer: "
7715 "<%.*s>: "
7716 "<%.*s>(%u): "
7717 "(%u:%u): "
7718 "position:<%u>",
7719 tag,
7720 name_size,
7721 name,
7722 (int)GRN_TEXT_LEN(&term),
7723 GRN_TEXT_VALUE(&term),
7724 tid,
7725 u->rid,
7726 u->sid,
7727 a[0]);
7728 GRN_OBJ_FIN(ctx, &term);
7729 goto exit;
7730 }
7731 GRN_LOG(ctx,
7732 GRN_LOG_DEBUG,
7733 "flushed! b=%p free=%d, seg(%d)",
7734 b,
7735 b->header.buffer_free,
7736 grn_ii_pos_lseg(ii, a[0]));
7737 if (b->header.buffer_free < size) {
7738 grn_obj term;
7739 GRN_DEFINE_NAME(ii);
7740 GRN_TEXT_INIT(&term, 0);
7741 grn_ii_get_term(ctx, ii, tid, &term);
7742 MERR("%s buffer is full: "
7743 "<%.*s>: "
7744 "<%.*s>(%u): "
7745 "(%u:%u): "
7746 "segment:<%u>, free:<%u>, required:<%u>",
7747 tag,
7748 name_size,
7749 name,
7750 (int)GRN_TEXT_LEN(&term),
7751 GRN_TEXT_VALUE(&term),
7752 tid,
7753 u->rid,
7754 u->sid,
7755 a[0],
7756 b->header.buffer_free,
7757 size);
7758 GRN_OBJ_FIN(ctx, &term);
7759 buffer_close(ctx, ii, pseg);
7760 goto exit;
7761 }
7762 }
7763
7764 b->header.buffer_free -= size;
7765 br = (buffer_rec *)(((byte *)&b->terms[b->header.nterms]) +
7766 b->header.buffer_free);
7767 buffer_put(ctx, ii, b, bt, br, bs, u, size);
7768 buffer_close(ctx, ii, pseg);
7769 break;
7770 }
7771 exit:
7772 array_unref(ctx, ii, tid);
7773 if (bs) {
7774 GRN_FREE(bs);
7775 }
7776 return ctx->rc;
7777 }
7778
7779 extern "C" grn_rc
7780 grn_ii_delete_one(
7781 grn_ctx *ctx, grn_ii *ii, grn_id tid, grn_ii_updspec *u, grn_hash *h)
7782 {
7783 GRN_SLOW_LOG_PUSH(ctx, GRN_LOG_DEBUG);
7784 grn_rc rc = grn_ii_delete_one_internal(ctx, ii, tid, u, h);
7785 GRN_SLOW_LOG_POP_BEGIN(ctx, GRN_LOG_DEBUG, elapsed_time)
7786 {
7787 GRN_DEFINE_NAME(ii);
7788 grn_obj *source_table = grn_ctx_at(ctx, DB_OBJ(ii)->range);
7789 GRN_DEFINE_NAME_CUSTOM(source_table, source_table_name);
7790 grn_obj_unref(ctx, source_table);
7791 grn_obj term;
7792 GRN_TEXT_INIT(&term, 0);
7793 grn_ii_get_term(ctx, ii, tid, &term);
7794 GRN_LOG(ctx,
7795 GRN_LOG_DEBUG,
7796 "[ii][delete][one][slow][%f] "
7797 "<%.*s>: "
7798 "<%.*s>(%u): "
7799 "record:<%.*s>(%u:%u)",
7800 elapsed_time,
7801 name_size,
7802 name,
7803 (int)GRN_TEXT_LEN(&term),
7804 GRN_TEXT_VALUE(&term),
7805 tid,
7806 source_table_name_size,
7807 source_table_name,
7808 u->rid,
7809 u->sid);
7810 GRN_OBJ_FIN(ctx, &term);
7811 }
7812 GRN_SLOW_LOG_POP_END(ctx);
7813 return rc;
7814 }
7815
7816 #define CHUNK_USED 1
7817 #define BUFFER_USED 2
7818 #define SOLE_DOC_USED 4
7819 #define SOLE_POS_USED 8
7820
7821 struct _grn_ii_cursor {
7822 grn_db_obj obj;
7823 grn_ctx *ctx;
7824 grn_ii *ii;
7825 grn_id id;
7826 grn_posting *post;
7827
7828 grn_id min; /* Minimum record ID */
7829 grn_id max;
7830 grn_posting_internal pc;
7831 grn_posting_internal pb;
7832
7833 uint32_t cdf; /* Document frequency */
7834 uint32_t *cdp;
7835 uint32_t *crp; /* Record ID */
7836 uint32_t *csp; /* Section ID */
7837 uint32_t *ctp; /* Term frequency */
7838 uint32_t *cwp; /* Weight */
7839 uint32_t *cpp; /* Position */
7840
7841 uint8_t *bp;
7842
7843 uint32_t nelements;
7844 uint32_t nchunks;
7845 uint32_t curr_chunk;
7846 chunk_info *cinfo;
7847 grn_io_win iw;
7848 uint8_t *cp;
7849 uint8_t *cpe;
7850 datavec rdv[MAX_N_ELEMENTS + 1];
7851
7852 buffer *buf;
7853 uint16_t stat;
7854 uint16_t nextb;
7855 uint32_t buffer_pseg;
7856 int flags;
7857 uint32_t *ppseg;
7858
7859 int weight;
7860
7861 uint32_t prev_chunk_rid;
7862
7863 float scale;
7864 float *scales;
7865 size_t n_scales;
7866 };
7867
7868 static bool
7869 buffer_is_reused(grn_ctx *ctx, grn_ii *ii, grn_ii_cursor *c)
7870 {
7871 if (*c->ppseg != c->buffer_pseg) {
7872 uint32_t i;
7873 for (i = ii->header.common->bgqtail; i != ii->header.common->bgqhead;
7874 i = (i + 1) & (GRN_II_BGQSIZE - 1)) {
7875 if (ii->header.common->bgqbody[i] == c->buffer_pseg) {
7876 return false;
7877 }
7878 }
7879 return true;
7880 }
7881 return false;
7882 }
7883
7884 static int
7885 chunk_is_reused(
7886 grn_ctx *ctx, grn_ii *ii, grn_ii_cursor *c, uint32_t offset, uint32_t size)
7887 {
7888 if (*c->ppseg != c->buffer_pseg) {
7889 uint32_t i, gseg;
7890 if (size > S_CHUNK) {
7891 return 1;
7892 }
7893 grn_bit_scan_rev_result m;
7894 if (size > (1 << GRN_II_W_LEAST_CHUNK)) {
7895 int es = size - 1;
7896 GRN_BIT_SCAN_REV(es, m);
7897 m++;
7898 } else {
7899 m = GRN_II_W_LEAST_CHUNK;
7900 }
7901 gseg = ii->header.common->garbages[m - GRN_II_W_LEAST_CHUNK];
7902 while (gseg != GRN_II_PSEG_NOT_ASSIGNED) {
7903 grn_io_win iw;
7904 auto ginfo = static_cast<grn_ii_ginfo *>(
7905 WIN_MAP(ctx, ii->chunk, &iw, gseg, 0, S_GARBAGE, GRN_IO_RDWR));
7906 if (!ginfo) {
7907 break;
7908 }
7909 for (i = 0; i < ginfo->nrecs; i++) {
7910 if (ginfo->recs[i] == offset) {
7911 grn_io_win_unmap(ctx, &iw);
7912 return 0;
7913 }
7914 }
7915 gseg = ginfo->next;
7916 grn_io_win_unmap(ctx, &iw);
7917 }
7918 return 1;
7919 }
7920 return 0;
7921 }
7922
7923 #define GRN_II_CURSOR_CMP(c1, c2) \
7924 (((c1)->post->rid > (c2)->post->rid) || \
7925 (((c1)->post->rid == (c2)->post->rid) && \
7926 (((c1)->post->sid > (c2)->post->sid) || \
7927 (((c1)->post->sid == (c2)->post->sid) && \
7928 ((c1)->post->pos > (c2)->post->pos)))))
7929
7930 extern "C" grn_ii_cursor *
7931 grn_ii_cursor_open(grn_ctx *ctx,
7932 grn_ii *ii,
7933 grn_id tid,
7934 grn_id min,
7935 grn_id max,
7936 int nelements,
7937 int flags)
7938 {
7939 grn_ii_cursor *c = NULL;
7940 uint32_t pos, *a;
7941 if (!(a = array_at(ctx, ii, tid))) {
7942 return NULL;
7943 }
7944 for (;;) {
7945 c = NULL;
7946 if (!(pos = a[0])) {
7947 goto exit;
7948 }
7949 c = static_cast<grn_ii_cursor *>(GRN_CALLOC(sizeof(grn_ii_cursor)));
7950 if (!c) {
7951 goto exit;
7952 }
7953 c->ctx = ctx;
7954 c->ii = ii;
7955 c->id = tid;
7956 c->min = min;
7957 c->max = max;
7958 c->nelements = nelements;
7959 c->flags = flags;
7960 c->weight = 0;
7961 c->scale = 1.0;
7962 c->scales = NULL;
7963 c->n_scales = 0;
7964 datavec_init(ctx, ii, c->rdv, 0, 0);
7965 if (POS_IS_EMBED(pos)) {
7966 c->stat = 0;
7967 if ((ii->header.common->flags & GRN_OBJ_WITH_SECTION)) {
7968 c->pb.rid = POS_RID_SID_EXTRACT_RID(pos);
7969 c->pb.sid = POS_RID_SID_EXTRACT_SID(pos);
7970 } else {
7971 c->pb.rid = POS_RID_EXTRACT(pos);
7972 c->pb.sid = 1;
7973 }
7974 c->pb.tf = 1;
7975 c->pb.weight = 0;
7976 c->pb.weight_float = (float)(c->pb.weight);
7977 c->pb.pos = a[1];
7978 c->pb.scale = c->scale;
7979 } else {
7980 uint32_t chunk;
7981 buffer_term *bt;
7982 c->buffer_pseg = buffer_open(ctx, ii, pos, &bt, &c->buf);
7983 if (c->buffer_pseg == GRN_II_PSEG_NOT_ASSIGNED) {
7984 GRN_FREE(c);
7985 c = NULL;
7986 goto exit;
7987 }
7988 const uint32_t lseg = grn_ii_pos_lseg(ii, pos);
7989 c->ppseg = grn_ii_get_buffer_pseg_address_inline(ii, lseg);
7990 if (bt->size_in_chunk &&
7991 (chunk = c->buf->header.chunk) != GRN_II_PSEG_NOT_ASSIGNED) {
7992 if (!(c->cp = static_cast<uint8_t *>(WIN_MAP(ctx,
7993 ii->chunk,
7994 &c->iw,
7995 chunk,
7996 bt->pos_in_chunk,
7997 bt->size_in_chunk,
7998 GRN_IO_RDONLY)))) {
7999 buffer_close(ctx, ii, c->buffer_pseg);
8000 GRN_FREE(c);
8001 c = NULL;
8002 goto exit;
8003 }
8004 if (buffer_is_reused(ctx, ii, c)) {
8005 grn_ii_cursor_close(ctx, c);
8006 continue;
8007 }
8008 c->cpe = c->cp + bt->size_in_chunk;
8009 if ((bt->tid & CHUNK_SPLIT)) {
8010 uint32_t i;
8011 grn_id crid;
8012 GRN_B_DEC(c->nchunks, c->cp);
8013 if (chunk_is_reused(ctx, ii, c, chunk, c->buf->header.chunk_size)) {
8014 grn_ii_cursor_close(ctx, c);
8015 continue;
8016 }
8017 if (!(c->cinfo = GRN_MALLOCN(chunk_info, c->nchunks))) {
8018 buffer_close(ctx, ii, c->buffer_pseg);
8019 grn_io_win_unmap(ctx, &c->iw);
8020 GRN_FREE(c);
8021 c = NULL;
8022 goto exit;
8023 }
8024 for (i = 0, crid = GRN_ID_NIL; i < c->nchunks; i++) {
8025 GRN_B_DEC(c->cinfo[i].segno, c->cp);
8026 GRN_B_DEC(c->cinfo[i].size, c->cp);
8027 GRN_B_DEC(c->cinfo[i].dgap, c->cp);
8028 crid += c->cinfo[i].dgap;
8029 if (crid < min) {
8030 c->pc.rid = crid;
8031 c->curr_chunk = i + 1;
8032 }
8033 }
8034 if (chunk_is_reused(ctx, ii, c, chunk, c->buf->header.chunk_size)) {
8035 grn_ii_cursor_close(ctx, c);
8036 continue;
8037 }
8038 }
8039 }
8040 c->nextb = bt->pos_in_buffer;
8041 c->stat = CHUNK_USED | BUFFER_USED;
8042 }
8043 if (pos == a[0]) {
8044 break;
8045 }
8046 grn_ii_cursor_close(ctx, c);
8047 }
8048 exit:
8049 array_unref(ctx, ii, tid);
8050 return c;
8051 }
8052
8053 extern "C" grn_ii *
8054 grn_ii_cursor_get_ii(grn_ctx *ctx, grn_ii_cursor *cursor)
8055 {
8056 return cursor->ii;
8057 }
8058
8059 static inline float
8060 grn_ii_cursor_resolve_scale(grn_ctx *ctx,
8061 grn_ii_cursor *cursor,
8062 uint32_t section_id)
8063 {
8064 if (cursor->n_scales > 0) {
8065 if (section_id <= cursor->n_scales) {
8066 return cursor->scales[section_id - 1];
8067 } else {
8068 return 0.0;
8069 }
8070 } else {
8071 return cursor->scale;
8072 }
8073 }
8074
8075 extern "C" grn_rc
8076 grn_ii_cursor_set_scale(grn_ctx *ctx, grn_ii_cursor *cursor, float scale)
8077 {
8078 cursor->scale = scale;
8079 cursor->scales = NULL;
8080 cursor->n_scales = 0;
8081 if (!cursor->buf) {
8082 cursor->pb.scale = grn_ii_cursor_resolve_scale(ctx, cursor, cursor->pb.sid);
8083 }
8084 return ctx->rc;
8085 }
8086
8087 extern "C" grn_rc
8088 grn_ii_cursor_set_scales(grn_ctx *ctx,
8089 grn_ii_cursor *cursor,
8090 float *scales,
8091 size_t n_scales)
8092 {
8093 cursor->scale = 0.0;
8094 cursor->scales = scales;
8095 cursor->n_scales = n_scales;
8096 if (!cursor->buf) {
8097 cursor->pb.scale = grn_ii_cursor_resolve_scale(ctx, cursor, cursor->pb.sid);
8098 }
8099 return ctx->rc;
8100 }
8101
8102 static inline void
8103 grn_ii_cursor_set_min(grn_ctx *ctx, grn_ii_cursor *c, grn_id min)
8104 {
8105 if (c->min >= min) {
8106 return;
8107 }
8108
8109 if (grn_ii_cursor_set_min_enable) {
8110 grn_id old_min = c->min;
8111 c->min = min;
8112 if (c->buf && c->pc.rid != GRN_ID_NIL && c->pc.rid < c->min &&
8113 c->prev_chunk_rid < c->min && c->curr_chunk < c->nchunks) {
8114 uint32_t i;
8115 uint32_t skip_chunk = 0;
8116 grn_id rid = c->prev_chunk_rid;
8117
8118 if (c->curr_chunk > 0) {
8119 i = c->curr_chunk - 1;
8120 } else {
8121 i = 0;
8122 }
8123 for (; i < c->nchunks; i++) {
8124 rid += c->cinfo[i].dgap;
8125 if (rid < c->min) {
8126 skip_chunk = i + 1;
8127 } else {
8128 rid -= c->cinfo[i].dgap;
8129 break;
8130 }
8131 }
8132 if (skip_chunk > c->curr_chunk) {
8133 grn_id old_rid = c->pc.rid;
8134 grn_id old_prev_chunk_rid = c->prev_chunk_rid;
8135 uint32_t old_chunk = c->curr_chunk;
8136 bool old_chunk_used = (c->stat & CHUNK_USED);
8137 c->pc.rid = rid;
8138 c->pc.rest = 0;
8139 c->prev_chunk_rid = rid - c->cinfo[skip_chunk - 1].dgap;
8140 c->curr_chunk = skip_chunk;
8141 c->crp = c->cdp + c->cdf;
8142 c->stat |= CHUNK_USED;
8143 if (grn_logger_pass(ctx, GRN_LOG_DEBUG)) {
8144 GRN_DEFINE_NAME(c->ii);
8145 grn_obj term;
8146 GRN_TEXT_INIT(&term, 0);
8147 grn_ii_get_term(ctx, c->ii, c->id, &term);
8148 GRN_LOG(ctx,
8149 GRN_LOG_DEBUG,
8150 "[ii][cursor][min][%.*s][%.*s][%u] skip: "
8151 "<%p>: "
8152 "rid(%u->%u): "
8153 "prev-chunk-rid(%u->%u): "
8154 "min(%u->%u): "
8155 "chunk(%u->%u): "
8156 "chunk-used(%s->%s)",
8157 name_size,
8158 name,
8159 (int)GRN_TEXT_LEN(&term),
8160 GRN_TEXT_VALUE(&term),
8161 c->id,
8162 c,
8163 old_rid,
8164 rid,
8165 old_prev_chunk_rid,
8166 c->prev_chunk_rid,
8167 old_min,
8168 min,
8169 old_chunk,
8170 c->curr_chunk,
8171 old_chunk_used ? "true" : "false",
8172 (c->stat & CHUNK_USED) ? "true" : "false");
8173 GRN_OBJ_FIN(ctx, &term);
8174 }
8175 }
8176 }
8177 }
8178 }
8179
8180 typedef struct {
8181 bool include_garbage;
8182 } grn_ii_cursor_next_options;
8183
8184 static inline grn_posting *
8185 grn_ii_cursor_next_internal(grn_ctx *ctx,
8186 grn_ii_cursor *c,
8187 grn_ii_cursor_next_options *options)
8188 {
8189 const bool include_garbage = options->include_garbage;
8190 if (c->buf) {
8191 for (;;) {
8192 if (c->stat & CHUNK_USED) {
8193 for (;;) {
8194 if (c->crp < c->cdp + c->cdf) {
8195 uint32_t dgap = *c->crp++;
8196 c->pc.rid += dgap;
8197 if (dgap) {
8198 c->pc.sid = 0;
8199 }
8200 if ((c->ii->header.common->flags & GRN_OBJ_WITH_SECTION)) {
8201 c->pc.sid += 1 + *c->csp++;
8202 } else {
8203 c->pc.sid = 1;
8204 }
8205 c->cpp += c->pc.rest;
8206 c->pc.rest = c->pc.tf = 1 + *c->ctp++;
8207 if ((c->ii->header.common->flags & GRN_OBJ_WITH_WEIGHT)) {
8208 c->pc.weight = *c->cwp++;
8209 } else {
8210 c->pc.weight = 0;
8211 }
8212 c->pc.weight_float = (float)(c->pc.weight);
8213 c->pc.pos = 0;
8214 c->pc.scale = grn_ii_cursor_resolve_scale(ctx, c, c->pc.sid);
8215 /*
8216 {
8217 static int count = 0;
8218 int tf = c->pc.tf, pos = 0, *pp = (int *)c->cpp;
8219 grn_obj buf;
8220 GRN_TEXT_INIT(&buf, 0);
8221 grn_text_itoa(ctx, &buf, c->pc.rid);
8222 GRN_TEXT_PUTC(ctx, &buf, ':');
8223 grn_text_itoa(ctx, &buf, c->pc.sid);
8224 GRN_TEXT_PUTC(ctx, &buf, ':');
8225 grn_text_itoa(ctx, &buf, c->pc.tf);
8226 GRN_TEXT_PUTC(ctx, &buf, '(');
8227 while (tf--) {
8228 pos += *pp++;
8229 count++;
8230 grn_text_itoa(ctx, &buf, pos);
8231 if (tf) { GRN_TEXT_PUTC(ctx, &buf, ':'); }
8232 }
8233 GRN_TEXT_PUTC(ctx, &buf, ')');
8234 GRN_TEXT_PUTC(ctx, &buf, '\0');
8235 GRN_LOG(ctx, GRN_LOG_DEBUG, "posting(%d):%s", count,
8236 GRN_TEXT_VALUE(&buf)); GRN_OBJ_FIN(ctx, &buf);
8237 }
8238 */
8239 if (c->pc.rid < c->min || c->pc.scale <= 0.0) {
8240 continue;
8241 }
8242 } else {
8243 if (c->curr_chunk <= c->nchunks) {
8244 if (c->curr_chunk == c->nchunks) {
8245 if (c->cp < c->cpe) {
8246 int decoded_size;
8247 decoded_size =
8248 grn_decv(ctx, c->ii, c->id, c->cp, c->cpe - c->cp, c->rdv);
8249 if (decoded_size == 0) {
8250 GRN_DEFINE_NAME(c->ii);
8251 grn_obj term;
8252 GRN_TEXT_INIT(&term, 0);
8253 grn_ii_get_term(ctx, c->ii, c->id, &term);
8254 GRN_LOG(ctx,
8255 GRN_LOG_WARNING,
8256 "[ii][cursor][next][chunk][last][%.*s][%.*s][%u] "
8257 "failed to decode the last chunk. "
8258 "Another thread might change "
8259 "the chunk while decoding: "
8260 "<%p>: <%d>: <%" GRN_FMT_INT64D ">",
8261 name_size,
8262 name,
8263 (int)GRN_TEXT_LEN(&term),
8264 GRN_TEXT_VALUE(&term),
8265 c->id,
8266 c,
8267 c->curr_chunk,
8268 c->cinfo ? (int64_t)(c->cinfo[c->curr_chunk].segno)
8269 : -1);
8270 GRN_OBJ_FIN(ctx, &term);
8271 c->pc.rid = GRN_ID_NIL;
8272 break;
8273 }
8274 if (buffer_is_reused(ctx, c->ii, c)) {
8275 GRN_DEFINE_NAME(c->ii);
8276 grn_obj term;
8277 GRN_TEXT_INIT(&term, 0);
8278 grn_ii_get_term(ctx, c->ii, c->id, &term);
8279 GRN_LOG(ctx,
8280 GRN_LOG_WARNING,
8281 "[ii][cursor][next][chunk][last][%.*s][%.*s][%u] "
8282 "buffer is reused by another thread: <%p>",
8283 name_size,
8284 name,
8285 (int)GRN_TEXT_LEN(&term),
8286 GRN_TEXT_VALUE(&term),
8287 c->id,
8288 c);
8289 GRN_OBJ_FIN(ctx, &term);
8290 c->pc.rid = GRN_ID_NIL;
8291 break;
8292 }
8293 if (chunk_is_reused(ctx,
8294 c->ii,
8295 c,
8296 c->buf->header.chunk,
8297 c->buf->header.chunk_size)) {
8298 GRN_DEFINE_NAME(c->ii);
8299 grn_obj term;
8300 GRN_TEXT_INIT(&term, 0);
8301 grn_ii_get_term(ctx, c->ii, c->id, &term);
8302 GRN_LOG(ctx,
8303 GRN_LOG_WARNING,
8304 "[ii][cursor][next][chunk][last][%.*s][%.*s][%u] "
8305 "chunk is reused by another thread: "
8306 "<%p>: <%d>",
8307 name_size,
8308 name,
8309 (int)GRN_TEXT_LEN(&term),
8310 GRN_TEXT_VALUE(&term),
8311 c->id,
8312 c,
8313 c->buf->header.chunk);
8314 GRN_OBJ_FIN(ctx, &term);
8315 c->pc.rid = GRN_ID_NIL;
8316 break;
8317 }
8318 } else {
8319 c->pc.rid = GRN_ID_NIL;
8320 break;
8321 }
8322 } else {
8323 uint8_t *cp;
8324 grn_io_win iw;
8325 uint32_t size = c->cinfo[c->curr_chunk].size;
8326 if (size && (cp = static_cast<uint8_t *>(
8327 WIN_MAP(ctx,
8328 c->ii->chunk,
8329 &iw,
8330 c->cinfo[c->curr_chunk].segno,
8331 0,
8332 size,
8333 GRN_IO_RDONLY)))) {
8334 int decoded_size;
8335 decoded_size = grn_decv(ctx, c->ii, c->id, cp, size, c->rdv);
8336 grn_io_win_unmap(ctx, &iw);
8337 if (decoded_size == 0) {
8338 GRN_DEFINE_NAME(c->ii);
8339 grn_obj term;
8340 GRN_TEXT_INIT(&term, 0);
8341 grn_ii_get_term(ctx, c->ii, c->id, &term);
8342 GRN_LOG(ctx,
8343 GRN_LOG_WARNING,
8344 "[ii][cursor][next][chunk][%.*s][%.*s][%u] "
8345 "failed to decode the next chunk. "
8346 "Another thread might change "
8347 "the chunk while decoding: "
8348 "<%p>: <%d>: <%" GRN_FMT_INT64D ">",
8349 name_size,
8350 name,
8351 (int)GRN_TEXT_LEN(&term),
8352 GRN_TEXT_VALUE(&term),
8353 c->id,
8354 c,
8355 c->curr_chunk,
8356 c->cinfo ? (int64_t)(c->cinfo[c->curr_chunk].segno)
8357 : -1);
8358 GRN_OBJ_FIN(ctx, &term);
8359 c->pc.rid = GRN_ID_NIL;
8360 break;
8361 }
8362 if (buffer_is_reused(ctx, c->ii, c)) {
8363 GRN_DEFINE_NAME(c->ii);
8364 grn_obj term;
8365 GRN_TEXT_INIT(&term, 0);
8366 grn_ii_get_term(ctx, c->ii, c->id, &term);
8367 GRN_LOG(ctx,
8368 GRN_LOG_WARNING,
8369 "[ii][cursor][next][chunk][%.*s][%.*s][%u] "
8370 "buffer is reused by another thread: <%p>",
8371 name_size,
8372 name,
8373 (int)GRN_TEXT_LEN(&term),
8374 GRN_TEXT_VALUE(&term),
8375 c->id,
8376 c);
8377 GRN_OBJ_FIN(ctx, &term);
8378 c->pc.rid = GRN_ID_NIL;
8379 break;
8380 }
8381 if (chunk_is_reused(ctx,
8382 c->ii,
8383 c,
8384 c->cinfo[c->curr_chunk].segno,
8385 size)) {
8386 GRN_DEFINE_NAME(c->ii);
8387 grn_obj term;
8388 GRN_TEXT_INIT(&term, 0);
8389 grn_ii_get_term(ctx, c->ii, c->id, &term);
8390 GRN_LOG(ctx,
8391 GRN_LOG_WARNING,
8392 "[ii][cursor][next][chunk][%.*s][%.*s][%u] "
8393 "chunk is reused by another thread: "
8394 "<%p>: <%d>",
8395 name_size,
8396 name,
8397 (int)GRN_TEXT_LEN(&term),
8398 GRN_TEXT_VALUE(&term),
8399 c->id,
8400 c,
8401 c->cinfo[c->curr_chunk].segno);
8402 GRN_OBJ_FIN(ctx, &term);
8403 c->pc.rid = GRN_ID_NIL;
8404 break;
8405 }
8406 } else {
8407 c->pc.rid = GRN_ID_NIL;
8408 break;
8409 }
8410 }
8411 {
8412 int j = 0;
8413 c->cdf = c->rdv[j].data_size;
8414 c->crp = c->cdp = c->rdv[j++].data;
8415 if ((c->ii->header.common->flags & GRN_OBJ_WITH_SECTION)) {
8416 c->csp = c->rdv[j++].data;
8417 }
8418 c->ctp = c->rdv[j++].data;
8419 if ((c->ii->header.common->flags & GRN_OBJ_WITH_WEIGHT)) {
8420 c->cwp = c->rdv[j++].data;
8421 }
8422 if ((c->ii->header.common->flags & GRN_OBJ_WITH_POSITION)) {
8423 c->cpp = c->rdv[j].data;
8424 }
8425 }
8426 c->prev_chunk_rid = c->pc.rid;
8427 c->pc.rid = GRN_ID_NIL;
8428 c->pc.sid = 0;
8429 c->pc.rest = 0;
8430 c->curr_chunk++;
8431 continue;
8432 } else {
8433 c->pc.rid = GRN_ID_NIL;
8434 }
8435 }
8436 break;
8437 }
8438 }
8439 if (c->stat & BUFFER_USED) {
8440 for (;;) {
8441 if (c->nextb) {
8442 uint32_t lrid = c->pb.rid, lsid = c->pb.sid; /* for check */
8443 buffer_rec *br = BUFFER_REC_AT(c->buf, c->nextb);
8444 if (buffer_is_reused(ctx, c->ii, c)) {
8445 GRN_DEFINE_NAME(c->ii);
8446 grn_obj term;
8447 GRN_TEXT_INIT(&term, 0);
8448 grn_ii_get_term(ctx, c->ii, c->id, &term);
8449 GRN_LOG(ctx,
8450 GRN_LOG_WARNING,
8451 "[ii][cursor][next][buffer][%.*s][%.*s][%u] "
8452 "buffer is reused by another thread: "
8453 "<%p>: <%d>: <%d>",
8454 name_size,
8455 name,
8456 (int)GRN_TEXT_LEN(&term),
8457 GRN_TEXT_VALUE(&term),
8458 c->id,
8459 c,
8460 c->buffer_pseg,
8461 *c->ppseg);
8462 GRN_OBJ_FIN(ctx, &term);
8463 c->pb.rid = GRN_ID_NIL;
8464 break;
8465 }
8466 c->bp = GRN_NEXT_ADDR(br);
8467 GRN_B_DEC(c->pb.rid, c->bp);
8468 if ((c->ii->header.common->flags & GRN_OBJ_WITH_SECTION)) {
8469 GRN_B_DEC(c->pb.sid, c->bp);
8470 } else {
8471 c->pb.sid = 1;
8472 }
8473 if (lrid > c->pb.rid || (lrid == c->pb.rid && lsid >= c->pb.sid)) {
8474 GRN_DEFINE_NAME(c->ii);
8475 grn_obj term;
8476 GRN_TEXT_INIT(&term, 0);
8477 grn_ii_get_term(ctx, c->ii, c->id, &term);
8478 ERR(GRN_FILE_CORRUPT,
8479 "[ii][broken][cursor][next][buffer][%.*s][%.*s][%u] "
8480 "posting in list in buffer isn't sorted: "
8481 "(%d:%d) -> (%d:%d) (%d->%d)",
8482 name_size,
8483 name,
8484 (int)GRN_TEXT_LEN(&term),
8485 GRN_TEXT_VALUE(&term),
8486 c->id,
8487 lrid,
8488 lsid,
8489 c->pb.rid,
8490 c->pb.sid,
8491 c->buffer_pseg,
8492 *c->ppseg);
8493 GRN_OBJ_FIN(ctx, &term);
8494 c->pb.rid = GRN_ID_NIL;
8495 break;
8496 }
8497 c->pb.scale = grn_ii_cursor_resolve_scale(ctx, c, c->pb.sid);
8498 if (c->pb.rid < c->min || c->pb.scale <= 0.0) {
8499 c->pb.rid = 0;
8500 if (br->jump > 0 && !BUFFER_REC_DELETED(br)) {
8501 buffer_rec *jump_br = BUFFER_REC_AT(c->buf, br->jump);
8502 if (BUFFER_REC_DELETED(jump_br)) {
8503 c->nextb = br->step;
8504 } else {
8505 uint8_t *jump_bp;
8506 uint32_t jump_rid;
8507 jump_bp = GRN_NEXT_ADDR(jump_br);
8508 GRN_B_DEC(jump_rid, jump_bp);
8509 if (jump_rid < c->min) {
8510 c->nextb = br->jump;
8511 } else {
8512 c->nextb = br->step;
8513 }
8514 }
8515 } else {
8516 c->nextb = br->step;
8517 }
8518 continue;
8519 }
8520 c->nextb = br->step;
8521 GRN_B_DEC(c->pb.tf, c->bp);
8522 if ((c->ii->header.common->flags & GRN_OBJ_WITH_WEIGHT)) {
8523 GRN_B_DEC(c->pb.weight, c->bp);
8524 } else {
8525 c->pb.weight = 0;
8526 }
8527 c->pb.weight_float = (float)(c->pb.weight);
8528 c->pb.rest = c->pb.tf;
8529 c->pb.pos = 0;
8530 } else {
8531 c->pb.rid = 0;
8532 }
8533 break;
8534 }
8535 }
8536 if (c->pb.rid) {
8537 if (c->pc.rid) {
8538 if (c->pc.rid < c->pb.rid) {
8539 c->stat = CHUNK_USED;
8540 if (include_garbage || (c->pc.tf && c->pc.sid)) {
8541 c->post = (grn_posting *)(&c->pc);
8542 break;
8543 }
8544 } else {
8545 if (c->pb.rid < c->pc.rid) {
8546 c->stat = BUFFER_USED;
8547 if (include_garbage || (c->pb.tf && c->pb.sid)) {
8548 c->post = (grn_posting *)(&c->pb);
8549 break;
8550 }
8551 } else {
8552 if (c->pb.sid) {
8553 if (c->pc.sid < c->pb.sid) {
8554 c->stat = CHUNK_USED;
8555 if (include_garbage || (c->pc.tf && c->pc.sid)) {
8556 c->post = (grn_posting *)(&c->pc);
8557 break;
8558 }
8559 } else {
8560 c->stat = BUFFER_USED;
8561 if (c->pb.sid == c->pc.sid) {
8562 c->stat |= CHUNK_USED;
8563 }
8564 if (include_garbage || (c->pb.tf)) {
8565 c->post = (grn_posting *)(&c->pb);
8566 break;
8567 }
8568 }
8569 } else {
8570 c->stat = CHUNK_USED;
8571 }
8572 }
8573 }
8574 } else {
8575 c->stat = BUFFER_USED;
8576 if (include_garbage || (c->pb.tf && c->pb.sid)) {
8577 c->post = (grn_posting *)(&c->pb);
8578 break;
8579 }
8580 }
8581 } else {
8582 if (c->pc.rid) {
8583 c->stat = CHUNK_USED;
8584 if (include_garbage || (c->pc.tf && c->pc.sid)) {
8585 c->post = (grn_posting *)(&c->pc);
8586 break;
8587 }
8588 } else {
8589 c->post = NULL;
8590 return NULL;
8591 }
8592 }
8593 }
8594 } else {
8595 if (c->stat & SOLE_DOC_USED) {
8596 c->post = NULL;
8597 return NULL;
8598 } else {
8599 c->post = (grn_posting *)(&c->pb);
8600 c->stat |= SOLE_DOC_USED;
8601 if (c->post->rid < c->min) {
8602 c->post = NULL;
8603 return NULL;
8604 }
8605 if (c->pb.scale <= 0.0) {
8606 c->post = NULL;
8607 return NULL;
8608 }
8609 }
8610 }
8611 return c->post;
8612 }
8613
8614 extern "C" grn_posting *
8615 grn_ii_cursor_next(grn_ctx *ctx, grn_ii_cursor *c)
8616 {
8617 grn_ii_cursor_next_options options = {/* .include_garbage = */ false};
8618 return grn_ii_cursor_next_internal(ctx, c, &options);
8619 }
8620
8621 extern "C" grn_posting *
8622 grn_ii_cursor_next_pos(grn_ctx *ctx, grn_ii_cursor *c)
8623 {
8624 uint32_t gap;
8625 if ((c->ii->header.common->flags & GRN_OBJ_WITH_POSITION)) {
8626 if (c->nelements == c->ii->n_elements) {
8627 if (c->buf) {
8628 if (c->post == (grn_posting *)(&c->pc)) {
8629 if (c->pc.rest) {
8630 c->pc.rest--;
8631 c->pc.pos += *c->cpp++;
8632 } else {
8633 return NULL;
8634 }
8635 } else if (c->post == (grn_posting *)(&c->pb)) {
8636 if (buffer_is_reused(ctx, c->ii, c)) {
8637 GRN_DEFINE_NAME(c->ii);
8638 grn_obj term;
8639 GRN_TEXT_INIT(&term, 0);
8640 grn_ii_get_term(ctx, c->ii, c->id, &term);
8641 GRN_LOG(ctx,
8642 GRN_LOG_WARNING,
8643 "[ii][cursor][next][pos][buffer][%.*s][%.*s][%u] "
8644 "buffer(%d,%d) is reused by another thread: %p",
8645 name_size,
8646 name,
8647 (int)GRN_TEXT_LEN(&term),
8648 GRN_TEXT_VALUE(&term),
8649 c->id,
8650 c->buffer_pseg,
8651 *c->ppseg,
8652 c);
8653 GRN_OBJ_FIN(ctx, &term);
8654 return NULL;
8655 }
8656 if (c->pb.rest) {
8657 c->pb.rest--;
8658 GRN_B_DEC(gap, c->bp);
8659 c->pb.pos += gap;
8660 } else {
8661 return NULL;
8662 }
8663 } else {
8664 return NULL;
8665 }
8666 } else {
8667 if (c->stat & SOLE_POS_USED) {
8668 return NULL;
8669 } else {
8670 c->stat |= SOLE_POS_USED;
8671 }
8672 }
8673 }
8674 } else {
8675 if (c->stat & SOLE_POS_USED) {
8676 return NULL;
8677 } else {
8678 c->stat |= SOLE_POS_USED;
8679 }
8680 }
8681 return c->post;
8682 }
8683
8684 extern "C" grn_rc
8685 grn_ii_cursor_close(grn_ctx *ctx, grn_ii_cursor *c)
8686 {
8687 if (!c) {
8688 return GRN_INVALID_ARGUMENT;
8689 }
8690 datavec_fin(ctx, c->rdv);
8691 if (c->cinfo) {
8692 GRN_FREE(c->cinfo);
8693 }
8694 if (c->buf) {
8695 buffer_close(ctx, c->ii, c->buffer_pseg);
8696 }
8697 if (c->cp) {
8698 grn_io_win_unmap(ctx, &c->iw);
8699 }
8700 GRN_FREE(c);
8701 return GRN_SUCCESS;
8702 }
8703
8704 extern "C" uint32_t
8705 grn_ii_get_chunksize(grn_ctx *ctx, grn_ii *ii, grn_id tid)
8706 {
8707 uint32_t res, pos, *a;
8708 a = array_at(ctx, ii, tid);
8709 if (!a) {
8710 return 0;
8711 }
8712 if ((pos = a[0])) {
8713 if (POS_IS_EMBED(pos)) {
8714 res = 0;
8715 } else {
8716 buffer *buf;
8717 uint32_t pseg;
8718 buffer_term *bt;
8719 if ((pseg = buffer_open(ctx, ii, pos, &bt, &buf)) ==
8720 GRN_II_PSEG_NOT_ASSIGNED) {
8721 res = 0;
8722 } else {
8723 res = bt->size_in_chunk;
8724 buffer_close(ctx, ii, pseg);
8725 }
8726 }
8727 } else {
8728 res = 0;
8729 }
8730 array_unref(ctx, ii, tid);
8731 return res;
8732 }
8733
8734 /* This doesn't return the number of records that have the token. But
8735 * this returns a similar number based of size in buffer. Buffer may
8736 * have deleted tokens. One record may use multiple buffers. (To be
8737 * confirmed.) So the estimated size may not match the number of
8738 * records. */
8739 extern "C" uint32_t
8740 grn_ii_estimate_size(grn_ctx *ctx, grn_ii *ii, grn_id tid)
8741 {
8742 uint32_t res, pos, *a;
8743 a = array_at(ctx, ii, tid);
8744 if (!a) {
8745 return 0;
8746 }
8747 if ((pos = a[0])) {
8748 if (POS_IS_EMBED(pos)) {
8749 res = 1;
8750 } else {
8751 buffer *buf;
8752 uint32_t pseg;
8753 buffer_term *bt;
8754 if ((pseg = buffer_open(ctx, ii, pos, &bt, &buf)) ==
8755 GRN_II_PSEG_NOT_ASSIGNED) {
8756 res = 0;
8757 } else {
8758 res = a[1] + bt->size_in_buffer + 2;
8759 buffer_close(ctx, ii, pseg);
8760 }
8761 }
8762 } else {
8763 res = 0;
8764 }
8765 array_unref(ctx, ii, tid);
8766 return res;
8767 }
8768
8769 extern "C" int
8770 grn_ii_entry_info(grn_ctx *ctx,
8771 grn_ii *ii,
8772 grn_id tid,
8773 unsigned int *a,
8774 unsigned int *chunk,
8775 unsigned int *chunk_size,
8776 unsigned int *buffer_free,
8777 unsigned int *nterms,
8778 unsigned int *nterms_void,
8779 unsigned int *bt_tid,
8780 unsigned int *size_in_chunk,
8781 unsigned int *pos_in_chunk,
8782 unsigned int *size_in_buffer,
8783 unsigned int *pos_in_buffer)
8784 {
8785 buffer *b;
8786 buffer_term *bt;
8787 uint32_t pseg, *ap;
8788 ERRCLR(NULL);
8789 ap = array_at(ctx, ii, tid);
8790 if (!ap) {
8791 return 0;
8792 }
8793 a[0] = *ap;
8794 array_unref(ctx, ii, tid);
8795 if (!a[0]) {
8796 return 1;
8797 }
8798 if (POS_IS_EMBED(a[0])) {
8799 return 2;
8800 }
8801 if ((pseg = buffer_open(ctx, ii, a[0], &bt, &b)) ==
8802 GRN_II_PSEG_NOT_ASSIGNED) {
8803 return 3;
8804 }
8805 *chunk = b->header.chunk;
8806 *chunk_size = b->header.chunk_size;
8807 *buffer_free = b->header.buffer_free;
8808 *nterms = b->header.nterms;
8809 *bt_tid = bt->tid;
8810 *size_in_chunk = bt->size_in_chunk;
8811 *pos_in_chunk = bt->pos_in_chunk;
8812 *size_in_buffer = bt->size_in_buffer;
8813 *pos_in_buffer = bt->pos_in_buffer;
8814 buffer_close(ctx, ii, pseg);
8815 return 4;
8816 }
8817
8818 extern "C" uint32_t
8819 grn_ii_get_array_pseg(grn_ii *ii, uint32_t lseg)
8820 {
8821 return grn_ii_get_array_pseg_inline(ii, lseg);
8822 }
8823
8824 extern "C" uint32_t
8825 grn_ii_get_buffer_pseg(grn_ii *ii, uint32_t lseg)
8826 {
8827 return grn_ii_get_buffer_pseg_inline(ii, lseg);
8828 }
8829
8830 extern "C" uint32_t
8831 grn_ii_n_logical_segments(grn_ii *ii)
8832 {
8833 return grn_ii_n_logical_segments_inline(ii);
8834 }
8835
8836 extern "C" const char *
8837 grn_ii_path(grn_ii *ii)
8838 {
8839 return grn_io_path(ii->seg);
8840 }
8841
8842 extern "C" uint32_t
8843 grn_ii_max_section(grn_ii *ii)
8844 {
8845 return ii->header.common->smax;
8846 }
8847
8848 /* private classes */
8849
8850 /* b-heap */
8851
8852 typedef struct {
8853 int n_entries;
8854 int n_bins;
8855 grn_ii_cursor **bins;
8856 } cursor_heap;
8857
8858 extern "C" void
8859 grn_inspect_cursor_heap(grn_ctx *ctx, grn_obj *buffer, cursor_heap *heap)
8860 {
8861 grn_text_printf(ctx,
8862 buffer,
8863 "#<cursor_heap: n_entries=%d n_bins=%d\n",
8864 heap->n_entries,
8865 heap->n_bins);
8866 grn_text_printf(ctx, buffer, " bins:\n");
8867 int i;
8868 for (i = 0; i < heap->n_bins; i++) {
8869 grn_text_printf(ctx, buffer, " [%d] ", i);
8870 grn_ii_get_term(ctx, heap->bins[i]->ii, heap->bins[i]->id, buffer);
8871 grn_text_printf(ctx, buffer, "\n");
8872 }
8873 grn_text_printf(ctx, buffer, ">");
8874 }
8875
8876 static inline cursor_heap *
8877 cursor_heap_open(grn_ctx *ctx, int max)
8878 {
8879 auto h = static_cast<cursor_heap *>(GRN_CALLOC(sizeof(cursor_heap)));
8880 if (!h) {
8881 return NULL;
8882 }
8883 h->bins =
8884 static_cast<grn_ii_cursor **>(GRN_MALLOC(sizeof(grn_ii_cursor *) * max));
8885 if (!h->bins) {
8886 GRN_FREE(h);
8887 return NULL;
8888 }
8889 h->n_entries = 0;
8890 h->n_bins = max;
8891 return h;
8892 }
8893
8894 static inline grn_rc
8895 cursor_heap_push(grn_ctx *ctx,
8896 cursor_heap *h,
8897 grn_ii *ii,
8898 grn_id tid,
8899 uint32_t offset2,
8900 int weight,
8901 grn_id min)
8902 {
8903 int n, n2;
8904 grn_ii_cursor *c, *c2;
8905 if (h->n_entries >= h->n_bins) {
8906 int max = h->n_bins * 2;
8907 auto bins = static_cast<grn_ii_cursor **>(
8908 GRN_REALLOC(h->bins, sizeof(grn_ii_cursor *) * max));
8909 GRN_LOG(ctx, GRN_LOG_DEBUG, "expanded cursor_heap to %d,%p", max, bins);
8910 if (!bins) {
8911 return GRN_NO_MEMORY_AVAILABLE;
8912 }
8913 h->n_bins = max;
8914 h->bins = bins;
8915 }
8916 {
8917 if (!(c = grn_ii_cursor_open(ctx,
8918 ii,
8919 tid,
8920 min,
8921 GRN_ID_MAX,
8922 ii->n_elements,
8923 0))) {
8924 GRN_LOG(ctx, GRN_LOG_ERROR, "cursor open failed");
8925 return ctx->rc;
8926 }
8927 if (!grn_ii_cursor_next(ctx, c)) {
8928 grn_ii_cursor_close(ctx, c);
8929 return GRN_END_OF_DATA;
8930 }
8931 if (!grn_ii_cursor_next_pos(ctx, c)) {
8932 if (grn_logger_pass(ctx, GRN_LOG_ERROR)) {
8933 GRN_DEFINE_NAME(c->ii);
8934 grn_obj term;
8935 GRN_TEXT_INIT(&term, 0);
8936 grn_ii_get_term(ctx, c->ii, c->id, &term);
8937 GRN_LOG(ctx,
8938 GRN_LOG_ERROR,
8939 "[ii][cursor][heap][push][%.*s][%.*s][%u] "
8940 "invalid cursor: <%p>",
8941 name_size,
8942 name,
8943 (int)GRN_TEXT_LEN(&term),
8944 GRN_TEXT_VALUE(&term),
8945 c->id,
8946 c);
8947 GRN_OBJ_FIN(ctx, &term);
8948 }
8949 grn_ii_cursor_close(ctx, c);
8950 return GRN_END_OF_DATA;
8951 }
8952 if (weight) {
8953 c->weight = weight;
8954 }
8955 n = h->n_entries++;
8956 while (n) {
8957 n2 = (n - 1) >> 1;
8958 c2 = h->bins[n2];
8959 if (GRN_II_CURSOR_CMP(c, c2)) {
8960 break;
8961 }
8962 h->bins[n] = c2;
8963 n = n2;
8964 }
8965 h->bins[n] = c;
8966 }
8967 return GRN_SUCCESS;
8968 }
8969
8970 static inline grn_rc
8971 cursor_heap_push2(cursor_heap *h)
8972 {
8973 grn_rc rc = GRN_SUCCESS;
8974 return rc;
8975 }
8976
8977 static inline grn_ii_cursor *
8978 cursor_heap_min(cursor_heap *h)
8979 {
8980 return h->n_entries ? h->bins[0] : NULL;
8981 }
8982
8983 static inline void
8984 cursor_heap_recalc_min(cursor_heap *h)
8985 {
8986 int n = 0, n1, n2, m;
8987 if ((m = h->n_entries) > 1) {
8988 grn_ii_cursor *c = h->bins[0], *c1, *c2;
8989 for (;;) {
8990 n1 = n * 2 + 1;
8991 n2 = n1 + 1;
8992 c1 = n1 < m ? h->bins[n1] : NULL;
8993 c2 = n2 < m ? h->bins[n2] : NULL;
8994 if (c1 && GRN_II_CURSOR_CMP(c, c1)) {
8995 if (c2 && GRN_II_CURSOR_CMP(c, c2) && GRN_II_CURSOR_CMP(c1, c2)) {
8996 h->bins[n] = c2;
8997 n = n2;
8998 } else {
8999 h->bins[n] = c1;
9000 n = n1;
9001 }
9002 } else {
9003 if (c2 && GRN_II_CURSOR_CMP(c, c2)) {
9004 h->bins[n] = c2;
9005 n = n2;
9006 } else {
9007 h->bins[n] = c;
9008 break;
9009 }
9010 }
9011 }
9012 }
9013 }
9014
9015 static inline void
9016 cursor_heap_pop(grn_ctx *ctx, cursor_heap *h, grn_id min)
9017 {
9018 if (h->n_entries) {
9019 grn_ii_cursor *c = h->bins[0];
9020 grn_ii_cursor_set_min(ctx, c, min);
9021 if (!grn_ii_cursor_next(ctx, c)) {
9022 grn_ii_cursor_close(ctx, c);
9023 h->bins[0] = h->bins[--h->n_entries];
9024 } else if (!grn_ii_cursor_next_pos(ctx, c)) {
9025 if (grn_logger_pass(ctx, GRN_LOG_ERROR)) {
9026 GRN_DEFINE_NAME(c->ii);
9027 grn_obj term;
9028 GRN_TEXT_INIT(&term, 0);
9029 grn_ii_get_term(ctx, c->ii, c->id, &term);
9030 GRN_LOG(ctx,
9031 GRN_LOG_ERROR,
9032 "[ii][cursor][heap][pop][%.*s][%.*s][%u] invalid cursor: <%p>",
9033 name_size,
9034 name,
9035 (int)GRN_TEXT_LEN(&term),
9036 GRN_TEXT_VALUE(&term),
9037 c->id,
9038 c);
9039 GRN_OBJ_FIN(ctx, &term);
9040 }
9041 grn_ii_cursor_close(ctx, c);
9042 h->bins[0] = h->bins[--h->n_entries];
9043 }
9044 if (h->n_entries > 1) {
9045 cursor_heap_recalc_min(h);
9046 }
9047 }
9048 }
9049
9050 static inline void
9051 cursor_heap_pop_pos(grn_ctx *ctx, cursor_heap *h)
9052 {
9053 if (h->n_entries) {
9054 grn_ii_cursor *c = h->bins[0];
9055 if (!grn_ii_cursor_next_pos(ctx, c)) {
9056 if (!grn_ii_cursor_next(ctx, c)) {
9057 grn_ii_cursor_close(ctx, c);
9058 h->bins[0] = h->bins[--h->n_entries];
9059 } else if (!grn_ii_cursor_next_pos(ctx, c)) {
9060 if (grn_logger_pass(ctx, GRN_LOG_ERROR)) {
9061 GRN_DEFINE_NAME(c->ii);
9062 grn_obj term;
9063 GRN_TEXT_INIT(&term, 0);
9064 grn_ii_get_term(ctx, c->ii, c->id, &term);
9065 GRN_LOG(ctx,
9066 GRN_LOG_ERROR,
9067 "[ii][cursor][heap][pop][position][%.*s][%.*s][%u] "
9068 "invalid cursor: <%p>",
9069 name_size,
9070 name,
9071 (int)GRN_TEXT_LEN(&term),
9072 GRN_TEXT_VALUE(&term),
9073 c->id,
9074 c);
9075 GRN_OBJ_FIN(ctx, &term);
9076 }
9077 grn_ii_cursor_close(ctx, c);
9078 h->bins[0] = h->bins[--h->n_entries];
9079 }
9080 }
9081 if (h->n_entries > 1) {
9082 cursor_heap_recalc_min(h);
9083 }
9084 }
9085 }
9086
9087 static inline void
9088 cursor_heap_close(grn_ctx *ctx, cursor_heap *h)
9089 {
9090 int i;
9091 if (!h) {
9092 return;
9093 }
9094 for (i = h->n_entries; i--;) {
9095 grn_ii_cursor_close(ctx, h->bins[i]);
9096 }
9097 GRN_FREE(h->bins);
9098 GRN_FREE(h);
9099 }
9100
9101 static grn_rc
9102 grn_vector2updspecs(grn_ctx *ctx,
9103 grn_ii *ii,
9104 grn_id rid,
9105 unsigned int original_section,
9106 unsigned int section,
9107 grn_obj *in,
9108 grn_obj *out,
9109 grn_tokenize_mode mode,
9110 grn_obj *posting)
9111 {
9112 grn_id tid;
9113 grn_section *v;
9114 grn_token_cursor *token_cursor;
9115 grn_ii_updspec **u;
9116 grn_hash *h = (grn_hash *)out;
9117 grn_obj *lexicon = ii->lexicon;
9118 if (in->u.v.body) {
9119 grn_obj *source_column = nullptr;
9120 auto n_sources = DB_OBJ(ii)->source_size / sizeof(grn_id);
9121 if (n_sources > 0 && original_section > 0) {
9122 auto source_ids = static_cast<grn_id *>(DB_OBJ(ii)->source);
9123 auto source_id = source_ids[original_section - 1];
9124 source_column = grn_ctx_at(ctx, source_id);
9125 }
9126 bool have_tokenizer = grn_table_have_tokenizer(ctx, lexicon);
9127 const char *head = GRN_BULK_HEAD(in->u.v.body);
9128 int32_t i;
9129 int32_t n = (int32_t)(in->u.v.n_sections);
9130 for (i = 0, v = in->u.v.sections; i < n; i++, v++) {
9131 unsigned int token_flags = 0;
9132 if (v->length && (token_cursor = grn_token_cursor_open(ctx,
9133 lexicon,
9134 head + v->offset,
9135 v->length,
9136 mode,
9137 token_flags))) {
9138 grn_token_cursor_set_source_id(ctx, token_cursor, rid);
9139 if (v->domain != GRN_ID_NIL) {
9140 grn_token_cursor_set_query_domain(ctx, token_cursor, v->domain);
9141 }
9142 if (source_column) {
9143 grn_token_cursor_set_source_column(ctx, token_cursor, source_column);
9144 }
9145 while (!token_cursor->status) {
9146 if ((tid = grn_token_cursor_next(ctx, token_cursor))) {
9147 if (posting) {
9148 GRN_RECORD_PUT(ctx, posting, tid);
9149 }
9150 if (!grn_hash_add(ctx,
9151 h,
9152 &tid,
9153 sizeof(grn_id),
9154 (void **)&u,
9155 NULL)) {
9156 break;
9157 }
9158 if (!*u) {
9159 if (!(*u = grn_ii_updspec_open(ctx, rid, section))) {
9160 GRN_DEFINE_NAME(ii);
9161 MERR("[ii][update][spec] failed to create an update spec: "
9162 "<%.*s>: "
9163 "record:<%u>:<%u>, token:<%u>:<%d>:<%f>",
9164 name_size,
9165 name,
9166 rid,
9167 section,
9168 tid,
9169 token_cursor->pos,
9170 v->weight);
9171 grn_token_cursor_close(ctx, token_cursor);
9172 return ctx->rc;
9173 }
9174 }
9175 if (grn_ii_updspec_add(ctx,
9176 *u,
9177 have_tokenizer ? token_cursor->pos : i,
9178 (int32_t)(v->weight))) {
9179 GRN_DEFINE_NAME(ii);
9180 MERR("[ii][update][spec] failed to add to update spec: "
9181 "<%.*s>: "
9182 "record:<%u>:<%u>, token:<%u>:<%d>:<%f>",
9183 name_size,
9184 name,
9185 rid,
9186 section,
9187 tid,
9188 token_cursor->pos,
9189 v->weight);
9190 grn_token_cursor_close(ctx, token_cursor);
9191 return ctx->rc;
9192 }
9193 }
9194 }
9195 grn_token_cursor_close(ctx, token_cursor);
9196 }
9197 }
9198 if (source_column) {
9199 grn_obj_unref(ctx, source_column);
9200 }
9201 }
9202 return ctx->rc;
9203 }
9204
9205 static grn_rc
9206 grn_uvector2updspecs_data(grn_ctx *ctx,
9207 grn_ii *ii,
9208 grn_id rid,
9209 unsigned int section,
9210 grn_obj *in,
9211 grn_obj *out,
9212 grn_tokenize_mode mode,
9213 grn_obj *posting)
9214 {
9215 grn_rc rc = GRN_SUCCESS;
9216 grn_hash *h = (grn_hash *)out;
9217 grn_obj *lexicon = ii->lexicon;
9218 grn_obj *tokenizer;
9219 bool need_cast;
9220 grn_obj element_buffer;
9221 grn_obj casted_element_buffer;
9222 int i, n;
9223 unsigned int element_size;
9224
9225 tokenizer = grn_obj_get_info(ctx, lexicon, GRN_INFO_DEFAULT_TOKENIZER, NULL);
9226 need_cast = (!tokenizer && lexicon->header.domain != in->header.domain);
9227 if (need_cast) {
9228 GRN_VALUE_FIX_SIZE_INIT(&element_buffer, 0, in->header.domain);
9229 GRN_VALUE_FIX_SIZE_INIT(&casted_element_buffer,
9230 GRN_OBJ_VECTOR,
9231 lexicon->header.domain);
9232 } else {
9233 GRN_VOID_INIT(&element_buffer);
9234 GRN_VOID_INIT(&casted_element_buffer);
9235 }
9236
9237 n = grn_uvector_size(ctx, in);
9238 element_size = grn_uvector_element_size(ctx, in);
9239 for (i = 0; i < n; i++) {
9240 grn_token_cursor *token_cursor;
9241 unsigned int token_flags = 0;
9242 const char *element;
9243
9244 element = GRN_BULK_HEAD(in) + (element_size * i);
9245 if (need_cast) {
9246 GRN_BULK_REWIND(&element_buffer);
9247 GRN_BULK_REWIND(&casted_element_buffer);
9248 grn_bulk_write(ctx, &element_buffer, element, element_size);
9249 grn_rc cast_rc =
9250 grn_obj_cast(ctx, &element_buffer, &casted_element_buffer, true);
9251 if (cast_rc != GRN_SUCCESS) {
9252 GRN_DEFINE_NAME(ii);
9253 {
9254 grn_obj *domain =
9255 grn_ctx_at(ctx, casted_element_buffer.header.domain);
9256 char domain_name[GRN_TABLE_MAX_KEY_SIZE];
9257 int domain_name_size;
9258 domain_name_size =
9259 grn_obj_name(ctx, domain, domain_name, GRN_TABLE_MAX_KEY_SIZE);
9260 grn_obj inspected_element;
9261 GRN_TEXT_INIT(&inspected_element, 0);
9262 grn_inspect(ctx, &inspected_element, &element_buffer);
9263 GRN_LOG(ctx,
9264 GRN_LOG_WARNING,
9265 "[ii][updspec][uvector][data][%.*s] "
9266 "failed to cast to <%.*s>: <%.*s>",
9267 name_size,
9268 name,
9269 domain_name_size,
9270 domain_name,
9271 (int)GRN_TEXT_LEN(&inspected_element),
9272 GRN_TEXT_VALUE(&inspected_element));
9273 GRN_OBJ_FIN(ctx, &inspected_element);
9274 }
9275 }
9276 element = GRN_BULK_HEAD(&casted_element_buffer);
9277 element_size = GRN_BULK_VSIZE(&casted_element_buffer);
9278 }
9279 token_cursor = grn_token_cursor_open(ctx,
9280 lexicon,
9281 element,
9282 element_size,
9283 mode,
9284 token_flags);
9285 if (!token_cursor) {
9286 continue;
9287 }
9288
9289 grn_token_cursor_set_query_domain(ctx, token_cursor, in->header.domain);
9290 while (!token_cursor->status) {
9291 grn_id tid;
9292 if ((tid = grn_token_cursor_next(ctx, token_cursor))) {
9293 grn_ii_updspec **u;
9294 int pos;
9295
9296 if (posting) {
9297 GRN_RECORD_PUT(ctx, posting, tid);
9298 }
9299 if (!grn_hash_add(ctx, h, &tid, sizeof(grn_id), (void **)&u, NULL)) {
9300 break;
9301 }
9302 if (!*u) {
9303 if (!(*u = grn_ii_updspec_open(ctx, rid, section))) {
9304 GRN_LOG(ctx,
9305 GRN_LOG_ALERT,
9306 "grn_ii_updspec_open on grn_uvector2updspecs_data failed!");
9307 grn_token_cursor_close(ctx, token_cursor);
9308 rc = GRN_NO_MEMORY_AVAILABLE;
9309 goto exit;
9310 }
9311 }
9312 if (tokenizer) {
9313 pos = token_cursor->pos;
9314 } else {
9315 pos = i;
9316 }
9317 if (grn_ii_updspec_add(ctx, *u, pos, 0)) {
9318 GRN_LOG(ctx,
9319 GRN_LOG_ALERT,
9320 "grn_ii_updspec_add on grn_uvector2updspecs failed!");
9321 grn_token_cursor_close(ctx, token_cursor);
9322 rc = GRN_NO_MEMORY_AVAILABLE;
9323 goto exit;
9324 }
9325 }
9326 }
9327
9328 grn_token_cursor_close(ctx, token_cursor);
9329 }
9330
9331 exit:
9332 GRN_OBJ_FIN(ctx, &element_buffer);
9333 GRN_OBJ_FIN(ctx, &casted_element_buffer);
9334
9335 return rc;
9336 }
9337
9338 static grn_rc
9339 grn_uvector2updspecs_id(grn_ctx *ctx,
9340 grn_ii *ii,
9341 grn_id rid,
9342 unsigned int section,
9343 grn_obj *in,
9344 grn_obj *out)
9345 {
9346 int i, n;
9347 grn_ii_updspec **u;
9348 grn_hash *h = (grn_hash *)out;
9349
9350 n = grn_vector_size(ctx, in);
9351 for (i = 0; i < n; i++) {
9352 grn_id id;
9353 uint32_t weight;
9354
9355 id = grn_uvector_get_element(ctx, in, i, &weight);
9356 if (!grn_hash_add(ctx, h, &id, sizeof(grn_id), (void **)&u, NULL)) {
9357 break;
9358 }
9359 if (!*u) {
9360 if (!(*u = grn_ii_updspec_open(ctx, rid, section))) {
9361 GRN_LOG(ctx,
9362 GRN_LOG_ALERT,
9363 "grn_ii_updspec_open on grn_ii_update failed!");
9364 return GRN_NO_MEMORY_AVAILABLE;
9365 }
9366 }
9367 if (grn_ii_updspec_add(ctx, *u, i, weight)) {
9368 GRN_LOG(ctx,
9369 GRN_LOG_ALERT,
9370 "grn_ii_updspec_add on grn_ii_update failed!");
9371 return GRN_NO_MEMORY_AVAILABLE;
9372 }
9373 }
9374 return GRN_SUCCESS;
9375 }
9376
9377 static grn_rc
9378 grn_uvector2updspecs(grn_ctx *ctx,
9379 grn_ii *ii,
9380 grn_id rid,
9381 unsigned int section,
9382 grn_obj *in,
9383 grn_obj *out,
9384 grn_tokenize_mode mode,
9385 grn_obj *posting)
9386 {
9387 if (grn_type_id_is_builtin(ctx, in->header.domain)) {
9388 return grn_uvector2updspecs_data(ctx,
9389 ii,
9390 rid,
9391 section,
9392 in,
9393 out,
9394 mode,
9395 posting);
9396 } else {
9397 return grn_uvector2updspecs_id(ctx, ii, rid, section, in, out);
9398 }
9399 }
9400
9401 static inline grn_rc
9402 grn_ii_column_update_internal(grn_ctx *ctx,
9403 grn_ii *ii,
9404 grn_id rid,
9405 unsigned int original_section,
9406 unsigned int section,
9407 grn_obj *oldvalue,
9408 grn_obj *newvalue,
9409 grn_obj *posting)
9410 {
9411 grn_id *tp;
9412 bool do_grn_ii_updspec_cmp = true;
9413 grn_ii_updspec **u, **un;
9414 grn_obj *old_value = oldvalue;
9415 grn_obj *new_value = newvalue;
9416 grn_obj *old_value_bulk = NULL;
9417 grn_obj *new_value_bulk = NULL;
9418 grn_obj old_buffer;
9419 grn_obj new_buffer;
9420 grn_obj buf, *post = NULL;
9421
9422 if (!ii) {
9423 ERR(GRN_INVALID_ARGUMENT, "[ii][column][update] ii is NULL");
9424 return ctx->rc;
9425 }
9426 if (!ii->lexicon) {
9427 ERR(GRN_INVALID_ARGUMENT, "[ii][column][update] lexicon is NULL");
9428 return ctx->rc;
9429 }
9430 if (rid == GRN_ID_NIL) {
9431 GRN_DEFINE_NAME(ii);
9432 ERR(GRN_INVALID_ARGUMENT,
9433 "[ii][column][update] record ID is nil: <%.*s>",
9434 name_size,
9435 name);
9436 return ctx->rc;
9437 }
9438 if (old_value && old_value->header.type == GRN_VOID) {
9439 old_value = NULL;
9440 }
9441 if (new_value && new_value->header.type == GRN_VOID) {
9442 new_value = NULL;
9443 }
9444 if (old_value || new_value) {
9445 bool is_text_vector_index = true;
9446 if (old_value) {
9447 grn_obj *extracted_old_value =
9448 grn_table_extract(ctx, ii->lexicon, old_value);
9449 if (!extracted_old_value) {
9450 return ctx->rc;
9451 }
9452 if (extracted_old_value != old_value) {
9453 old_value = extracted_old_value;
9454 }
9455 if (!(old_value->header.type == GRN_VECTOR &&
9456 grn_type_id_is_text_family(ctx, old_value->header.domain))) {
9457 is_text_vector_index = false;
9458 }
9459 }
9460 if (new_value) {
9461 grn_obj *extracted_new_value =
9462 grn_table_extract(ctx, ii->lexicon, new_value);
9463 if (!extracted_new_value) {
9464 return ctx->rc;
9465 }
9466 if (extracted_new_value != new_value) {
9467 new_value = extracted_new_value;
9468 }
9469 if (!(new_value->header.type == GRN_VECTOR &&
9470 grn_type_id_is_text_family(ctx, new_value->header.domain))) {
9471 is_text_vector_index = false;
9472 }
9473 }
9474 if (is_text_vector_index) {
9475 grn_obj *tokenizer;
9476 grn_table_get_info(ctx, ii->lexicon, NULL, NULL, &tokenizer, NULL, NULL);
9477 if (tokenizer) {
9478 grn_obj old_elem, new_elem;
9479 unsigned int i, max_n;
9480 unsigned int old_n = 0, new_n = 0;
9481 if (old_value) {
9482 old_n = grn_vector_size(ctx, old_value);
9483 GRN_OBJ_INIT(&old_elem,
9484 GRN_BULK,
9485 GRN_OBJ_DO_SHALLOW_COPY,
9486 old_value->header.domain);
9487 }
9488 if (new_value) {
9489 new_n = grn_vector_size(ctx, new_value);
9490 GRN_OBJ_INIT(&new_elem,
9491 GRN_BULK,
9492 GRN_OBJ_DO_SHALLOW_COPY,
9493 new_value->header.domain);
9494 }
9495 max_n = (old_n > new_n) ? old_n : new_n;
9496 for (i = 0; i < max_n; i++) {
9497 grn_rc rc;
9498 grn_obj *old_p = NULL, *new_p = NULL;
9499 if (i < old_n) {
9500 const char *value;
9501 unsigned int size;
9502 size =
9503 grn_vector_get_element(ctx, old_value, i, &value, NULL, NULL);
9504 GRN_TEXT_SET_REF(&old_elem, value, size);
9505 old_p = &old_elem;
9506 }
9507 if (i < new_n) {
9508 const char *value;
9509 unsigned int size;
9510 size =
9511 grn_vector_get_element(ctx, new_value, i, &value, NULL, NULL);
9512 GRN_TEXT_SET_REF(&new_elem, value, size);
9513 new_p = &new_elem;
9514 }
9515 rc = grn_ii_column_update_internal(ctx,
9516 ii,
9517 rid,
9518 original_section,
9519 section + i,
9520 old_p,
9521 new_p,
9522 posting);
9523 if (rc != GRN_SUCCESS) {
9524 break;
9525 }
9526 }
9527 if (old_value) {
9528 GRN_OBJ_FIN(ctx, &old_elem);
9529 }
9530 if (new_value) {
9531 GRN_OBJ_FIN(ctx, &new_elem);
9532 }
9533 return ctx->rc;
9534 }
9535 }
9536 }
9537 if (posting) {
9538 GRN_RECORD_INIT(&buf, GRN_OBJ_VECTOR, grn_obj_id(ctx, ii->lexicon));
9539 post = &buf;
9540 }
9541 if (grn_io_lock(ctx, ii->seg, grn_lock_timeout)) {
9542 return ctx->rc;
9543 }
9544 if (new_value) {
9545 unsigned char type = (ii->obj.header.domain == new_value->header.domain)
9546 ? GRN_UVECTOR
9547 : new_value->header.type;
9548 switch (type) {
9549 case GRN_BULK:
9550 {
9551 if (grn_bulk_is_zero(ctx, new_value)) {
9552 do_grn_ii_updspec_cmp = false;
9553 }
9554 new_value_bulk = new_value;
9555 GRN_OBJ_INIT(&new_buffer,
9556 GRN_VECTOR,
9557 GRN_OBJ_DO_SHALLOW_COPY,
9558 new_value->header.domain);
9559 new_buffer.u.v.body = new_value;
9560 new_value = &new_buffer;
9561 grn_vector_delimit(ctx, new_value, 0, new_value_bulk->header.domain);
9562 }
9563 /* fallthru */
9564 case GRN_VECTOR:
9565 {
9566 grn_obj *new_value_before = new_value;
9567 new_value = (grn_obj *)grn_hash_create(ctx,
9568 NULL,
9569 sizeof(grn_id),
9570 sizeof(grn_ii_updspec *),
9571 GRN_HASH_TINY);
9572 if (!new_value) {
9573 GRN_DEFINE_NAME(ii);
9574 MERR(
9575 "[ii][column][update][new][vector] failed to create a hash table: "
9576 "<%.*s>: ",
9577 name_size,
9578 name);
9579 } else {
9580 grn_vector2updspecs(ctx,
9581 ii,
9582 rid,
9583 original_section,
9584 section,
9585 new_value_before,
9586 new_value,
9587 GRN_TOKEN_ADD,
9588 post);
9589 }
9590 if (new_value_before != newvalue) {
9591 grn_obj_close(ctx, new_value_before);
9592 }
9593 if (ctx->rc != GRN_SUCCESS) {
9594 goto exit;
9595 }
9596 }
9597 break;
9598 case GRN_UVECTOR:
9599 {
9600 grn_obj *new_value_before = new_value;
9601 new_value = (grn_obj *)grn_hash_create(ctx,
9602 NULL,
9603 sizeof(grn_id),
9604 sizeof(grn_ii_updspec *),
9605 GRN_HASH_TINY);
9606 if (!new_value) {
9607 GRN_DEFINE_NAME(ii);
9608 MERR(
9609 "[ii][column][update][new][uvector] failed to create a hash table: "
9610 "<%.*s>: ",
9611 name_size,
9612 name);
9613 } else {
9614 if (new_value_before->header.type == GRN_UVECTOR) {
9615 grn_uvector2updspecs(ctx,
9616 ii,
9617 rid,
9618 section,
9619 new_value_before,
9620 new_value,
9621 GRN_TOKEN_ADD,
9622 post);
9623 } else {
9624 grn_obj uvector;
9625 uint32_t weight = 0;
9626 GRN_VALUE_FIX_SIZE_INIT(&uvector,
9627 GRN_OBJ_VECTOR,
9628 new_value_before->header.domain);
9629 if (new_value_before->header.impl_flags & GRN_OBJ_WITH_WEIGHT) {
9630 uvector.header.impl_flags |= GRN_OBJ_WITH_WEIGHT;
9631 }
9632 grn_uvector_add_element(ctx,
9633 &uvector,
9634 GRN_RECORD_VALUE(new_value_before),
9635 weight);
9636 grn_uvector2updspecs(ctx,
9637 ii,
9638 rid,
9639 section,
9640 &uvector,
9641 new_value,
9642 GRN_TOKEN_ADD,
9643 post);
9644 GRN_OBJ_FIN(ctx, &uvector);
9645 }
9646 }
9647 if (new_value_before != newvalue) {
9648 grn_obj_close(ctx, new_value_before);
9649 }
9650 if (ctx->rc != GRN_SUCCESS) {
9651 goto exit;
9652 }
9653 }
9654 break;
9655 case GRN_TABLE_HASH_KEY:
9656 break;
9657 default:
9658 {
9659 GRN_DEFINE_NAME(ii);
9660 ERR(GRN_INVALID_ARGUMENT,
9661 "[ii][column][update][new] invalid object: "
9662 "<%.*s>: "
9663 "<%s>(%#x)",
9664 name_size,
9665 name,
9666 grn_obj_type_to_string(type),
9667 type);
9668 }
9669 goto exit;
9670 }
9671 }
9672 if (posting) {
9673 grn_ii_updspec *u_;
9674 uint32_t offset = 0;
9675 grn_id tid_ = 0, gap, tid, *tpe;
9676 grn_table_sort_optarg arg = {
9677 GRN_TABLE_SORT_ASC | GRN_TABLE_SORT_AS_NUMBER |
9678 GRN_TABLE_SORT_AS_UNSIGNED,
9679 NULL,
9680 NULL,
9681 NULL,
9682 0,
9683 };
9684 grn_array *sorted = grn_array_create(ctx, NULL, sizeof(grn_id), 0);
9685 grn_hash_sort(ctx, (grn_hash *)new_value, -1, sorted, &arg);
9686 GRN_TEXT_PUT(ctx,
9687 posting,
9688 ((grn_hash *)new_value)->n_entries,
9689 sizeof(uint32_t));
9690 GRN_ARRAY_EACH(ctx, sorted, 0, 0, id, &tp, {
9691 grn_hash_get_key(ctx, (grn_hash *)new_value, *tp, &tid, sizeof(grn_id));
9692 gap = tid - tid_;
9693 GRN_TEXT_PUT(ctx, posting, &gap, sizeof(grn_id));
9694 tid_ = tid;
9695 });
9696 GRN_ARRAY_EACH(ctx, sorted, 0, 0, id, &tp, {
9697 grn_hash_get_value(ctx, (grn_hash *)new_value, *tp, &u_);
9698 u_->offset = offset++;
9699 GRN_TEXT_PUT(ctx, posting, &u_->tf, sizeof(int32_t));
9700 });
9701 tpe = (grn_id *)GRN_BULK_CURR(post);
9702 for (tp = (grn_id *)GRN_BULK_HEAD(post); tp < tpe; tp++) {
9703 grn_hash_get(ctx,
9704 (grn_hash *)new_value,
9705 (void *)tp,
9706 sizeof(grn_id),
9707 (void **)&u);
9708 GRN_TEXT_PUT(ctx, posting, &(*u)->offset, sizeof(int32_t));
9709 }
9710 GRN_OBJ_FIN(ctx, post);
9711 grn_array_close(ctx, sorted);
9712 }
9713
9714 if (old_value) {
9715 unsigned char type = (ii->obj.header.domain == old_value->header.domain)
9716 ? GRN_UVECTOR
9717 : old_value->header.type;
9718 switch (type) {
9719 case GRN_BULK:
9720 {
9721 old_value_bulk = old_value;
9722 GRN_OBJ_INIT(&old_buffer,
9723 GRN_VECTOR,
9724 GRN_OBJ_DO_SHALLOW_COPY,
9725 old_value->header.domain);
9726 old_buffer.u.v.body = old_value;
9727 old_value = &old_buffer;
9728 grn_vector_delimit(ctx, old_value, 0, old_value_bulk->header.domain);
9729 }
9730 /* fallthru */
9731 case GRN_VECTOR:
9732 {
9733 grn_obj *old_value_keep = old_value;
9734 old_value = (grn_obj *)grn_hash_create(ctx,
9735 NULL,
9736 sizeof(grn_id),
9737 sizeof(grn_ii_updspec *),
9738 GRN_HASH_TINY);
9739 if (!old_value) {
9740 GRN_DEFINE_NAME(ii);
9741 MERR(
9742 "[ii][column][update][old][vector] failed to create a hash table: "
9743 "<%.*s>: ",
9744 name_size,
9745 name);
9746 } else {
9747 grn_vector2updspecs(ctx,
9748 ii,
9749 rid,
9750 original_section,
9751 section,
9752 old_value_keep,
9753 old_value,
9754 GRN_TOKEN_DEL,
9755 NULL);
9756 }
9757 if (old_value_keep != oldvalue) {
9758 grn_obj_close(ctx, old_value_keep);
9759 }
9760 if (ctx->rc != GRN_SUCCESS) {
9761 goto exit;
9762 }
9763 }
9764 break;
9765 case GRN_UVECTOR:
9766 {
9767 grn_obj *old_value_keep = old_value;
9768 old_value = (grn_obj *)grn_hash_create(ctx,
9769 NULL,
9770 sizeof(grn_id),
9771 sizeof(grn_ii_updspec *),
9772 GRN_HASH_TINY);
9773 if (!old_value) {
9774 GRN_DEFINE_NAME(ii);
9775 MERR(
9776 "[ii][column][update][old][uvector] failed to create a hash table: "
9777 "<%.*s>: ",
9778 name_size,
9779 name);
9780 } else {
9781 if (old_value_keep->header.type == GRN_UVECTOR) {
9782 grn_uvector2updspecs(ctx,
9783 ii,
9784 rid,
9785 section,
9786 old_value_keep,
9787 old_value,
9788 GRN_TOKEN_DEL,
9789 NULL);
9790 } else {
9791 grn_obj uvector;
9792 uint32_t weight = 0;
9793 GRN_VALUE_FIX_SIZE_INIT(&uvector,
9794 GRN_OBJ_VECTOR,
9795 old_value_keep->header.domain);
9796 if (old_value_keep->header.impl_flags & GRN_OBJ_WITH_WEIGHT) {
9797 uvector.header.impl_flags |= GRN_OBJ_WITH_WEIGHT;
9798 }
9799 grn_uvector_add_element(ctx,
9800 &uvector,
9801 GRN_RECORD_VALUE(old_value_keep),
9802 weight);
9803 grn_uvector2updspecs(ctx,
9804 ii,
9805 rid,
9806 section,
9807 &uvector,
9808 old_value,
9809 GRN_TOKEN_DEL,
9810 NULL);
9811 GRN_OBJ_FIN(ctx, &uvector);
9812 }
9813 }
9814 if (old_value_keep != oldvalue) {
9815 grn_obj_close(ctx, old_value_keep);
9816 }
9817 if (ctx->rc != GRN_SUCCESS) {
9818 goto exit;
9819 }
9820 }
9821 break;
9822 case GRN_TABLE_HASH_KEY:
9823 break;
9824 default:
9825 {
9826 GRN_DEFINE_NAME(ii);
9827 ERR(GRN_INVALID_ARGUMENT,
9828 "[ii][column][update][old] invalid object: "
9829 "<%.*s>: "
9830 "<%s>(%#x)",
9831 name_size,
9832 name,
9833 grn_obj_type_to_string(type),
9834 type);
9835 }
9836 goto exit;
9837 }
9838 }
9839
9840 if (old_value) {
9841 grn_id eid;
9842 grn_hash *o = (grn_hash *)old_value;
9843 grn_hash *n = (grn_hash *)new_value;
9844 GRN_HASH_EACH(ctx, o, id, &tp, NULL, &u, {
9845 if (n && (eid = grn_hash_get(ctx, n, tp, sizeof(grn_id), (void **)&un))) {
9846 if (do_grn_ii_updspec_cmp && !grn_ii_updspec_cmp(*u, *un)) {
9847 grn_ii_updspec_close(ctx, *un);
9848 grn_hash_delete_by_id(ctx, n, eid, NULL);
9849 }
9850 } else {
9851 grn_ii_delete_one(ctx, ii, *tp, *u, n);
9852 }
9853 if (ctx->rc != GRN_SUCCESS) {
9854 break;
9855 }
9856 });
9857 }
9858 if (new_value) {
9859 grn_hash *n = (grn_hash *)new_value;
9860 GRN_HASH_EACH(ctx, n, id, &tp, NULL, &u, {
9861 grn_ii_update_one(ctx, ii, *tp, *u, n);
9862 if (ctx->rc != GRN_SUCCESS) {
9863 break;
9864 }
9865 });
9866 } else {
9867 if (!section) {
9868 /* todo: delete key when all sections deleted */
9869 }
9870 }
9871 exit:
9872 grn_io_unlock(ctx, ii->seg);
9873 if (old_value) {
9874 if (old_value->header.type == GRN_TABLE_HASH_KEY) {
9875 grn_hash *o = (grn_hash *)old_value;
9876 GRN_HASH_EACH(ctx, o, id, &tp, NULL, &u, {
9877 grn_ii_updspec_close(ctx, *u);
9878 });
9879 }
9880 if (old_value != oldvalue) {
9881 grn_obj_close(ctx, old_value);
9882 }
9883 if (old_value_bulk && old_value_bulk != oldvalue) {
9884 grn_obj_close(ctx, old_value_bulk);
9885 }
9886 }
9887 if (new_value) {
9888 if (new_value->header.type == GRN_TABLE_HASH_KEY) {
9889 grn_hash *n = (grn_hash *)new_value;
9890 GRN_HASH_EACH(ctx, n, id, &tp, NULL, &u, {
9891 grn_ii_updspec_close(ctx, *u);
9892 });
9893 }
9894 if (new_value != newvalue) {
9895 grn_obj_close(ctx, new_value);
9896 }
9897 if (new_value_bulk && new_value_bulk != newvalue) {
9898 grn_obj_close(ctx, new_value_bulk);
9899 }
9900 }
9901 return ctx->rc;
9902 }
9903
9904 extern "C" grn_rc
9905 grn_ii_column_update(grn_ctx *ctx,
9906 grn_ii *ii,
9907 grn_id rid,
9908 unsigned int section,
9909 grn_obj *oldvalue,
9910 grn_obj *newvalue,
9911 grn_obj *posting)
9912 {
9913 GRN_SLOW_LOG_PUSH(ctx, GRN_LOG_DEBUG);
9914 grn_rc rc = grn_ii_column_update_internal(ctx,
9915 ii,
9916 rid,
9917 section,
9918 section,
9919 oldvalue,
9920 newvalue,
9921 posting);
9922 GRN_SLOW_LOG_POP_BEGIN(ctx, GRN_LOG_DEBUG, elapsed_time)
9923 {
9924 GRN_DEFINE_NAME(ii);
9925 GRN_LOG(ctx,
9926 GRN_LOG_DEBUG,
9927 "[ii][column][update][slow][%f] "
9928 "<%.*s>: "
9929 "record:<%u>:<%u>",
9930 elapsed_time,
9931 name_size,
9932 name,
9933 rid,
9934 section);
9935 }
9936 GRN_SLOW_LOG_POP_END(ctx);
9937 return rc;
9938 }
9939
9940 /* token_info */
9941
9942 typedef struct {
9943 /* All token cursors of the token info. If the target token is
9944 * expanded (EX_* except EX_NONE), token cursors of multiple tokens
9945 * may be included. */
9946 cursor_heap *cursors;
9947 /* The number of tokens from the first token in the given query or a
9948 * phrase in the given query. */
9949 uint32_t offset;
9950 /* The number of tokens from the first token in the input. */
9951 int32_t pos;
9952 /* The estimated size (see grn_ii_estimate_size() for estimated
9953 * size) of all tokens including this token_info. */
9954 uint32_t size;
9955 /* The number of the token info. If the target token is expanded
9956 * (EX_* except EX_NONE), there may be multiple tokens in a token
9957 * info. */
9958 int ntoken;
9959 /* The current posting of the token info. */
9960 grn_posting *p;
9961 /* The ID of phrase group that the token info belongs.
9962 *
9963 * This is used only for GRN_OP_*NEAR_PHRASE_PRODUCT. */
9964 uint32_t phrase_group_id;
9965 /* The ID of phrase that the token info belongs.
9966 *
9967 * This is used only for GRN_OP_*NEAR_PHRASE*. */
9968 uint32_t phrase_id;
9969 /* The number of tokens in the phrase that the token info
9970 * belongs. This counts not used tokens. For example, "abc" with
9971 * TokenNgram is tokenized to "ab", "bc" and "c" but "c" isn't
9972 * used. Because we can find "abc" only with "ab" and
9973 * "bc". n_tokens_in_phrase is 3 because it counts
9974 * "c". n_used_tokens_in_phrase is 2 because it doesn't count "c".
9975 *
9976 * This is used only for GRN_OP_*NEAR_PHRASE*. */
9977 uint32_t n_tokens_in_phrase;
9978 /* The number of used tokens in the phrase that the token info
9979 * belongs. See also the above n_tokens_in_phrase document.
9980 *
9981 * This is used only for GRN_OP_*NEAR_PHRASE*. */
9982 uint32_t n_used_tokens_in_phrase;
9983 /* Whether the token info must be the last token or not. If the
9984 * token info is appeared not at the last, the query isn't matched.
9985 *
9986 * This is used only for GRN_OP_*NEAR_PHRASE*. */
9987 bool must_last;
9988 } token_info;
9989
9990 extern "C" void
9991 grn_inspect_token_info(grn_ctx *ctx, grn_obj *buffer, token_info *info)
9992 {
9993 grn_text_printf(ctx, buffer, "#<token_info:\n");
9994 grn_text_printf(ctx, buffer, " cursors: ");
9995 grn_obj cursor_heap_inspected;
9996 GRN_TEXT_INIT(&cursor_heap_inspected, 0);
9997 grn_inspect_cursor_heap(ctx, &cursor_heap_inspected, info->cursors);
9998 grn_inspect_indent(ctx, buffer, &cursor_heap_inspected, " ");
9999 GRN_OBJ_FIN(ctx, &cursor_heap_inspected);
10000 grn_text_printf(ctx, buffer, "\n");
10001 grn_text_printf(ctx, buffer, " offset:%u\n", info->offset);
10002 grn_text_printf(ctx, buffer, " pos:%d\n", info->pos);
10003 grn_text_printf(ctx, buffer, " size:%u\n", info->size);
10004 grn_text_printf(ctx, buffer, " n_tokens:%d\n", info->ntoken);
10005 grn_text_printf(
10006 ctx,
10007 buffer,
10008 " posting:#<posting: rid:%u sid:%u pos:%u tf:%u weight:%u>\n",
10009 info->p->rid,
10010 info->p->sid,
10011 info->p->pos,
10012 info->p->tf,
10013 info->p->weight);
10014 grn_text_printf(ctx, buffer, " phrase_group_id:%u\n", info->phrase_group_id);
10015 grn_text_printf(ctx, buffer, " phrase_id:%u\n", info->phrase_id);
10016 grn_text_printf(ctx,
10017 buffer,
10018 " n_tokens_in_phrase:%u\n",
10019 info->n_tokens_in_phrase);
10020 grn_text_printf(ctx,
10021 buffer,
10022 " n_used_tokens_in_phrase:%u\n",
10023 info->n_used_tokens_in_phrase);
10024 grn_text_printf(ctx,
10025 buffer,
10026 " must_last:%s\n",
10027 info->must_last ? "true" : "false");
10028 grn_text_printf(ctx, buffer, ">");
10029 }
10030
10031 extern "C" void
10032 grn_p_token_info(grn_ctx *ctx, token_info *info)
10033 {
10034 grn_obj inspected;
10035 GRN_TEXT_INIT(&inspected, 0);
10036 grn_inspect_token_info(ctx, &inspected, info);
10037 printf("%.*s\n", (int)GRN_TEXT_LEN(&inspected), GRN_TEXT_VALUE(&inspected));
10038 GRN_OBJ_FIN(ctx, &inspected);
10039 }
10040
10041 extern "C" void
10042 grn_inspect_token_infos(grn_ctx *ctx,
10043 grn_obj *buffer,
10044 token_info **infos,
10045 uint32_t n)
10046 {
10047 uint32_t i;
10048 for (i = 0; i < n; i++) {
10049 if (i > 0) {
10050 GRN_TEXT_PUTC(ctx, buffer, '\n');
10051 }
10052 grn_text_printf(ctx, buffer, "[%u]\n", i);
10053 grn_inspect_token_info(ctx, buffer, infos[i]);
10054 }
10055 }
10056
10057 extern "C" void
10058 grn_p_token_infos(grn_ctx *ctx, token_info **infos, uint32_t n)
10059 {
10060 grn_obj inspected;
10061 GRN_TEXT_INIT(&inspected, 0);
10062 grn_inspect_token_infos(ctx, &inspected, infos, n);
10063 printf("%.*s\n", (int)GRN_TEXT_LEN(&inspected), GRN_TEXT_VALUE(&inspected));
10064 GRN_OBJ_FIN(ctx, &inspected);
10065 }
10066
10067 #define EX_NONE 0
10068 #define EX_PREFIX 1
10069 #define EX_SUFFIX 2
10070 #define EX_BOTH 3
10071 #define EX_FUZZY 4
10072
10073 struct _btr_node {
10074 struct _btr_node *car;
10075 struct _btr_node *cdr;
10076 token_info *ti;
10077 };
10078
10079 typedef struct _btr_node btr_node;
10080
10081 typedef struct {
10082 int n;
10083 token_info *min;
10084 token_info *max;
10085 btr_node *root;
10086 btr_node *nodes;
10087 uint32_t n_must_lasts;
10088 } btr;
10089
10090 typedef enum {
10091 GRN_WV_NONE = 0,
10092 GRN_WV_STATIC,
10093 GRN_WV_DYNAMIC,
10094 GRN_WV_CONSTANT
10095 } grn_wv_mode;
10096
10097 typedef struct {
10098 uint32_t n_phrases;
10099 btr *btree;
10100 } phrase_group;
10101
10102 typedef struct {
10103 grn_ii *ii;
10104 grn_obj *lexicon;
10105 const char *query;
10106 unsigned int query_len;
10107 grn_hash *result_set;
10108 grn_operator op;
10109 grn_select_optarg *optarg;
10110 grn_operator mode;
10111 grn_wv_mode wv_mode;
10112 grn_scorer_score_func *score_func;
10113 grn_scorer_matched_record record;
10114 grn_id previous_min;
10115 grn_id current_min;
10116 bool set_min_enable_for_and_query;
10117 grn_fuzzy_search_optarg *fuzzy_search_optarg;
10118 grn_obj *query_options;
10119 bool only_skip_token;
10120 token_info **token_infos;
10121 uint32_t n_token_infos;
10122 uint32_t n_phrase_groups;
10123 phrase_group *phrase_groups;
10124 uint32_t n_phrases;
10125 token_info *current_token_info;
10126 btr *bt;
10127 int max_interval;
10128 int additional_last_interval;
10129 grn_obj *max_element_intervals;
10130 int min_interval;
10131 btr *check_element_intervals_btree;
10132 int32_t pos;
10133 grn_id rid;
10134 uint32_t sid;
10135 grn_id next_rid;
10136 uint32_t next_sid;
10137 bool may_match;
10138 int32_t start_pos;
10139 int32_t end_pos;
10140 int32_t total_score;
10141 uint32_t n_occurrences;
10142 } grn_ii_select_data;
10143
10144 static inline grn_token_cursor *
10145 grn_ii_select_data_open_token_cursor(grn_ctx *ctx,
10146 grn_ii_select_data *data,
10147 const char *text,
10148 size_t text_length,
10149 grn_tokenize_mode mode)
10150 {
10151 uint32_t token_flags = GRN_TOKEN_CURSOR_ENABLE_TOKENIZED_DELIMITER;
10152 grn_token_cursor *token_cursor = grn_token_cursor_open(ctx,
10153 data->lexicon,
10154 text,
10155 text_length,
10156 mode,
10157 token_flags);
10158 if (!token_cursor) {
10159 return NULL;
10160 }
10161 if (data->query_options) {
10162 grn_token_cursor_set_query_options(ctx, token_cursor, data->query_options);
10163 if (ctx->rc != GRN_SUCCESS) {
10164 grn_token_cursor_close(ctx, token_cursor);
10165 return NULL;
10166 }
10167 }
10168 if (data->optarg->query_domain != GRN_ID_NIL) {
10169 grn_token_cursor_set_query_domain(ctx,
10170 token_cursor,
10171 data->optarg->query_domain);
10172 }
10173 return token_cursor;
10174 }
10175
10176 static inline void
10177 token_info_expand_both(grn_ctx *ctx,
10178 grn_ii_select_data *data,
10179 const char *key,
10180 unsigned int key_size,
10181 token_info *ti)
10182 {
10183 int s = 0;
10184 grn_hash *h, *g;
10185 uint32_t *offset2;
10186 grn_hash_cursor *c;
10187 grn_id *tp, *tq;
10188 if ((h = grn_hash_create(ctx, NULL, sizeof(grn_id), 0, 0))) {
10189 grn_operator mode = GRN_OP_PREFIX;
10190 if (data->lexicon->header.type == GRN_TABLE_HASH_KEY) {
10191 mode = GRN_OP_EXACT;
10192 }
10193 /* TODO: use cursor like EX_PREFIX */
10194 grn_table_search(ctx,
10195 data->lexicon,
10196 key,
10197 key_size,
10198 mode,
10199 (grn_obj *)h,
10200 GRN_OP_OR);
10201 if (GRN_HASH_SIZE(h)) {
10202 if ((ti->cursors = cursor_heap_open(ctx, GRN_HASH_SIZE(h) + 256))) {
10203 if ((c = grn_hash_cursor_open(ctx, h, NULL, 0, NULL, 0, 0, -1, 0))) {
10204 uint32_t key2_size;
10205 const char *key2;
10206 while (grn_hash_cursor_next(ctx, c)) {
10207 grn_hash_cursor_get_key(ctx, c, (void **)&tp);
10208 key2 = _grn_table_key(ctx, data->lexicon, *tp, &key2_size);
10209 if (!key2) {
10210 break;
10211 }
10212 if ((data->lexicon->header.type != GRN_TABLE_PAT_KEY) ||
10213 !(data->lexicon->header.flags & GRN_OBJ_KEY_WITH_SIS) ||
10214 key2_size <= 2) { // todo: refine
10215 if ((s = grn_ii_estimate_size(ctx, data->ii, *tp))) {
10216 cursor_heap_push(ctx,
10217 ti->cursors,
10218 data->ii,
10219 *tp,
10220 0,
10221 0,
10222 data->previous_min);
10223 ti->ntoken++;
10224 ti->size += s;
10225 }
10226 } else {
10227 if ((g = grn_hash_create(ctx,
10228 NULL,
10229 sizeof(grn_id),
10230 0,
10231 GRN_HASH_TINY))) {
10232 /* TODO: use cursor like EX_PREFIX */
10233 grn_pat_suffix_search(ctx,
10234 (grn_pat *)(data->lexicon),
10235 key2,
10236 key2_size,
10237 g);
10238 GRN_HASH_EACH(ctx, g, id, &tq, NULL, &offset2, {
10239 if ((s = grn_ii_estimate_size(ctx, data->ii, *tq))) {
10240 cursor_heap_push(ctx,
10241 ti->cursors,
10242 data->ii,
10243 *tq,
10244 /* *offset2 */ 0,
10245 0,
10246 data->previous_min);
10247 ti->ntoken++;
10248 ti->size += s;
10249 }
10250 });
10251 grn_hash_close(ctx, g);
10252 }
10253 }
10254 }
10255 grn_hash_cursor_close(ctx, c);
10256 }
10257 }
10258 }
10259 grn_hash_close(ctx, h);
10260 }
10261 }
10262
10263 static inline grn_rc
10264 token_info_close(grn_ctx *ctx, token_info *ti)
10265 {
10266 cursor_heap_close(ctx, ti->cursors);
10267 GRN_FREE(ti);
10268 return GRN_SUCCESS;
10269 }
10270
10271 /*
10272 * If tid is GRN_ID_NIL, caller must specify valid key and key_size
10273 * (not NULL and 0). tid may be retrieved by grn_table_get(ctx,
10274 * data->lexicon, key, key_size) if tid is needed and tid is GRN_ID_NIL.
10275 *
10276 * If key is NULL, caller must specify valid tid (not GRN_ID_NIL). key
10277 * and key_size may be retrieved by _grn_table_key(ctx, data->lexicon,
10278 * tid, &key_size) if key is needed and key is NULL.
10279 *
10280 * Note that we should not normalize the input multiple times. Some
10281 * normalizers such as NormalizerTable aren't idempotent. If we
10282 * normalize the input multipe times with a non-idempotent normalizer,
10283 * the tokenized result is broken.
10284 */
10285 static inline token_info *
10286 token_info_open(grn_ctx *ctx,
10287 grn_ii_select_data *data,
10288 grn_id tid,
10289 const char *key,
10290 unsigned int key_size,
10291 uint32_t offset,
10292 int mode)
10293 {
10294 uint32_t s = 0;
10295 grn_hash *h;
10296 grn_id *tp;
10297 if (tid == GRN_ID_NIL && !key) {
10298 return NULL;
10299 }
10300 auto ti = static_cast<token_info *>(GRN_CALLOC(sizeof(token_info)));
10301 if (!ti) {
10302 return NULL;
10303 }
10304 ti->cursors = NULL;
10305 ti->size = 0;
10306 ti->ntoken = 0;
10307 ti->offset = offset;
10308 ti->phrase_id = 0;
10309 ti->must_last = false;
10310 switch (mode) {
10311 case EX_BOTH:
10312 if (!key) {
10313 key = _grn_table_key(ctx, data->lexicon, tid, &key_size);
10314 }
10315 token_info_expand_both(ctx, data, key, key_size, ti);
10316 break;
10317 case EX_NONE:
10318 if (tid == GRN_ID_NIL) {
10319 tid = grn_table_get(ctx, data->lexicon, key, key_size);
10320 }
10321 if (tid != GRN_ID_NIL && (s = grn_ii_estimate_size(ctx, data->ii, tid)) &&
10322 (ti->cursors = cursor_heap_open(ctx, 1))) {
10323 cursor_heap_push(ctx,
10324 ti->cursors,
10325 data->ii,
10326 tid,
10327 0,
10328 0,
10329 data->previous_min);
10330 ti->ntoken++;
10331 ti->size = s;
10332 }
10333 break;
10334 case EX_PREFIX:
10335 if (data->lexicon->header.type == GRN_TABLE_HASH_KEY) {
10336 if (tid == GRN_ID_NIL) {
10337 tid = grn_table_get(ctx, data->lexicon, key, key_size);
10338 }
10339 if (tid != GRN_ID_NIL) {
10340 ti->cursors = cursor_heap_open(ctx, 1);
10341 /* TODO: report error on !ti->cursors */
10342 if (ti->cursors) {
10343 s = grn_ii_estimate_size(ctx, data->ii, tid);
10344 if (s > 0) {
10345 cursor_heap_push(ctx,
10346 ti->cursors,
10347 data->ii,
10348 tid,
10349 0,
10350 0,
10351 data->previous_min);
10352 ti->ntoken++;
10353 ti->size += s;
10354 }
10355 }
10356 }
10357 } else {
10358 if (!key) {
10359 key = _grn_table_key(ctx, data->lexicon, tid, &key_size);
10360 }
10361 GRN_TABLE_EACH_BEGIN_MIN(ctx,
10362 data->lexicon,
10363 cursor,
10364 id,
10365 key,
10366 key_size,
10367 GRN_CURSOR_PREFIX)
10368 {
10369 if (!ti->cursors) {
10370 /* This is heuristic. 0.1% tokens may be matched. Must be
10371 * greater than 0. */
10372 unsigned int initial_capacity =
10373 (grn_table_size(ctx, data->lexicon) / 1000) + 1;
10374 ti->cursors = cursor_heap_open(ctx, initial_capacity);
10375 if (!ti->cursors) {
10376 /* TODO: report error */
10377 break;
10378 }
10379 }
10380 s = grn_ii_estimate_size(ctx, data->ii, id);
10381 if (s > 0) {
10382 cursor_heap_push(ctx,
10383 ti->cursors,
10384 data->ii,
10385 id,
10386 0,
10387 0,
10388 data->previous_min);
10389 ti->ntoken++;
10390 ti->size += s;
10391 }
10392 }
10393 GRN_TABLE_EACH_END(ctx, cursor);
10394 }
10395 break;
10396 case EX_SUFFIX:
10397 if ((h = grn_hash_create(ctx, NULL, sizeof(grn_id), 0, 0))) {
10398 grn_operator mode = GRN_OP_SUFFIX;
10399 if (data->lexicon->header.type == GRN_TABLE_HASH_KEY) {
10400 mode = GRN_OP_EXACT;
10401 }
10402 if (!key) {
10403 key = _grn_table_key(ctx, data->lexicon, tid, &key_size);
10404 }
10405 /* TODO: use cursor like EX_PREFIX */
10406 grn_table_search(ctx,
10407 data->lexicon,
10408 key,
10409 key_size,
10410 mode,
10411 (grn_obj *)h,
10412 GRN_OP_OR);
10413 if (GRN_HASH_SIZE(h)) {
10414 if ((ti->cursors = cursor_heap_open(ctx, GRN_HASH_SIZE(h)))) {
10415 uint32_t *offset2;
10416 GRN_HASH_EACH(ctx, h, id, &tp, NULL, &offset2, {
10417 if ((s = grn_ii_estimate_size(ctx, data->ii, *tp))) {
10418 cursor_heap_push(ctx,
10419 ti->cursors,
10420 data->ii,
10421 *tp,
10422 /* *offset2 */ 0,
10423 0,
10424 data->previous_min);
10425 ti->ntoken++;
10426 ti->size += s;
10427 }
10428 });
10429 }
10430 }
10431 grn_hash_close(ctx, h);
10432 }
10433 break;
10434 case EX_FUZZY:
10435 if ((h = (grn_hash *)grn_table_create(ctx,
10436 NULL,
10437 0,
10438 NULL,
10439 GRN_OBJ_TABLE_HASH_KEY |
10440 GRN_OBJ_WITH_SUBREC,
10441 grn_ctx_at(ctx, GRN_DB_UINT32),
10442 NULL))) {
10443 if (!key) {
10444 key = _grn_table_key(ctx, data->lexicon, tid, &key_size);
10445 }
10446 grn_ctx_trace_log_emit_string(ctx,
10447 "ii.select.fuzzy.input",
10448 key,
10449 key_size);
10450 /* TODO: use cursor like EX_PREFIX */
10451 grn_table_fuzzy_search(ctx,
10452 data->lexicon,
10453 key,
10454 key_size,
10455 data->fuzzy_search_optarg,
10456 (grn_obj *)h,
10457 GRN_OP_OR);
10458 if (GRN_HASH_SIZE(h)) {
10459 if ((ti->cursors = cursor_heap_open(ctx, GRN_HASH_SIZE(h)))) {
10460 grn_rset_recinfo *ri;
10461 GRN_HASH_EACH(ctx, h, id, &tp, NULL, (void **)&ri, {
10462 if ((s = grn_ii_estimate_size(ctx, data->ii, *tp))) {
10463 cursor_heap_push(ctx,
10464 ti->cursors,
10465 data->ii,
10466 *tp,
10467 0,
10468 (int)(ri->score - 1),
10469 data->previous_min);
10470 ti->ntoken++;
10471 ti->size += s;
10472 grn_ctx_trace_log_emit_record_key(ctx,
10473 "ii.select.fuzzy.input.actual",
10474 data->ii->lexicon,
10475 *tp);
10476 }
10477 });
10478 }
10479 }
10480 grn_obj_close(ctx, (grn_obj *)h);
10481 }
10482 break;
10483 }
10484 if (ctx->rc != GRN_SUCCESS) {
10485 token_info_close(ctx, ti);
10486 return NULL;
10487 }
10488 if (cursor_heap_push2(ti->cursors)) {
10489 token_info_close(ctx, ti);
10490 return NULL;
10491 }
10492 {
10493 grn_ii_cursor *ic;
10494 if (ti->cursors && (ic = cursor_heap_min(ti->cursors))) {
10495 grn_posting *p = ic->post;
10496 ti->pos = p->pos - ti->offset;
10497 ti->p = p;
10498 } else {
10499 token_info_close(ctx, ti);
10500 ti = NULL;
10501 }
10502 }
10503 return ti;
10504 }
10505
10506 static inline grn_rc
10507 token_info_skip(grn_ctx *ctx, token_info *ti, uint32_t rid, uint32_t sid)
10508 {
10509 grn_ii_cursor *c;
10510 grn_posting *p;
10511 for (;;) {
10512 if (!(c = cursor_heap_min(ti->cursors))) {
10513 return GRN_END_OF_DATA;
10514 }
10515 p = c->post;
10516 if (p->rid > rid || (p->rid == rid && p->sid >= sid)) {
10517 break;
10518 }
10519 cursor_heap_pop(ctx, ti->cursors, rid);
10520 }
10521 ti->pos = p->pos - ti->offset;
10522 ti->p = p;
10523 return GRN_SUCCESS;
10524 }
10525
10526 static inline grn_rc
10527 token_info_skip_pos(
10528 grn_ctx *ctx, token_info *ti, uint32_t rid, uint32_t sid, int32_t pos)
10529 {
10530 grn_ii_cursor *c;
10531 grn_posting *p;
10532 pos += ti->offset;
10533 for (;;) {
10534 if (!(c = cursor_heap_min(ti->cursors))) {
10535 return GRN_END_OF_DATA;
10536 }
10537 p = c->post;
10538 if (p->rid != rid || p->sid != sid || (int32_t)(p->pos) >= pos) {
10539 break;
10540 }
10541 cursor_heap_pop_pos(ctx, ti->cursors);
10542 }
10543 ti->pos = p->pos - ti->offset;
10544 ti->p = p;
10545 return GRN_SUCCESS;
10546 }
10547
10548 static inline int
10549 token_compare(const void *a, const void *b)
10550 {
10551 const token_info *t1 = *((token_info **)a), *t2 = *((token_info **)b);
10552 if (t1->phrase_group_id == t2->phrase_group_id) {
10553 if (t1->phrase_id == t2->phrase_id) {
10554 return t1->size - t2->size;
10555 } else {
10556 return t1->phrase_id - t2->phrase_id;
10557 }
10558 } else {
10559 return t1->phrase_group_id - t2->phrase_group_id;
10560 }
10561 }
10562
10563 #define TOKEN_CANDIDATE_NODE_SIZE 32
10564 #define TOKEN_CANDIDATE_ADJACENT_MAX_SIZE 16
10565 #define TOKEN_CANDIDATE_QUEUE_SIZE 64
10566 #define TOKEN_CANDIDATE_SIZE 16
10567
10568 typedef struct {
10569 grn_id tid;
10570 const unsigned char *token;
10571 uint32_t token_size;
10572 const unsigned char *source_token;
10573 uint32_t source_token_size;
10574 int32_t pos;
10575 grn_token_cursor_status status;
10576 int ef;
10577 uint32_t estimated_size;
10578 uint8_t adjacent[TOKEN_CANDIDATE_ADJACENT_MAX_SIZE]; /* Index of adjacent node
10579 from top */
10580 uint8_t n_adjacent;
10581 } token_candidate_node;
10582
10583 typedef struct {
10584 uint32_t
10585 *candidates; /* Standing bits indicate index of token_candidate_node */
10586 int top;
10587 int rear;
10588 int size;
10589 } token_candidate_queue;
10590
10591 typedef struct {
10592 grn_ii_select_data *select_data;
10593 token_candidate_node *nodes;
10594 uint32_t n_nodes;
10595 uint32_t max_estimated_size;
10596 uint32_t selected_candidate;
10597 } token_candidate_data;
10598
10599 static inline void
10600 token_candidate_adjacent_set(grn_ctx *ctx,
10601 grn_token_cursor *token_cursor,
10602 token_candidate_node *top,
10603 token_candidate_node *curr)
10604 {
10605 bool exists_adjacent = false;
10606 token_candidate_node *adj;
10607 for (adj = top; adj < curr; adj++) {
10608 if (token_cursor->curr <= adj->token + adj->token_size) {
10609 if (adj->n_adjacent < TOKEN_CANDIDATE_ADJACENT_MAX_SIZE) {
10610 adj->adjacent[adj->n_adjacent] = curr - top;
10611 adj->n_adjacent++;
10612 exists_adjacent = true;
10613 }
10614 }
10615 }
10616 if (!exists_adjacent) {
10617 adj = curr - 1;
10618 if (adj->n_adjacent < TOKEN_CANDIDATE_ADJACENT_MAX_SIZE) {
10619 adj->adjacent[adj->n_adjacent] = curr - top;
10620 adj->n_adjacent++;
10621 }
10622 }
10623 }
10624
10625 static inline grn_rc
10626 token_candidate_init(grn_ctx *ctx,
10627 token_candidate_data *data,
10628 grn_ii_select_data *select_data,
10629 grn_token_cursor *token_cursor,
10630 grn_id tid,
10631 int ef)
10632 {
10633 data->select_data = select_data;
10634 size_t size = TOKEN_CANDIDATE_NODE_SIZE;
10635 data->nodes = static_cast<token_candidate_node *>(
10636 GRN_MALLOC(TOKEN_CANDIDATE_NODE_SIZE * sizeof(token_candidate_node)));
10637 if (!data->nodes) {
10638 return GRN_NO_MEMORY_AVAILABLE;
10639 }
10640
10641 token_candidate_node *top = data->nodes;
10642 token_candidate_node *curr = top;
10643
10644 #define TOKEN_CANDIDATE_NODE_SET() \
10645 { \
10646 grn_token *token = grn_token_cursor_get_token(ctx, token_cursor); \
10647 curr->tid = tid; \
10648 curr->token = token_cursor->curr; \
10649 curr->token_size = token_cursor->curr_size; \
10650 curr->source_token_size = grn_token_get_source_length(ctx, token); \
10651 if (curr->source_token_size > 0) { \
10652 curr->source_token = NULL; \
10653 } else { \
10654 curr->source_token = \
10655 token_cursor->orig + grn_token_get_source_offset(ctx, token); \
10656 } \
10657 curr->pos = token_cursor->pos; \
10658 curr->status = token_cursor->status; \
10659 curr->ef = ef; \
10660 curr->estimated_size = grn_ii_estimate_size(ctx, select_data->ii, tid); \
10661 curr->n_adjacent = 0; \
10662 }
10663 TOKEN_CANDIDATE_NODE_SET();
10664 GRN_LOG(ctx,
10665 GRN_LOG_DEBUG,
10666 "[ii][overlap_token_skip] tid=%u pos=%d estimated_size=%u",
10667 curr->tid,
10668 curr->pos,
10669 curr->estimated_size);
10670 data->max_estimated_size = curr->estimated_size;
10671 curr++;
10672
10673 while (token_cursor->status == GRN_TOKEN_CURSOR_DOING) {
10674 if ((size_t)(curr - top) >= size) {
10675 auto nodes = static_cast<token_candidate_node *>(
10676 GRN_REALLOC(data->nodes,
10677 (curr - top + TOKEN_CANDIDATE_NODE_SIZE) *
10678 sizeof(token_candidate_node)));
10679 if (!nodes) {
10680 GRN_FREE(data->nodes);
10681 data->nodes = NULL;
10682 return GRN_NO_MEMORY_AVAILABLE;
10683 }
10684 top = data->nodes;
10685 curr = top + size;
10686 size += TOKEN_CANDIDATE_NODE_SIZE;
10687 }
10688 tid = grn_token_cursor_next(ctx, token_cursor);
10689 if (token_cursor->status != GRN_TOKEN_CURSOR_DONE_SKIP) {
10690 grn_token *token;
10691 token = grn_token_cursor_get_token(ctx, token_cursor);
10692 if (grn_token_get_force_prefix_search(ctx, token)) {
10693 ef |= EX_PREFIX;
10694 }
10695 TOKEN_CANDIDATE_NODE_SET();
10696 token_candidate_adjacent_set(ctx, token_cursor, top, curr);
10697 if (curr->estimated_size > data->max_estimated_size) {
10698 data->max_estimated_size = curr->estimated_size;
10699 }
10700 curr++;
10701 }
10702 }
10703 data->n_nodes = curr - top;
10704 return GRN_SUCCESS;
10705 #undef TOKEN_CANDIDATE_NODE_SET
10706 }
10707
10708 static inline grn_rc
10709 token_candidate_queue_init(grn_ctx *ctx, token_candidate_queue *q)
10710 {
10711 q->top = 0;
10712 q->rear = 0;
10713 q->size = TOKEN_CANDIDATE_QUEUE_SIZE;
10714
10715 q->candidates = static_cast<uint32_t *>(
10716 GRN_MALLOC(TOKEN_CANDIDATE_QUEUE_SIZE * sizeof(uint32_t)));
10717 if (!q->candidates) {
10718 q->size = 0;
10719 return GRN_NO_MEMORY_AVAILABLE;
10720 }
10721 return GRN_SUCCESS;
10722 }
10723
10724 static inline grn_rc
10725 token_candidate_enqueue(grn_ctx *ctx,
10726 token_candidate_queue *q,
10727 uint32_t candidate)
10728 {
10729 if (q->rear >= q->size) {
10730 if (!(q->candidates = static_cast<uint32_t *>(GRN_REALLOC(
10731 q->candidates,
10732 (q->rear + TOKEN_CANDIDATE_QUEUE_SIZE) * sizeof(uint32_t))))) {
10733 q->size = 0;
10734 return GRN_NO_MEMORY_AVAILABLE;
10735 }
10736 q->size += TOKEN_CANDIDATE_QUEUE_SIZE;
10737 }
10738 *(q->candidates + q->rear) = candidate;
10739 q->rear++;
10740 return GRN_SUCCESS;
10741 }
10742
10743 static inline grn_rc
10744 token_candidate_dequeue(grn_ctx *ctx,
10745 token_candidate_queue *q,
10746 uint32_t *candidate)
10747 {
10748 if (q->top == q->rear) {
10749 return GRN_END_OF_DATA;
10750 }
10751 *candidate = *(q->candidates + q->top);
10752 q->top++;
10753 return GRN_SUCCESS;
10754 }
10755
10756 static inline void
10757 token_candidate_queue_fin(grn_ctx *ctx, token_candidate_queue *q)
10758 {
10759 GRN_FREE(q->candidates);
10760 }
10761
10762 static inline token_candidate_node *
10763 token_candidate_last_node(grn_ctx *ctx,
10764 token_candidate_data *data,
10765 uint32_t candidate,
10766 int offset)
10767 {
10768 grn_bit_scan_rev_result i;
10769 GRN_BIT_SCAN_REV(candidate, i);
10770 return data->nodes + i + offset;
10771 }
10772
10773 static inline uint64_t
10774 token_candidate_score(grn_ctx *ctx,
10775 token_candidate_data *data,
10776 uint32_t candidate,
10777 int offset)
10778 {
10779 grn_bit_scan_rev_result i, last;
10780 uint64_t score = 0;
10781 GRN_BIT_SCAN_REV(candidate, last);
10782 for (i = 0; i <= last; i++) {
10783 if (candidate & (1 << i)) {
10784 token_candidate_node *node = data->nodes + i + offset;
10785 if (node->estimated_size > 0) {
10786 score += data->max_estimated_size / node->estimated_size;
10787 }
10788 }
10789 }
10790 return score;
10791 }
10792
10793 static inline grn_rc
10794 token_candidate_select(grn_ctx *ctx,
10795 token_candidate_data *data,
10796 uint32_t offset,
10797 uint32_t limit)
10798 {
10799 if (offset + limit > (data->n_nodes - 1)) {
10800 limit = (data->n_nodes - 1) - offset;
10801 }
10802 token_candidate_queue q;
10803 grn_rc rc = token_candidate_queue_init(ctx, &q);
10804 if (rc != GRN_SUCCESS) {
10805 return rc;
10806 }
10807 uint32_t candidate;
10808 uint64_t max_score = 0;
10809 uint32_t min_n_nodes = 0;
10810 rc = token_candidate_enqueue(ctx, &q, 1);
10811 if (rc != GRN_SUCCESS) {
10812 goto exit;
10813 }
10814 while (token_candidate_dequeue(ctx, &q, &candidate) != GRN_END_OF_DATA) {
10815 token_candidate_node *candidate_last_node =
10816 token_candidate_last_node(ctx, data, candidate, offset);
10817 int i;
10818 for (i = 0; i < candidate_last_node->n_adjacent; i++) {
10819 uint32_t adjacent;
10820 uint32_t new_candidate;
10821 uint32_t n_nodes = 0;
10822 adjacent = candidate_last_node->adjacent[i] - offset;
10823 if (adjacent > limit) {
10824 break;
10825 }
10826 new_candidate = candidate | (1 << adjacent);
10827 GET_NUM_BITS(new_candidate, n_nodes);
10828 if (min_n_nodes > 0 && n_nodes > min_n_nodes + 1) {
10829 goto exit;
10830 }
10831 rc = token_candidate_enqueue(ctx, &q, new_candidate);
10832 if (rc != GRN_SUCCESS) {
10833 goto exit;
10834 }
10835 if (adjacent == limit) {
10836 if (min_n_nodes == 0) {
10837 min_n_nodes = n_nodes;
10838 }
10839 if (min_n_nodes <= n_nodes && n_nodes <= min_n_nodes + 1) {
10840 uint64_t score =
10841 token_candidate_score(ctx, data, new_candidate, offset);
10842 if (score > max_score) {
10843 max_score = score;
10844 data->selected_candidate = new_candidate;
10845 }
10846 }
10847 }
10848 }
10849 }
10850 rc = GRN_SUCCESS;
10851 exit:
10852 token_candidate_queue_fin(ctx, &q);
10853 return rc;
10854 }
10855
10856 static inline grn_rc
10857 token_candidate_build(grn_ctx *ctx, token_candidate_data *data, int offset)
10858 {
10859 grn_rc rc = GRN_END_OF_DATA;
10860 grn_bit_scan_rev_result last = 0;
10861 GRN_BIT_SCAN_REV(data->selected_candidate, last);
10862 grn_bit_scan_rev_result i;
10863 for (i = 1; i <= last; i++) {
10864 if (data->selected_candidate & (1 << i)) {
10865 token_info *ti;
10866 token_candidate_node *node = data->nodes + i + offset;
10867 switch (node->status) {
10868 case GRN_TOKEN_CURSOR_DOING:
10869 ti = token_info_open(ctx,
10870 data->select_data,
10871 node->tid,
10872 reinterpret_cast<const char *>(node->source_token),
10873 node->source_token_size,
10874 node->pos,
10875 EX_NONE);
10876 break;
10877 case GRN_TOKEN_CURSOR_DONE:
10878 if (node->tid != GRN_ID_NIL) {
10879 ti =
10880 token_info_open(ctx,
10881 data->select_data,
10882 node->tid,
10883 reinterpret_cast<const char *>(node->source_token),
10884 node->source_token_size,
10885 node->pos,
10886 node->ef & EX_PREFIX);
10887 break;
10888 } /* else fallthru */
10889 default:
10890 ti = token_info_open(ctx,
10891 data->select_data,
10892 node->tid,
10893 (const char *)(node->token),
10894 node->token_size,
10895 node->pos,
10896 node->ef & EX_PREFIX);
10897 break;
10898 }
10899 if (!ti) {
10900 goto exit;
10901 }
10902 data->select_data->token_infos[data->select_data->n_token_infos++] = ti;
10903 GRN_LOG(ctx,
10904 GRN_LOG_DEBUG,
10905 "[ii][overlap_token_skip] tid=%u pos=%d estimated_size=%u",
10906 node->tid,
10907 node->pos,
10908 node->estimated_size);
10909 }
10910 }
10911 rc = GRN_SUCCESS;
10912 exit:
10913 return rc;
10914 }
10915
10916 static inline grn_rc
10917 token_info_build_skipping_overlap(grn_ctx *ctx,
10918 grn_ii_select_data *select_data,
10919 grn_token_cursor *token_cursor,
10920 grn_id tid,
10921 int ef)
10922 {
10923 token_candidate_data data;
10924 grn_rc rc =
10925 token_candidate_init(ctx, &data, select_data, token_cursor, tid, ef);
10926 if (rc != GRN_SUCCESS) {
10927 return rc;
10928 }
10929
10930 uint32_t offset = 0;
10931 uint32_t limit = TOKEN_CANDIDATE_SIZE - 1;
10932 while (offset < data.n_nodes - 1) {
10933 data.selected_candidate = 0;
10934 rc = token_candidate_select(ctx, &data, offset, limit);
10935 if (rc != GRN_SUCCESS) {
10936 goto exit;
10937 }
10938 rc = token_candidate_build(ctx, &data, offset);
10939 if (rc != GRN_SUCCESS) {
10940 goto exit;
10941 }
10942 offset += limit;
10943 }
10944 rc = GRN_SUCCESS;
10945 exit:
10946 if (data.nodes) {
10947 GRN_FREE(data.nodes);
10948 }
10949 return rc;
10950 }
10951
10952 static inline grn_rc
10953 token_info_build_phrase(grn_ctx *ctx,
10954 grn_ii_select_data *data,
10955 const char *phrase,
10956 unsigned int phrase_len)
10957 {
10958 token_info *ti;
10959 grn_rc rc = GRN_END_OF_DATA;
10960 grn_token_cursor *token_cursor =
10961 grn_ii_select_data_open_token_cursor(ctx,
10962 data,
10963 phrase,
10964 phrase_len,
10965 GRN_TOKENIZE_GET);
10966 if (!token_cursor) {
10967 return ctx->rc;
10968 }
10969 if (data->mode == GRN_OP_UNSPLIT) {
10970 if ((ti = token_info_open(ctx,
10971 data,
10972 GRN_ID_NIL,
10973 (char *)token_cursor->orig,
10974 token_cursor->orig_blen,
10975 0,
10976 EX_BOTH))) {
10977 data->token_infos[data->n_token_infos++] = ti;
10978 rc = GRN_SUCCESS;
10979 }
10980 } else {
10981 grn_id tid;
10982 int default_ef = EX_NONE;
10983 grn_token *token;
10984 switch (data->mode) {
10985 case GRN_OP_PREFIX:
10986 default_ef = EX_PREFIX;
10987 break;
10988 case GRN_OP_SUFFIX:
10989 default_ef = EX_SUFFIX;
10990 break;
10991 case GRN_OP_PARTIAL:
10992 default_ef = EX_BOTH;
10993 break;
10994 default:
10995 default_ef = EX_NONE;
10996 break;
10997 }
10998 tid = grn_token_cursor_next(ctx, token_cursor);
10999 if (ctx->rc != GRN_SUCCESS) {
11000 rc = ctx->rc;
11001 goto exit;
11002 }
11003 token = grn_token_cursor_get_token(ctx, token_cursor);
11004 const unsigned char *key = NULL;
11005 uint32_t size = 0;
11006 if (tid == GRN_ID_NIL) {
11007 key = token_cursor->orig;
11008 size = token_cursor->orig_blen;
11009 } else {
11010 size = grn_token_get_source_length(ctx, token);
11011 if (size > 0) {
11012 key = token_cursor->orig + grn_token_get_source_offset(ctx, token);
11013 }
11014 }
11015 int ef = default_ef;
11016 if (grn_token_get_force_prefix_search(ctx, token)) {
11017 ef |= EX_PREFIX;
11018 }
11019 switch (token_cursor->status) {
11020 case GRN_TOKEN_CURSOR_DOING:
11021 ti = token_info_open(ctx,
11022 data,
11023 tid,
11024 reinterpret_cast<const char *>(key),
11025 size,
11026 token_cursor->pos,
11027 ef & EX_SUFFIX);
11028 break;
11029 case GRN_TOKEN_CURSOR_DONE:
11030 case GRN_TOKEN_CURSOR_NOT_FOUND:
11031 ti = token_info_open(ctx,
11032 data,
11033 tid,
11034 reinterpret_cast<const char *>(key),
11035 size,
11036 0,
11037 ef);
11038 break;
11039 case GRN_TOKEN_CURSOR_DONE_SKIP:
11040 data->only_skip_token = true;
11041 goto exit;
11042 default:
11043 goto exit;
11044 }
11045 if (!ti) {
11046 goto exit;
11047 }
11048 data->token_infos[data->n_token_infos++] = ti;
11049
11050 if (grn_ii_overlap_token_skip_enable) {
11051 rc = token_info_build_skipping_overlap(ctx, data, token_cursor, tid, ef);
11052 goto exit;
11053 }
11054
11055 while (token_cursor->status == GRN_TOKEN_CURSOR_DOING) {
11056 grn_token *token;
11057 tid = grn_token_cursor_next(ctx, token_cursor);
11058 token = grn_token_cursor_get_token(ctx, token_cursor);
11059 const unsigned char *key = NULL;
11060 uint32_t size = 0;
11061 if (tid == GRN_ID_NIL) {
11062 key = token_cursor->curr;
11063 size = token_cursor->curr_size;
11064 } else {
11065 size = grn_token_get_source_length(ctx, token);
11066 if (size > 0) {
11067 key = token_cursor->orig + grn_token_get_source_offset(ctx, token);
11068 }
11069 }
11070 ef = default_ef;
11071 if (grn_token_get_force_prefix_search(ctx, token)) {
11072 ef |= EX_PREFIX;
11073 }
11074 switch (token_cursor->status) {
11075 case GRN_TOKEN_CURSOR_DONE_SKIP:
11076 continue;
11077 case GRN_TOKEN_CURSOR_DOING:
11078 ti = token_info_open(ctx,
11079 data,
11080 tid,
11081 reinterpret_cast<const char *>(key),
11082 size,
11083 token_cursor->pos,
11084 EX_NONE);
11085 break;
11086 default:
11087 ti = token_info_open(ctx,
11088 data,
11089 tid,
11090 reinterpret_cast<const char *>(key),
11091 size,
11092 token_cursor->pos,
11093 ef & EX_PREFIX);
11094 break;
11095 }
11096 if (!ti) {
11097 goto exit;
11098 }
11099 data->token_infos[data->n_token_infos++] = ti;
11100 }
11101 rc = GRN_SUCCESS;
11102 }
11103 exit:
11104 grn_token_cursor_close(ctx, token_cursor);
11105 return rc;
11106 }
11107
11108 static inline grn_rc
11109 token_info_build(grn_ctx *ctx, grn_ii_select_data *data)
11110 {
11111 data->only_skip_token = false;
11112 return token_info_build_phrase(ctx, data, data->query, data->query_len);
11113 }
11114
11115 static inline grn_rc
11116 token_info_build_fuzzy(grn_ctx *ctx, grn_ii_select_data *data)
11117 {
11118 token_info *ti;
11119 grn_rc rc = GRN_END_OF_DATA;
11120
11121 if (data->fuzzy_search_optarg->flags & GRN_TABLE_FUZZY_SEARCH_SKIP_TOKENIZE) {
11122 ti = token_info_open(ctx,
11123 data,
11124 GRN_ID_NIL,
11125 data->query,
11126 data->query_len,
11127 1,
11128 EX_FUZZY);
11129 if (!ti) {
11130 return rc;
11131 }
11132 data->token_infos[data->n_token_infos++] = ti;
11133 return GRN_SUCCESS;
11134 }
11135
11136 grn_token_cursor *token_cursor =
11137 grn_ii_select_data_open_token_cursor(ctx,
11138 data,
11139 data->query,
11140 data->query_len,
11141 GRN_TOKENIZE_ONLY);
11142 data->only_skip_token = false;
11143 if (!token_cursor) {
11144 return ctx->rc;
11145 }
11146 grn_id tid = grn_token_cursor_next(ctx, token_cursor);
11147 switch (token_cursor->status) {
11148 case GRN_TOKEN_CURSOR_DONE_SKIP:
11149 data->only_skip_token = true;
11150 goto exit;
11151 case GRN_TOKEN_CURSOR_DOING:
11152 case GRN_TOKEN_CURSOR_DONE:
11153 ti = token_info_open(ctx,
11154 data,
11155 tid,
11156 (const char *)token_cursor->curr,
11157 token_cursor->curr_size,
11158 token_cursor->pos,
11159 EX_FUZZY);
11160 break;
11161 default:
11162 ti = NULL;
11163 break;
11164 }
11165 if (!ti) {
11166 goto exit;
11167 }
11168 data->token_infos[data->n_token_infos++] = ti;
11169 while (token_cursor->status == GRN_TOKEN_CURSOR_DOING) {
11170 tid = grn_token_cursor_next(ctx, token_cursor);
11171 const unsigned char *key = NULL;
11172 uint32_t key_size = 0;
11173 if (tid == GRN_ID_NIL) {
11174 key = token_cursor->curr;
11175 key_size = token_cursor->curr_size;
11176 } else {
11177 grn_token *token = grn_token_cursor_get_token(ctx, token_cursor);
11178 key_size = grn_token_get_source_length(ctx, token);
11179 if (key_size > 0) {
11180 key = token_cursor->orig + grn_token_get_source_offset(ctx, token);
11181 }
11182 }
11183 switch (token_cursor->status) {
11184 case GRN_TOKEN_CURSOR_DONE_SKIP:
11185 continue;
11186 case GRN_TOKEN_CURSOR_DOING:
11187 case GRN_TOKEN_CURSOR_DONE:
11188 ti = token_info_open(ctx,
11189 data,
11190 tid,
11191 reinterpret_cast<const char *>(key),
11192 key_size,
11193 token_cursor->pos,
11194 EX_FUZZY);
11195 break;
11196 default:
11197 break;
11198 }
11199 if (!ti) {
11200 goto exit;
11201 }
11202 data->token_infos[data->n_token_infos++] = ti;
11203 }
11204 rc = GRN_SUCCESS;
11205 exit:
11206 grn_token_cursor_close(ctx, token_cursor);
11207 return rc;
11208 }
11209
11210 static inline bool
11211 token_info_build_near_phrase_is_same_phrase(grn_ctx *ctx,
11212 grn_ii_select_data *data,
11213 uint32_t start1,
11214 uint32_t n1,
11215 uint32_t start2,
11216 uint32_t n2)
11217 {
11218 uint32_t i1 = 0;
11219 uint32_t i2 = 0;
11220 while (i1 < n1 && i2 < n2) {
11221 token_info *token_info1 = data->token_infos[start1 + i1];
11222 token_info *token_info2 = data->token_infos[start2 + i2];
11223 if (token_info1->offset != token_info2->offset) {
11224 if (token_info1->offset > token_info2->offset) {
11225 i2++;
11226 } else {
11227 i1++;
11228 }
11229 continue;
11230 }
11231 if (token_info1->must_last != token_info2->must_last) {
11232 return false;
11233 }
11234 cursor_heap *cursors1 = token_info1->cursors;
11235 cursor_heap *cursors2 = token_info2->cursors;
11236 if (cursors1->n_entries != cursors2->n_entries) {
11237 return false;
11238 }
11239 int j;
11240 for (j = 0; j < cursors1->n_entries; j++) {
11241 if (cursors1->bins[j]->id != cursors2->bins[j]->id) {
11242 return false;
11243 }
11244 }
11245 i1++;
11246 i2++;
11247 }
11248 return i1 == n1 && i2 == n2;
11249 }
11250
11251 static inline bool
11252 token_info_build_near_phrase_have_same_phrase(grn_ctx *ctx,
11253 grn_ii_select_data *data,
11254 uint32_t n_token_infos_before,
11255 uint32_t phrase_group_id)
11256 {
11257 uint32_t n_target_tokens = data->n_token_infos - n_token_infos_before;
11258 uint32_t i = 0;
11259 token_info *token_info;
11260 for (i = 0; i < n_token_infos_before;
11261 i += token_info->n_used_tokens_in_phrase) {
11262 token_info = data->token_infos[i];
11263 if (token_info->phrase_group_id != phrase_group_id) {
11264 continue;
11265 }
11266
11267 if (token_info_build_near_phrase_is_same_phrase(
11268 ctx,
11269 data,
11270 i,
11271 token_info->n_used_tokens_in_phrase,
11272 n_token_infos_before,
11273 n_target_tokens)) {
11274 return true;
11275 }
11276 }
11277 return false;
11278 }
11279
11280 static inline grn_rc
11281 token_info_build_near_phrase(grn_ctx *ctx, grn_ii_select_data *data)
11282 {
11283 const char *tag = "[ii][token-info][build]";
11284 grn_rc rc = GRN_SUCCESS;
11285 data->only_skip_token = false;
11286 grn_obj buffer;
11287 GRN_TEXT_INIT(&buffer, 0);
11288 const char *current = data->query;
11289 const char *query_end = current + data->query_len;
11290 const char *last_char = NULL;
11291 int last_char_len = 0;
11292 bool in_paren = false;
11293 uint32_t phrase_group_id = 0;
11294 uint32_t n_phrases_in_group = 0;
11295 bool have_no_phrase_group = false;
11296 uint32_t phrase_id = 0;
11297 const bool is_product_mode =
11298 (data->mode == GRN_OP_NEAR_PHRASE_PRODUCT ||
11299 data->mode == GRN_OP_ORDERED_NEAR_PHRASE_PRODUCT);
11300
11301 if (is_product_mode) {
11302 phrase_group_id--;
11303 }
11304
11305 while (current < query_end) {
11306 int space_char_len = grn_isspace(current, ctx->encoding);
11307 if (space_char_len > 0) {
11308 current += space_char_len;
11309 continue;
11310 }
11311
11312 const char *phrase = NULL;
11313 size_t phrase_len = 0;
11314 bool use_buffer = false;
11315 GRN_BULK_REWIND(&buffer);
11316 bool escaping = false;
11317 int char_len = grn_charlen(ctx, current, query_end);
11318 if (char_len == 0) {
11319 ERR(GRN_INVALID_ARGUMENT,
11320 "%s invalid character: <%0x>: <%.*s>",
11321 tag,
11322 current[0],
11323 (int)(data->query_len),
11324 data->query);
11325 goto exit;
11326 }
11327
11328 if (is_product_mode) {
11329 if (char_len == 1 && current[0] == GRN_QUERY_PARENL) {
11330 if (in_paren) {
11331 ERR(GRN_INVALID_ARGUMENT,
11332 "%s parenthesis must not be nested: <%.*s|%.*s|%.*s>",
11333 tag,
11334 (int)(current - data->query),
11335 data->query,
11336 char_len,
11337 current,
11338 (int)((data->query + data->query_len) - current - char_len),
11339 current + char_len);
11340 goto exit;
11341 }
11342 in_paren = true;
11343 phrase_group_id++;
11344 n_phrases_in_group = 0;
11345 current += char_len;
11346 continue;
11347 } else if (char_len == 1 && current[0] == GRN_QUERY_PARENR) {
11348 if (!in_paren) {
11349 ERR(GRN_INVALID_ARGUMENT,
11350 "%s unbalanced close parenthesis is detected: <%.*s|%.*s|%.*s>",
11351 tag,
11352 (int)(current - data->query),
11353 data->query,
11354 char_len,
11355 current,
11356 (int)((data->query + data->query_len) - current - char_len),
11357 current + char_len);
11358 goto exit;
11359 }
11360 in_paren = false;
11361 current += char_len;
11362 if (n_phrases_in_group == 0) {
11363 have_no_phrase_group = true;
11364 }
11365 continue;
11366 } else {
11367 if (!in_paren) {
11368 ERR(GRN_INVALID_ARGUMENT,
11369 "%s all phrases must be in parenthesis: <%.*s|%.*s|%.*s>",
11370 tag,
11371 (int)(current - data->query),
11372 data->query,
11373 char_len,
11374 current,
11375 (int)((data->query + data->query_len) - current - char_len),
11376 current + char_len);
11377 goto exit;
11378 }
11379 }
11380 }
11381
11382 if (char_len == 1 && current[0] == GRN_QUERY_QUOTEL) {
11383 use_buffer = true;
11384 current += char_len;
11385 while (current < query_end) {
11386 char_len = grn_charlen(ctx, current, query_end);
11387 if (char_len == 0) {
11388 ERR(GRN_INVALID_ARGUMENT,
11389 "%s invalid character: <%0x>: <%.*s>",
11390 tag,
11391 current[0],
11392 (int)(data->query_len),
11393 data->query);
11394 goto exit;
11395 }
11396 if (escaping) {
11397 escaping = false;
11398 last_char = NULL;
11399 last_char_len = 0;
11400 } else {
11401 if (char_len == 1) {
11402 if (current[0] == GRN_QUERY_ESCAPE) {
11403 escaping = true;
11404 current += char_len;
11405 continue;
11406 } else if (current[0] == GRN_QUERY_QUOTER) {
11407 current += char_len;
11408 break;
11409 }
11410 }
11411 last_char = current;
11412 last_char_len = char_len;
11413 }
11414 GRN_TEXT_PUT(ctx, &buffer, current, char_len);
11415 current += char_len;
11416 }
11417 phrase = GRN_TEXT_VALUE(&buffer);
11418 phrase_len = GRN_TEXT_LEN(&buffer);
11419 } else {
11420 phrase = current;
11421 while (current < query_end) {
11422 if (!escaping) {
11423 space_char_len = grn_isspace(current, ctx->encoding);
11424 if (space_char_len > 0) {
11425 break;
11426 }
11427 }
11428 char_len = grn_charlen(ctx, current, query_end);
11429 if (char_len == 0) {
11430 ERR(GRN_INVALID_ARGUMENT,
11431 "%s invalid character: <%0x>: <%.*s>",
11432 tag,
11433 current[0],
11434 (int)(data->query_len),
11435 data->query);
11436 goto exit;
11437 }
11438 if (escaping) {
11439 escaping = false;
11440 last_char = NULL;
11441 last_char_len = 0;
11442 } else {
11443 if (char_len == 1) {
11444 if (current[0] == GRN_QUERY_ESCAPE) {
11445 if (!use_buffer) {
11446 use_buffer = true;
11447 GRN_TEXT_PUT(ctx, &buffer, phrase, current - phrase);
11448 }
11449 current += char_len;
11450 escaping = true;
11451 continue;
11452 } else if (current[0] == GRN_QUERY_QUOTEL) {
11453 break;
11454 } else if (is_product_mode && (current[0] == GRN_QUERY_PARENL ||
11455 current[0] == GRN_QUERY_PARENR)) {
11456 break;
11457 }
11458 }
11459 last_char = current;
11460 last_char_len = char_len;
11461 }
11462 if (use_buffer) {
11463 GRN_TEXT_PUT(ctx, &buffer, current, char_len);
11464 }
11465 current += char_len;
11466 }
11467 if (use_buffer) {
11468 phrase = GRN_TEXT_VALUE(&buffer);
11469 phrase_len = GRN_TEXT_LEN(&buffer);
11470 } else {
11471 phrase_len = current - phrase;
11472 }
11473 }
11474
11475 if (phrase_len == 0) {
11476 continue;
11477 }
11478
11479 bool must_last = false;
11480 if (!(data->mode == GRN_OP_ORDERED_NEAR_PHRASE ||
11481 data->mode == GRN_OP_ORDERED_NEAR_PHRASE_PRODUCT)) {
11482 if (last_char_len == 1 && *last_char == '$') {
11483 phrase_len -= last_char_len;
11484 must_last = true;
11485 }
11486 }
11487
11488 uint32_t n_before = data->n_token_infos;
11489 rc = token_info_build_phrase(ctx, data, phrase, phrase_len);
11490 if (is_product_mode) {
11491 if (!(rc == GRN_SUCCESS || rc == GRN_END_OF_DATA)) {
11492 goto exit;
11493 }
11494 if (rc == GRN_END_OF_DATA ||
11495 token_info_build_near_phrase_have_same_phrase(ctx,
11496 data,
11497 n_before,
11498 phrase_group_id)) {
11499 rc = GRN_SUCCESS;
11500 uint32_t i;
11501 for (i = n_before; i < data->n_token_infos; i++) {
11502 token_info_close(ctx, data->token_infos[i]);
11503 }
11504 data->n_token_infos = n_before;
11505 continue;
11506 }
11507 n_phrases_in_group++;
11508 } else {
11509 if (rc != GRN_SUCCESS) {
11510 goto exit;
11511 }
11512 }
11513 if (data->n_token_infos > n_before) {
11514 data->token_infos[data->n_token_infos - 1]->must_last = must_last;
11515 }
11516 must_last = false;
11517 uint32_t n_tokens_in_phrase = 0;
11518 {
11519 grn_token_cursor *token_cursor =
11520 grn_ii_select_data_open_token_cursor(ctx,
11521 data,
11522 phrase,
11523 phrase_len,
11524 GRN_TOKENIZE_ONLY);
11525 if (token_cursor) {
11526 while (token_cursor->status == GRN_TOKEN_CURSOR_DOING) {
11527 grn_token_cursor_next(ctx, token_cursor);
11528 n_tokens_in_phrase++;
11529 }
11530 grn_token_cursor_close(ctx, token_cursor);
11531 }
11532 }
11533 uint32_t i;
11534 uint32_t n_used_tokens_in_phrase = data->n_token_infos - n_before;
11535 for (i = n_before; i < data->n_token_infos; i++) {
11536 data->token_infos[i]->n_tokens_in_phrase = n_tokens_in_phrase;
11537 data->token_infos[i]->n_used_tokens_in_phrase = n_used_tokens_in_phrase;
11538 data->token_infos[i]->phrase_group_id = phrase_group_id;
11539 data->token_infos[i]->phrase_id = phrase_id;
11540 }
11541 phrase_id++;
11542 }
11543
11544 if (is_product_mode) {
11545 if (in_paren) {
11546 ERR(GRN_INVALID_ARGUMENT, "%s close parenthesis is missing", tag);
11547 goto exit;
11548 }
11549 if (have_no_phrase_group) {
11550 rc = GRN_END_OF_DATA;
11551 goto exit;
11552 }
11553 }
11554
11555 data->n_phrase_groups = phrase_group_id + 1;
11556 data->n_phrases = phrase_id;
11557
11558 if (data->mode == GRN_OP_ORDERED_NEAR_PHRASE) {
11559 if (data->n_token_infos > 0) {
11560 data->token_infos[data->n_token_infos - 1]->must_last = true;
11561 }
11562 }
11563
11564 exit:
11565 if (rc == GRN_SUCCESS && ctx->rc != GRN_SUCCESS) {
11566 rc = ctx->rc;
11567 }
11568 GRN_OBJ_FIN(ctx, &buffer);
11569 return rc;
11570 }
11571
11572 static void
11573 token_info_clear_offset(token_info **tis, uint32_t n)
11574 {
11575 token_info **tie;
11576 for (tie = tis + n; tis < tie; tis++) {
11577 (*tis)->offset = 0;
11578 }
11579 }
11580
11581 static inline void
11582 bt_zap(btr *bt)
11583 {
11584 bt->n = 0;
11585 bt->min = NULL;
11586 bt->max = NULL;
11587 bt->root = NULL;
11588 bt->n_must_lasts = 0;
11589 }
11590
11591 static inline btr *
11592 bt_open(grn_ctx *ctx, int size)
11593 {
11594 auto bt = static_cast<btr *>(GRN_CALLOC(sizeof(btr)));
11595 if (bt) {
11596 bt_zap(bt);
11597 bt->nodes = static_cast<btr_node *>(GRN_MALLOC(sizeof(btr_node) * size));
11598 if (!bt->nodes) {
11599 GRN_FREE(bt);
11600 bt = NULL;
11601 }
11602 }
11603 return bt;
11604 }
11605
11606 static inline void
11607 bt_close(grn_ctx *ctx, btr *bt)
11608 {
11609 if (!bt) {
11610 return;
11611 }
11612 GRN_FREE(bt->nodes);
11613 GRN_FREE(bt);
11614 }
11615
11616 /* Adds a token info to the given tree. btr::min and btr::max are updated
11617 * are updated when the given token info is minimum or maximum token info
11618 * in the given tree. */
11619 static inline void
11620 bt_push(btr *bt, token_info *ti)
11621 {
11622 bool min_p = true;
11623 bool max_p = true;
11624 int32_t pos = ti->pos;
11625 btr_node *node, *new_node, **last;
11626 new_node = bt->nodes + bt->n++;
11627 new_node->ti = ti;
11628 new_node->car = NULL;
11629 new_node->cdr = NULL;
11630 for (last = &bt->root; (node = *last);) {
11631 if (pos < node->ti->pos) {
11632 last = &node->car;
11633 max_p = false;
11634 } else {
11635 last = &node->cdr;
11636 min_p = false;
11637 }
11638 }
11639 *last = new_node;
11640 if (min_p) {
11641 bt->min = ti;
11642 }
11643 if (max_p) {
11644 bt->max = ti;
11645 }
11646 if (ti->must_last) {
11647 bt->n_must_lasts++;
11648 }
11649 }
11650
11651 /* Drops the minimum token info. Note that you can't push a token info to
11652 * this btr after this function is called. */
11653 static inline void
11654 bt_pop(btr *bt)
11655 {
11656 btr_node *min;
11657 btr_node *parent = NULL;
11658 btr_node **last;
11659 for (last = &bt->root; (min = *last) && min->car;
11660 parent = min, last = &min->car) {
11661 }
11662 if (min) {
11663 *last = min->cdr;
11664 if (min->cdr) {
11665 btr_node *new_min;
11666 for (new_min = min->cdr; new_min->car; new_min = new_min->car)
11667 ;
11668 bt->min = new_min->ti;
11669 } else if (parent) {
11670 bt->min = parent->ti;
11671 } else {
11672 bt->min = NULL;
11673 }
11674 if (last == &(bt->root)) {
11675 bt->max = bt->min;
11676 }
11677 min->cdr = NULL;
11678 bt->n--;
11679 if (min->ti->must_last) {
11680 bt->n_must_lasts--;
11681 }
11682 }
11683 }
11684
11685 /* Replace the token info of the minimum node. Note that bt->min may
11686 * not be correct until you call bt_reorder_min(). */
11687 static inline void
11688 bt_replace_min(btr *bt, token_info *ti)
11689 {
11690 btr_node *min, **last;
11691 if (ti->must_last) {
11692 bt->n_must_lasts++;
11693 }
11694 for (last = &bt->root; (min = *last) && min->car; last = &min->car)
11695 ;
11696 if (min) {
11697 if (min->ti->must_last) {
11698 bt->n_must_lasts--;
11699 }
11700 min->ti = ti;
11701 bt->min = ti;
11702 }
11703 }
11704
11705 /* Re-order the minimum token info. The minimum token info must be
11706 * updated before you call this function. */
11707 static inline void
11708 bt_reorder_min(btr *bt)
11709 {
11710 btr_node *node, *min, **last;
11711 for (last = &bt->root; (min = *last) && min->car; last = &min->car)
11712 ;
11713 if (min) {
11714 bool min_p = true;
11715 bool max_p = true;
11716 int32_t pos = min->ti->pos;
11717 *last = min->cdr;
11718 min->cdr = NULL;
11719 for (last = &bt->root; (node = *last);) {
11720 if (pos < node->ti->pos) {
11721 last = &node->car;
11722 max_p = false;
11723 } else {
11724 last = &node->cdr;
11725 min_p = false;
11726 }
11727 }
11728 *last = min;
11729 if (max_p) {
11730 bt->max = min->ti;
11731 }
11732 if (!min_p) {
11733 btr_node *new_min;
11734 for (new_min = bt->root; new_min->car; new_min = new_min->car)
11735 ;
11736 bt->min = new_min->ti;
11737 }
11738 }
11739 }
11740
11741 /* select */
11742
11743 static inline void
11744 grn_rset_add_record(grn_ctx *ctx,
11745 grn_hash *rset,
11746 grn_rset_posinfo *posinfo,
11747 double score,
11748 grn_operator op)
11749 {
11750 grn_id id;
11751 grn_rset_recinfo *recinfo;
11752 switch (op) {
11753 case GRN_OP_OR:
11754 id =
11755 grn_hash_add(ctx, rset, posinfo, rset->key_size, (void **)&recinfo, NULL);
11756 if (id != GRN_ID_NIL) {
11757 if (rset->obj.header.flags & GRN_OBJ_WITH_SUBREC) {
11758 grn_table_add_subrec(ctx, (grn_obj *)rset, recinfo, score, posinfo, 1);
11759 grn_selector_data_current_add_score(ctx,
11760 (grn_obj *)rset,
11761 id,
11762 posinfo->rid,
11763 score);
11764 }
11765 }
11766 break;
11767 case GRN_OP_AND:
11768 id = grn_hash_get(ctx, rset, posinfo, rset->key_size, (void **)&recinfo);
11769 if (id != GRN_ID_NIL) {
11770 if (rset->obj.header.flags & GRN_OBJ_WITH_SUBREC) {
11771 recinfo->n_subrecs |= GRN_RSET_UTIL_BIT;
11772 grn_table_add_subrec(ctx, (grn_obj *)rset, recinfo, score, posinfo, 1);
11773 grn_selector_data_current_add_score(ctx,
11774 (grn_obj *)rset,
11775 id,
11776 posinfo->rid,
11777 score);
11778 }
11779 }
11780 break;
11781 case GRN_OP_AND_NOT:
11782 id = grn_hash_get(ctx, rset, posinfo, rset->key_size, (void **)&recinfo);
11783 if (id != GRN_ID_NIL) {
11784 grn_hash_delete_by_id(ctx, rset, id, NULL);
11785 }
11786 break;
11787 case GRN_OP_ADJUST:
11788 id = grn_hash_get(ctx, rset, posinfo, rset->key_size, (void **)&recinfo);
11789 if (id != GRN_ID_NIL) {
11790 if (rset->obj.header.flags & GRN_OBJ_WITH_SUBREC) {
11791 recinfo->score += score;
11792 grn_selector_data_current_add_score(ctx,
11793 (grn_obj *)rset,
11794 id,
11795 posinfo->rid,
11796 score);
11797 }
11798 }
11799 break;
11800 default:
11801 break;
11802 }
11803 }
11804
11805 /* TODO: It may be better that we record the min ID when add/delete a
11806 * record. */
11807 /* TODO: It may be useful that we just return approximate value. For
11808 * example, we can stop min ID search when we find an ID that is less
11809 * than grn_table_size(ctx, grn_ctx_at(ctx,
11810 * result_set->header.domain))/100. */
11811 extern "C" grn_id
11812 grn_result_set_get_min_id(grn_ctx *ctx, grn_hash *result_set)
11813 {
11814 GRN_API_ENTER;
11815 if (!result_set) {
11816 GRN_API_RETURN(GRN_ID_NIL);
11817 }
11818 if (GRN_HASH_SIZE(result_set) == 0) {
11819 GRN_API_RETURN(GRN_ID_NIL);
11820 }
11821 grn_id min_id = GRN_ID_MAX;
11822 GRN_HASH_EACH_BEGIN(ctx, result_set, cursor, id)
11823 {
11824 void *key;
11825 grn_hash_cursor_get_key(ctx, cursor, &key);
11826 grn_id id = *((grn_id *)key);
11827 if (id < min_id) {
11828 min_id = id;
11829 }
11830 }
11831 GRN_HASH_EACH_END(ctx, cursor);
11832 GRN_API_RETURN(min_id);
11833 }
11834
11835 extern "C" grn_rc
11836 grn_result_set_add_record(grn_ctx *ctx,
11837 grn_hash *result_set,
11838 grn_posting *posting,
11839 grn_operator op)
11840 {
11841 GRN_API_ENTER;
11842 grn_rset_add_record(ctx,
11843 result_set,
11844 (grn_rset_posinfo *)posting,
11845 ((grn_posting_internal *)posting)->weight_float,
11846 op);
11847 GRN_API_RETURN(ctx->rc);
11848 }
11849
11850 extern "C" grn_rc
11851 grn_result_set_add_table(grn_ctx *ctx,
11852 grn_hash *result_set,
11853 grn_obj *table,
11854 double score,
11855 grn_operator op)
11856 {
11857 GRN_API_ENTER;
11858 const int flags = GRN_CURSOR_BY_ID | GRN_CURSOR_ASCENDING;
11859 grn_table_cursor *cursor =
11860 grn_table_cursor_open(ctx, table, NULL, 0, NULL, 0, 0, -1, flags);
11861 if (cursor) {
11862 grn_result_set_add_table_cursor(ctx, result_set, cursor, score, op);
11863 grn_table_cursor_close(ctx, cursor);
11864 }
11865 GRN_API_RETURN(ctx->rc);
11866 }
11867
11868 extern "C" grn_rc
11869 grn_result_set_add_table_cursor(grn_ctx *ctx,
11870 grn_hash *result_set,
11871 grn_table_cursor *cursor,
11872 double score,
11873 grn_operator op)
11874 {
11875 GRN_API_ENTER;
11876 grn_obj *table = grn_table_cursor_table(ctx, cursor);
11877 if (result_set->obj.header.domain != DB_OBJ(table)->id) {
11878 grn_obj result_set_inspected;
11879 grn_obj table_inspected;
11880 GRN_TEXT_INIT(&result_set_inspected, 0);
11881 GRN_TEXT_INIT(&table_inspected, 0);
11882 grn_inspect_limited(ctx, &result_set_inspected, (grn_obj *)result_set);
11883 grn_inspect_limited(ctx, &table_inspected, table);
11884 ERR(GRN_INVALID_ARGUMENT,
11885 "[result-set][add-table-cursor] "
11886 "table must be the domain of the result set: %.*s: %.*s",
11887 (int)GRN_TEXT_LEN(&result_set_inspected),
11888 GRN_TEXT_VALUE(&result_set_inspected),
11889 (int)GRN_TEXT_LEN(&table_inspected),
11890 GRN_TEXT_VALUE(&table_inspected));
11891 GRN_OBJ_FIN(ctx, &result_set_inspected);
11892 GRN_OBJ_FIN(ctx, &table_inspected);
11893 GRN_API_RETURN(ctx->rc);
11894 }
11895
11896 grn_rc rc;
11897 if (op == GRN_OP_OR || op == GRN_OP_AND) {
11898 rc = grn_hash_add_table_cursor(ctx, result_set, cursor, score, op);
11899 } else {
11900 grn_rset_posinfo posinfo = {};
11901 while ((posinfo.rid = grn_table_cursor_next(ctx, cursor))) {
11902 grn_rset_add_record(ctx, result_set, &posinfo, score, op);
11903 if (ctx->rc != GRN_SUCCESS) {
11904 break;
11905 }
11906 }
11907 rc = ctx->rc;
11908 }
11909 GRN_API_RETURN(rc);
11910 }
11911
11912 extern "C" grn_rc
11913 grn_result_set_add_index_cursor(grn_ctx *ctx,
11914 grn_hash *result_set,
11915 grn_obj *cursor,
11916 double additional_score,
11917 double weight,
11918 grn_operator op)
11919 {
11920 GRN_API_ENTER;
11921
11922 grn_obj *index_column = grn_index_cursor_get_index_column(ctx, cursor);
11923 if (result_set->obj.header.domain != DB_OBJ(index_column)->range) {
11924 grn_obj result_set_inspected;
11925 grn_obj index_column_inspected;
11926 GRN_TEXT_INIT(&result_set_inspected, 0);
11927 GRN_TEXT_INIT(&index_column_inspected, 0);
11928 grn_inspect_limited(ctx, &result_set_inspected, (grn_obj *)result_set);
11929 grn_inspect_limited(ctx, &index_column_inspected, index_column);
11930 ERR(GRN_INVALID_ARGUMENT,
11931 "[result-set][add-index-cursor] "
11932 "not an index column for the result set: %.*s: %.*s",
11933 (int)GRN_TEXT_LEN(&result_set_inspected),
11934 GRN_TEXT_VALUE(&result_set_inspected),
11935 (int)GRN_TEXT_LEN(&index_column_inspected),
11936 GRN_TEXT_VALUE(&index_column_inspected));
11937 GRN_OBJ_FIN(ctx, &result_set_inspected);
11938 GRN_OBJ_FIN(ctx, &index_column_inspected);
11939 GRN_API_RETURN(ctx->rc);
11940 }
11941
11942 grn_rc rc;
11943 if (op == GRN_OP_OR || op == GRN_OP_AND) {
11944 rc = grn_hash_add_index_cursor(ctx,
11945 result_set,
11946 cursor,
11947 additional_score,
11948 weight,
11949 op);
11950 } else {
11951 grn_id term_id;
11952 grn_posting *posting;
11953 while ((posting = grn_index_cursor_next(ctx, cursor, &term_id))) {
11954 grn_rset_posinfo posinfo = {
11955 posting->rid,
11956 posting->sid,
11957 posting->pos,
11958 };
11959 grn_posting_internal *posting_internal = (grn_posting_internal *)posting;
11960 double score =
11961 (posting_internal->weight_float + additional_score) * weight;
11962 grn_rset_add_record(ctx, result_set, &posinfo, score, op);
11963 if (ctx->rc != GRN_SUCCESS) {
11964 break;
11965 }
11966 }
11967 rc = ctx->rc;
11968 }
11969 GRN_API_RETURN(rc);
11970 }
11971
11972 extern "C" grn_rc
11973 grn_result_set_add_ii_cursor(grn_ctx *ctx,
11974 grn_hash *result_set,
11975 grn_ii_cursor *cursor,
11976 double additional_score,
11977 double weight,
11978 grn_operator op)
11979 {
11980 GRN_API_ENTER;
11981
11982 grn_obj *index_column = (grn_obj *)(cursor->ii);
11983 if (result_set->obj.header.domain != DB_OBJ(index_column)->range) {
11984 grn_obj result_set_inspected;
11985 grn_obj index_column_inspected;
11986 GRN_TEXT_INIT(&result_set_inspected, 0);
11987 GRN_TEXT_INIT(&index_column_inspected, 0);
11988 grn_inspect_limited(ctx, &result_set_inspected, (grn_obj *)result_set);
11989 grn_inspect_limited(ctx, &index_column_inspected, index_column);
11990 ERR(GRN_INVALID_ARGUMENT,
11991 "[result-set][add-ii-cursor] "
11992 "not an index column for the result set: %.*s: %.*s",
11993 (int)GRN_TEXT_LEN(&result_set_inspected),
11994 GRN_TEXT_VALUE(&result_set_inspected),
11995 (int)GRN_TEXT_LEN(&index_column_inspected),
11996 GRN_TEXT_VALUE(&index_column_inspected));
11997 GRN_OBJ_FIN(ctx, &result_set_inspected);
11998 GRN_OBJ_FIN(ctx, &index_column_inspected);
11999 GRN_API_RETURN(ctx->rc);
12000 }
12001
12002 grn_rc rc;
12003 if (op == GRN_OP_OR || op == GRN_OP_AND) {
12004 rc = grn_hash_add_ii_cursor(ctx,
12005 result_set,
12006 cursor,
12007 additional_score,
12008 weight,
12009 op);
12010 } else {
12011 grn_posting *posting;
12012 while ((posting = grn_ii_cursor_next(ctx, cursor))) {
12013 grn_rset_posinfo posinfo = {
12014 posting->rid,
12015 posting->sid,
12016 posting->pos,
12017 };
12018 grn_posting_internal *posting_internal = (grn_posting_internal *)posting;
12019 double score =
12020 (posting_internal->weight_float + additional_score) * weight;
12021 grn_rset_add_record(ctx, result_set, &posinfo, score, op);
12022 if (ctx->rc != GRN_SUCCESS) {
12023 break;
12024 }
12025 }
12026 rc = ctx->rc;
12027 }
12028 GRN_API_RETURN(rc);
12029 }
12030
12031 extern "C" grn_rc
12032 grn_result_set_add_ii_select_cursor(grn_ctx *ctx,
12033 grn_hash *result_set,
12034 grn_ii_select_cursor *cursor,
12035 grn_operator op)
12036 {
12037 GRN_API_ENTER;
12038
12039 grn_obj *index_column = (grn_obj *)grn_ii_select_cursor_get_ii(ctx, cursor);
12040 if (result_set->obj.header.domain != DB_OBJ(index_column)->range) {
12041 grn_obj result_set_inspected;
12042 grn_obj index_column_inspected;
12043 GRN_TEXT_INIT(&result_set_inspected, 0);
12044 GRN_TEXT_INIT(&index_column_inspected, 0);
12045 grn_inspect_limited(ctx, &result_set_inspected, (grn_obj *)result_set);
12046 grn_inspect_limited(ctx, &index_column_inspected, index_column);
12047 ERR(GRN_INVALID_ARGUMENT,
12048 "[result-set][add-ii-select-cursor] "
12049 "not an index column for the result set: %.*s: %.*s",
12050 (int)GRN_TEXT_LEN(&result_set_inspected),
12051 GRN_TEXT_VALUE(&result_set_inspected),
12052 (int)GRN_TEXT_LEN(&index_column_inspected),
12053 GRN_TEXT_VALUE(&index_column_inspected));
12054 GRN_OBJ_FIN(ctx, &result_set_inspected);
12055 GRN_OBJ_FIN(ctx, &index_column_inspected);
12056 GRN_API_RETURN(ctx->rc);
12057 }
12058
12059 grn_rc rc;
12060 if (op == GRN_OP_OR || op == GRN_OP_AND) {
12061 rc = grn_hash_add_ii_select_cursor(ctx, result_set, cursor, op);
12062 } else {
12063 grn_ii_select_cursor_posting *posting;
12064 while ((posting = grn_ii_select_cursor_next(ctx, cursor))) {
12065 grn_rset_posinfo posinfo = {
12066 posting->rid,
12067 posting->sid,
12068 posting->pos,
12069 };
12070 grn_rset_add_record(ctx, result_set, &posinfo, posting->score, op);
12071 if (ctx->rc != GRN_SUCCESS) {
12072 break;
12073 }
12074 }
12075 rc = ctx->rc;
12076 }
12077 GRN_API_RETURN(rc);
12078 }
12079
12080 extern "C" grn_rc
12081 grn_result_set_copy(grn_ctx *ctx,
12082 grn_hash *result_set,
12083 grn_hash *output_result_set)
12084 {
12085 GRN_API_ENTER;
12086
12087 GRN_HASH_EACH_BEGIN(ctx, result_set, cursor, id)
12088 {
12089 void *key = NULL;
12090 uint32_t key_size = 0;
12091 void *value = NULL;
12092 grn_hash_cursor_get_key_value(ctx, cursor, &key, &key_size, &value);
12093 void *output_value = NULL;
12094 grn_id id = grn_hash_add(ctx,
12095 output_result_set,
12096 key,
12097 (int)key_size,
12098 &output_value,
12099 NULL);
12100 if (id == GRN_ID_NIL) {
12101 if (ctx->rc == GRN_SUCCESS) {
12102 continue;
12103 } else {
12104 break;
12105 }
12106 }
12107 grn_rset_recinfo *ri = static_cast<grn_rset_recinfo *>(value);
12108 grn_rset_recinfo *output_ri = static_cast<grn_rset_recinfo *>(output_value);
12109 grn_memcpy(output_ri, ri, (output_result_set)->value_size);
12110 output_ri->score = 0;
12111 }
12112 GRN_HASH_EACH_END(ctx, cursor);
12113
12114 GRN_API_RETURN(ctx->rc);
12115 }
12116
12117 static inline void
12118 res_add(grn_ctx *ctx,
12119 grn_hash *s,
12120 grn_rset_posinfo *pi,
12121 double score,
12122 grn_operator op)
12123 {
12124 grn_rset_add_record(ctx, s, pi, score, op);
12125 }
12126
12127 extern "C" grn_rc
12128 grn_ii_posting_add(grn_ctx *ctx, grn_posting *pos, grn_hash *s, grn_operator op)
12129 {
12130 grn_rset_add_record(ctx, s, (grn_rset_posinfo *)(pos), pos->weight, op);
12131 return ctx->rc;
12132 }
12133
12134 extern "C" grn_rc
12135 grn_ii_posting_add_float(grn_ctx *ctx,
12136 grn_posting *pos,
12137 grn_hash *s,
12138 grn_operator op)
12139 {
12140 return grn_result_set_add_record(ctx, s, pos, op);
12141 }
12142
12143 static float
12144 get_weight(grn_ctx *ctx, grn_ii_select_data *data)
12145 {
12146 switch (data->wv_mode) {
12147 case GRN_WV_NONE:
12148 return 1;
12149 case GRN_WV_STATIC:
12150 if (data->sid == 0) {
12151 return 0;
12152 } else if (data->sid <= (uint32_t)(data->optarg->vector_size)) {
12153 if (data->optarg->weight_vector) {
12154 return (float)(data->optarg->weight_vector[data->sid - 1]);
12155 } else {
12156 return data->optarg->weight_vector_float[data->sid - 1];
12157 }
12158 } else {
12159 return 0;
12160 }
12161 case GRN_WV_DYNAMIC:
12162 /* todo : support hash with keys
12163 if (s->keys) {
12164 uint32_t key_size;
12165 const char *key = _grn_table_key(ctx, s->keys, rid, &key_size);
12166 // todo : change grn_select_optarg
12167 return key ? optarg->func(s, key, key_size, sid, optarg->func_arg) : 0;
12168 }
12169 */
12170 /* todo : cast */
12171 {
12172 int weight = data->optarg->func(ctx,
12173 data->result_set,
12174 (void *)(intptr_t)(data->rid),
12175 data->sid,
12176 data->optarg->func_arg);
12177 return (float)weight;
12178 }
12179 case GRN_WV_CONSTANT:
12180 if (data->optarg->vector_size < 0) {
12181 return data->optarg->weight_float;
12182 } else {
12183 return (float)(data->optarg->vector_size);
12184 }
12185 default:
12186 return 1;
12187 }
12188 }
12189
12190 static void
12191 grn_ii_select_data_init(grn_ctx *ctx,
12192 grn_ii_select_data *data,
12193 grn_select_optarg *optarg)
12194 {
12195 data->optarg = optarg;
12196 data->mode = GRN_OP_EXACT;
12197 data->wv_mode = GRN_WV_NONE;
12198 data->score_func = NULL;
12199 data->previous_min = GRN_ID_NIL;
12200 data->current_min = GRN_ID_NIL;
12201 data->set_min_enable_for_and_query = false;
12202 data->only_skip_token = false;
12203 data->query_options = NULL;
12204
12205 data->token_infos = NULL;
12206 data->n_token_infos = 0;
12207 data->n_phrase_groups = 0;
12208 data->phrase_groups = NULL;
12209 data->n_phrases = 0;
12210
12211 data->bt = NULL;
12212 data->check_element_intervals_btree = NULL;
12213
12214 data->rid = 0;
12215 data->sid = 0;
12216 data->next_rid = 0;
12217 data->next_sid = 0;
12218
12219 if (!optarg) {
12220 return;
12221 }
12222
12223 data->mode = optarg->mode;
12224
12225 if (optarg->func) {
12226 data->wv_mode = GRN_WV_DYNAMIC;
12227 } else if (optarg->vector_size != 0) {
12228 if (optarg->weight_vector || optarg->weight_vector_float) {
12229 data->wv_mode = GRN_WV_STATIC;
12230 } else {
12231 data->wv_mode = GRN_WV_CONSTANT;
12232 }
12233 }
12234
12235 if (optarg->match_info) {
12236 if (optarg->match_info->flags & GRN_MATCH_INFO_GET_MIN_RECORD_ID) {
12237 data->previous_min = optarg->match_info->min;
12238 data->set_min_enable_for_and_query = true;
12239 }
12240 }
12241
12242 if (optarg->scorer) {
12243 grn_proc *scorer = (grn_proc *)(optarg->scorer);
12244 data->score_func = scorer->callbacks.scorer.score;
12245 data->record.table = grn_ctx_at(ctx, data->result_set->obj.header.domain);
12246 data->record.lexicon = data->lexicon;
12247 data->record.id = GRN_ID_NIL;
12248 GRN_RECORD_INIT(&(data->record.terms),
12249 GRN_OBJ_VECTOR,
12250 data->lexicon->header.domain);
12251 GRN_UINT32_INIT(&(data->record.term_weights), GRN_OBJ_VECTOR);
12252 data->record.total_term_weights = 0;
12253 data->record.n_documents = grn_table_size(ctx, data->record.table);
12254 data->record.n_occurrences = 0;
12255 data->record.n_candidates = 0;
12256 data->record.n_tokens = 0;
12257 data->record.weight = 0;
12258 data->record.args_expr = optarg->scorer_args_expr;
12259 data->record.args_expr_offset = optarg->scorer_args_expr_offset;
12260 }
12261
12262 data->fuzzy_search_optarg = &(optarg->fuzzy);
12263 data->query_options = optarg->query_options;
12264 }
12265
12266 static bool
12267 grn_ii_select_data_init_token_infos(grn_ctx *ctx,
12268 grn_ii_select_data *data,
12269 const char *tag)
12270 {
12271 if (data->query_len == 0) {
12272 return false;
12273 }
12274
12275 data->token_infos = static_cast<token_info **>(
12276 GRN_MALLOC(sizeof(token_info *) * data->query_len * 2));
12277 if (!data->token_infos) {
12278 char errbuf[GRN_CTX_MSGSIZE];
12279 grn_strcpy(errbuf, GRN_CTX_MSGSIZE, ctx->errbuf);
12280 ERR(ctx->rc, "%s failed to allocate token info container: %s", tag, errbuf);
12281 return false;
12282 }
12283
12284 if (data->mode == GRN_OP_FUZZY) {
12285 grn_rc rc = token_info_build_fuzzy(ctx, data);
12286 if (rc != GRN_SUCCESS) {
12287 return false;
12288 }
12289 if (data->n_token_infos == 0) {
12290 return false;
12291 }
12292 } else if (data->mode == GRN_OP_NEAR_PHRASE ||
12293 data->mode == GRN_OP_ORDERED_NEAR_PHRASE ||
12294 data->mode == GRN_OP_NEAR_PHRASE_PRODUCT ||
12295 data->mode == GRN_OP_ORDERED_NEAR_PHRASE_PRODUCT) {
12296 grn_rc rc = token_info_build_near_phrase(ctx, data);
12297 if (rc != GRN_SUCCESS) {
12298 return false;
12299 }
12300 } else {
12301 grn_rc rc = token_info_build(ctx, data);
12302 if (rc != GRN_SUCCESS) {
12303 return false;
12304 }
12305 }
12306 if (data->n_token_infos == 0) {
12307 return false;
12308 }
12309 P_NOTE("original token infos\n");
12310 P_TIS(ctx, data->token_infos, data->n_token_infos);
12311
12312 if (data->mode == GRN_OP_NEAR_PHRASE_PRODUCT ||
12313 data->mode == GRN_OP_ORDERED_NEAR_PHRASE_PRODUCT) {
12314 data->phrase_groups = static_cast<phrase_group *>(
12315 GRN_MALLOC(sizeof(phrase_group) * data->n_phrase_groups));
12316 if (!data->phrase_groups) {
12317 return false;
12318 }
12319 uint32_t i;
12320 for (i = 0; i < data->n_phrase_groups; i++) {
12321 uint32_t i_token_info;
12322 uint32_t current_phrase_id = (uint32_t)-1;
12323 uint32_t n_phrases = 0;
12324 for (i_token_info = 0; i_token_info < data->n_token_infos;
12325 i_token_info++) {
12326 const token_info *token_info = data->token_infos[i_token_info];
12327 if (token_info->phrase_id != current_phrase_id &&
12328 data->token_infos[i_token_info]->phrase_group_id == i) {
12329 n_phrases++;
12330 }
12331 current_phrase_id = token_info->phrase_id;
12332 }
12333 data->phrase_groups[i].n_phrases = n_phrases;
12334 data->phrase_groups[i].btree = bt_open(ctx, n_phrases);
12335 }
12336 } else {
12337 data->phrase_groups = NULL;
12338 }
12339
12340 if (data->mode == GRN_OP_NEAR_NO_OFFSET) {
12341 token_info_clear_offset(data->token_infos, data->n_token_infos);
12342 data->mode = GRN_OP_NEAR;
12343 }
12344 switch (data->mode) {
12345 case GRN_OP_NEAR:
12346 case GRN_OP_NEAR_PHRASE:
12347 case GRN_OP_ORDERED_NEAR_PHRASE:
12348 case GRN_OP_NEAR_PHRASE_PRODUCT:
12349 case GRN_OP_ORDERED_NEAR_PHRASE_PRODUCT:
12350 {
12351 size_t btree_size;
12352 if (data->mode == GRN_OP_NEAR_PHRASE_PRODUCT ||
12353 data->mode == GRN_OP_ORDERED_NEAR_PHRASE_PRODUCT) {
12354 btree_size = data->n_phrase_groups;
12355 } else {
12356 btree_size = data->n_token_infos;
12357 }
12358 data->bt = bt_open(ctx, btree_size);
12359 if (!data->bt) {
12360 char errbuf[GRN_CTX_MSGSIZE];
12361 grn_strcpy(errbuf, GRN_CTX_MSGSIZE, ctx->errbuf);
12362 ERR(ctx->rc, "%s failed to allocate btree: %s", tag, errbuf);
12363 return false;
12364 }
12365 data->max_interval = data->optarg->max_interval;
12366 data->additional_last_interval = data->optarg->additional_last_interval;
12367 data->max_element_intervals = data->optarg->max_element_intervals;
12368 data->min_interval = data->optarg->min_interval;
12369 if ((data->mode == GRN_OP_NEAR || data->mode == GRN_OP_NEAR_PHRASE ||
12370 data->mode == GRN_OP_NEAR_PHRASE_PRODUCT) &&
12371 data->max_element_intervals &&
12372 GRN_INT32_VECTOR_SIZE(data->max_element_intervals) > 0) {
12373 data->check_element_intervals_btree = bt_open(ctx, btree_size);
12374 if (!data->check_element_intervals_btree) {
12375 char errbuf[GRN_CTX_MSGSIZE];
12376 grn_strcpy(errbuf, GRN_CTX_MSGSIZE, ctx->errbuf);
12377 ERR(ctx->rc,
12378 "%s failed to allocate btree for checking element intervals: %s",
12379 tag,
12380 errbuf);
12381 return false;
12382 }
12383 }
12384 }
12385 break;
12386 default:
12387 break;
12388 }
12389 qsort(data->token_infos,
12390 data->n_token_infos,
12391 sizeof(token_info *),
12392 token_compare);
12393 P_NOTE("sorted token infos\n");
12394 P_TIS(ctx, data->token_infos, data->n_token_infos);
12395 if (data->mode == GRN_OP_NEAR_PHRASE) {
12396 bool have_must_last = false;
12397 uint32_t i;
12398 for (i = 0; i < data->n_token_infos; i++) {
12399 if (data->token_infos[i]->must_last) {
12400 if (have_must_last) {
12401 /* Multiple last tokens query are never matched. */
12402 return false;
12403 }
12404 have_must_last = true;
12405 }
12406 }
12407 }
12408 return true;
12409 }
12410
12411 static void
12412 grn_ii_select_data_fin(grn_ctx *ctx, grn_ii_select_data *data)
12413 {
12414 if (data->score_func) {
12415 GRN_OBJ_FIN(ctx, &(data->record.terms));
12416 GRN_OBJ_FIN(ctx, &(data->record.term_weights));
12417 }
12418
12419 if (data->set_min_enable_for_and_query && !data->only_skip_token) {
12420 if (data->current_min > data->previous_min) {
12421 data->optarg->match_info->min = data->current_min;
12422 }
12423 }
12424
12425 if (data->only_skip_token && data->optarg && data->optarg->match_info) {
12426 data->optarg->match_info->flags |= GRN_MATCH_INFO_ONLY_SKIP_TOKEN;
12427 }
12428
12429 if (data->phrase_groups) {
12430 uint32_t i;
12431 for (i = 0; i < data->n_phrase_groups; i++) {
12432 bt_close(ctx, data->phrase_groups[i].btree);
12433 }
12434 GRN_FREE(data->phrase_groups);
12435 }
12436
12437 if (data->token_infos) {
12438 token_info **token_info;
12439 for (token_info = data->token_infos;
12440 token_info < data->token_infos + data->n_token_infos;
12441 token_info++) {
12442 if (*token_info) {
12443 token_info_close(ctx, *token_info);
12444 }
12445 }
12446 GRN_FREE(data->token_infos);
12447 }
12448
12449 if (data->bt) {
12450 bt_close(ctx, data->bt);
12451 }
12452
12453 if (data->check_element_intervals_btree) {
12454 bt_close(ctx, data->check_element_intervals_btree);
12455 }
12456 }
12457
12458 static grn_rc
12459 grn_ii_similar_search_internal(grn_ctx *ctx, grn_ii_select_data *data)
12460 {
12461 int *w1;
12462 uint32_t limit;
12463 grn_id tid, *tp, max_size;
12464 grn_rc rc = GRN_SUCCESS;
12465 grn_hash *h;
12466 grn_token_cursor *token_cursor;
12467 if (data->query_len == 0) {
12468 return GRN_SUCCESS;
12469 }
12470 if (!data->lexicon || !data->query || !data->query_len || !data->result_set ||
12471 !data->optarg) {
12472 return GRN_INVALID_ARGUMENT;
12473 }
12474 if (!(h = grn_hash_create(ctx, NULL, sizeof(grn_id), sizeof(int), 0))) {
12475 return GRN_NO_MEMORY_AVAILABLE;
12476 }
12477 token_cursor = grn_ii_select_data_open_token_cursor(ctx,
12478 data,
12479 data->query,
12480 data->query_len,
12481 GRN_TOKENIZE_GET);
12482 if (!token_cursor) {
12483 grn_hash_close(ctx, h);
12484 return ctx->rc;
12485 }
12486 if (!(max_size = data->optarg->max_size)) {
12487 max_size = 1048576;
12488 }
12489 while (token_cursor->status != GRN_TOKEN_CURSOR_DONE &&
12490 token_cursor->status != GRN_TOKEN_CURSOR_DONE_SKIP) {
12491 if ((tid = grn_token_cursor_next(ctx, token_cursor))) {
12492 if (grn_hash_add(ctx, h, &tid, sizeof(grn_id), (void **)&w1, NULL)) {
12493 (*w1)++;
12494 }
12495 }
12496 if (tid && token_cursor->curr_size) {
12497 if (data->mode == GRN_OP_UNSPLIT) {
12498 grn_table_search(ctx,
12499 data->lexicon,
12500 token_cursor->curr,
12501 token_cursor->curr_size,
12502 GRN_OP_PREFIX,
12503 (grn_obj *)h,
12504 GRN_OP_OR);
12505 }
12506 if (data->mode == GRN_OP_PARTIAL) {
12507 grn_table_search(ctx,
12508 data->lexicon,
12509 token_cursor->curr,
12510 token_cursor->curr_size,
12511 GRN_OP_SUFFIX,
12512 (grn_obj *)h,
12513 GRN_OP_OR);
12514 }
12515 }
12516 }
12517 grn_token_cursor_close(ctx, token_cursor);
12518 {
12519 grn_hash_cursor *c =
12520 grn_hash_cursor_open(ctx, h, NULL, 0, NULL, 0, 0, -1, 0);
12521 if (!c) {
12522 GRN_LOG(ctx,
12523 GRN_LOG_ALERT,
12524 "grn_hash_cursor_open on grn_ii_similar_search failed !");
12525 grn_hash_close(ctx, h);
12526 return GRN_NO_MEMORY_AVAILABLE;
12527 }
12528 while (grn_hash_cursor_next(ctx, c)) {
12529 uint32_t es;
12530 grn_hash_cursor_get_key_value(ctx, c, (void **)&tp, NULL, (void **)&w1);
12531 if ((es = grn_ii_estimate_size(ctx, data->ii, *tp))) {
12532 *w1 += max_size / es;
12533 } else {
12534 grn_hash_cursor_delete(ctx, c, NULL);
12535 }
12536 }
12537 grn_hash_cursor_close(ctx, c);
12538 }
12539 limit = data->optarg->similarity_threshold
12540 ? ((uint32_t)(data->optarg->similarity_threshold) > GRN_HASH_SIZE(h)
12541 ? GRN_HASH_SIZE(h)
12542 : (uint32_t)(data->optarg->similarity_threshold))
12543 : (GRN_HASH_SIZE(h) >> 3) + 1;
12544 if (GRN_HASH_SIZE(h)) {
12545 grn_id j, id;
12546 float w2;
12547 int rep;
12548 grn_ii_cursor *c;
12549 grn_posting *pos;
12550 grn_table_sort_optarg arg = {GRN_TABLE_SORT_DESC | GRN_TABLE_SORT_BY_VALUE |
12551 GRN_TABLE_SORT_AS_NUMBER,
12552 NULL,
12553 NULL,
12554 NULL,
12555 0};
12556 grn_array *sorted = grn_array_create(ctx, NULL, sizeof(grn_id), 0);
12557 if (!sorted) {
12558 GRN_LOG(ctx,
12559 GRN_LOG_ALERT,
12560 "grn_hash_sort on grn_ii_similar_search failed !");
12561 grn_hash_close(ctx, h);
12562 return GRN_NO_MEMORY_AVAILABLE;
12563 }
12564 grn_hash_sort(ctx, h, limit, sorted, &arg);
12565 /* todo support subrec
12566 rep = (s->record_unit == GRN_REC_POSITION || s->subrec_unit ==
12567 GRN_REC_POSITION);
12568 */
12569 rep = 0;
12570 for (j = 1; j <= limit; j++) {
12571 grn_array_get_value(ctx, sorted, j, &id);
12572 _grn_hash_get_key_value(ctx, h, id, (void **)&tp, (void **)&w1);
12573 if (!*tp || !(c = grn_ii_cursor_open(ctx,
12574 data->ii,
12575 *tp,
12576 GRN_ID_NIL,
12577 GRN_ID_MAX,
12578 rep ? data->ii->n_elements
12579 : data->ii->n_elements - 1,
12580 0))) {
12581 GRN_LOG(ctx, GRN_LOG_ERROR, "cursor open failed (%d)", *tp);
12582 continue;
12583 }
12584 if (rep) {
12585 while (grn_ii_cursor_next(ctx, c)) {
12586 pos = c->post;
12587 data->rid = pos->rid;
12588 data->sid = pos->sid;
12589 if ((w2 = get_weight(ctx, data)) > 0) {
12590 while (grn_ii_cursor_next_pos(ctx, c)) {
12591 float pos_weight = grn_posting_get_weight_float(ctx, pos);
12592 res_add(ctx,
12593 data->result_set,
12594 (grn_rset_posinfo *)pos,
12595 *w1 * w2 * (1 + pos_weight),
12596 data->op);
12597 }
12598 }
12599 }
12600 } else {
12601 while (grn_ii_cursor_next(ctx, c)) {
12602 pos = c->post;
12603 data->rid = pos->rid;
12604 data->sid = pos->sid;
12605 if ((w2 = get_weight(ctx, data)) > 0) {
12606 float pos_weight = grn_posting_get_weight_float(ctx, pos);
12607 res_add(ctx,
12608 data->result_set,
12609 (grn_rset_posinfo *)pos,
12610 *w1 * w2 * (pos->tf + pos_weight),
12611 data->op);
12612 }
12613 }
12614 }
12615 grn_ii_cursor_close(ctx, c);
12616 }
12617 grn_array_close(ctx, sorted);
12618 }
12619 grn_hash_close(ctx, h);
12620 grn_ii_resolve_sel_and(ctx, data->result_set, data->op);
12621 // grn_hash_cursor_clear(r);
12622 return rc;
12623 }
12624
12625 extern "C" grn_rc
12626 grn_ii_similar_search(grn_ctx *ctx,
12627 grn_ii *ii,
12628 const char *string,
12629 unsigned int string_len,
12630 grn_hash *s,
12631 grn_operator op,
12632 grn_select_optarg *optarg)
12633 {
12634 grn_ii_select_data data;
12635 data.ii = ii;
12636 data.lexicon = data.ii->lexicon;
12637 data.query = string;
12638 data.query_len = string_len;
12639 data.result_set = s;
12640 data.op = op;
12641 grn_ii_select_data_init(ctx, &data, optarg);
12642 return grn_ii_similar_search_internal(ctx, &data);
12643 }
12644
12645 #define TERM_EXTRACT_EACH_POST 0
12646 #define TERM_EXTRACT_EACH_TERM 1
12647
12648 static grn_rc
12649 grn_ii_term_extract_internal(grn_ctx *ctx, grn_ii_select_data *data)
12650 {
12651 grn_rset_posinfo pi;
12652 grn_id tid;
12653 const char *p, *pe;
12654 grn_obj *nstr;
12655 const char *normalized;
12656 unsigned int normalized_length_in_bytes;
12657 grn_ii_cursor *c;
12658 grn_posting *pos;
12659 int skip, rep, policy;
12660 grn_rc rc = GRN_SUCCESS;
12661 if (data->query_len == 0) {
12662 return GRN_SUCCESS;
12663 }
12664 if (!data->ii || !data->query || !data->query_len || !data->result_set ||
12665 !data->optarg) {
12666 return GRN_INVALID_ARGUMENT;
12667 }
12668 if (!(nstr = grn_string_open(ctx, data->query, data->query_len, NULL, 0))) {
12669 return GRN_INVALID_ARGUMENT;
12670 }
12671 policy = data->optarg->max_interval;
12672 /* todo support subrec
12673 if (policy == TERM_EXTRACT_EACH_POST) {
12674 if ((rc = grn_records_reopen(s, GRN_REC_SECTION, GRN_REC_NONE, 0))) { goto
12675 exit; }
12676 }
12677 rep = (s->record_unit == GRN_REC_POSITION || s->subrec_unit ==
12678 GRN_REC_POSITION);
12679 */
12680 rep = 0;
12681 grn_string_get_normalized(ctx,
12682 nstr,
12683 &normalized,
12684 &normalized_length_in_bytes,
12685 NULL);
12686 for (p = normalized, pe = p + normalized_length_in_bytes; p < pe; p += skip) {
12687 if ((tid = grn_table_lcp_search(ctx, data->ii->lexicon, p, pe - p))) {
12688 if (policy == TERM_EXTRACT_EACH_POST) {
12689 if (!(skip = grn_table_get_key(ctx, data->ii->lexicon, tid, NULL, 0))) {
12690 break;
12691 }
12692 } else {
12693 if (!(skip = (int)grn_charlen(ctx, p, pe))) {
12694 break;
12695 }
12696 }
12697 if (!(c = grn_ii_cursor_open(ctx,
12698 data->ii,
12699 tid,
12700 GRN_ID_NIL,
12701 GRN_ID_MAX,
12702 rep ? data->ii->n_elements
12703 : data->ii->n_elements - 1,
12704 0))) {
12705 GRN_LOG(ctx, GRN_LOG_ERROR, "cursor open failed (%d)", tid);
12706 continue;
12707 }
12708 if (rep) {
12709 while (grn_ii_cursor_next(ctx, c)) {
12710 pos = c->post;
12711 data->rid = pos->rid;
12712 data->sid = pos->sid;
12713 while (grn_ii_cursor_next_pos(ctx, c)) {
12714 res_add(ctx,
12715 data->result_set,
12716 (grn_rset_posinfo *)pos,
12717 get_weight(ctx, data),
12718 data->op);
12719 }
12720 }
12721 } else {
12722 while (grn_ii_cursor_next(ctx, c)) {
12723 if (policy == TERM_EXTRACT_EACH_POST) {
12724 pi.rid = c->post->rid;
12725 pi.sid = p - normalized;
12726 res_add(ctx, data->result_set, &pi, pi.sid + 1, data->op);
12727 } else {
12728 pos = c->post;
12729 data->rid = pos->rid;
12730 data->sid = pos->sid;
12731 res_add(ctx,
12732 data->result_set,
12733 (grn_rset_posinfo *)pos,
12734 get_weight(ctx, data),
12735 data->op);
12736 }
12737 }
12738 }
12739 grn_ii_cursor_close(ctx, c);
12740 } else {
12741 if (!(skip = (int)grn_charlen(ctx, p, pe))) {
12742 break;
12743 }
12744 }
12745 }
12746 grn_obj_close(ctx, nstr);
12747 return rc;
12748 }
12749
12750 extern "C" grn_rc
12751 grn_ii_term_extract(grn_ctx *ctx,
12752 grn_ii *ii,
12753 const char *string,
12754 unsigned int string_len,
12755 grn_hash *s,
12756 grn_operator op,
12757 grn_select_optarg *optarg)
12758 {
12759 grn_ii_select_data data;
12760 data.ii = ii;
12761 data.lexicon = data.ii->lexicon;
12762 data.query = string;
12763 data.query_len = string_len;
12764 data.result_set = s;
12765 data.op = op;
12766 grn_ii_select_data_init(ctx, &data, optarg);
12767 return grn_ii_term_extract_internal(ctx, &data);
12768 }
12769
12770 struct grn_ii_select_cursor_ {
12771 grn_ii_select_data data;
12772 bool per_occurrence_mode;
12773 grn_ii_select_cursor_posting posting;
12774 bool done;
12775 grn_ii_select_cursor_posting unshifted_posting;
12776 bool have_unshifted_posting;
12777 };
12778
12779 static void
12780 grn_ii_select_cursor_init_internal(grn_ctx *ctx, grn_ii_select_cursor *cursor)
12781 {
12782 cursor->per_occurrence_mode = false;
12783 cursor->done = false;
12784 cursor->have_unshifted_posting = false;
12785 }
12786
12787 static grn_rc
12788 grn_ii_select_cursor_close(grn_ctx *ctx, grn_ii_select_cursor *cursor)
12789 {
12790 if (!cursor) {
12791 return GRN_SUCCESS;
12792 }
12793
12794 grn_ii_select_data_fin(ctx, &(cursor->data));
12795 GRN_FREE(cursor);
12796
12797 return GRN_SUCCESS;
12798 }
12799
12800 static grn_ii_select_cursor *
12801 grn_ii_select_cursor_open(grn_ctx *ctx,
12802 grn_ii *ii,
12803 const char *string,
12804 unsigned int string_len,
12805 grn_select_optarg *optarg)
12806 {
12807 const char *tag = "[ii][select][cursor][open]";
12808
12809 if (string_len == 0) {
12810 ERR(GRN_INVALID_ARGUMENT, "%s empty string", tag);
12811 return NULL;
12812 }
12813
12814 auto cursor = static_cast<grn_ii_select_cursor *>(
12815 GRN_CALLOC(sizeof(grn_ii_select_cursor)));
12816 if (!cursor) {
12817 char errbuf[GRN_CTX_MSGSIZE];
12818 grn_strcpy(errbuf, GRN_CTX_MSGSIZE, ctx->errbuf);
12819 ERR(ctx->rc, "%s failed to allocate cursor: %s", tag, errbuf);
12820 return NULL;
12821 }
12822
12823 cursor->data.ii = ii;
12824 cursor->data.lexicon = cursor->data.ii->lexicon;
12825 cursor->data.query = string;
12826 cursor->data.query_len = string_len;
12827 cursor->data.result_set = NULL;
12828 cursor->data.op = GRN_OP_OR;
12829 grn_ii_select_data_init(ctx, &(cursor->data), optarg);
12830 switch (cursor->data.mode) {
12831 case GRN_OP_EXACT:
12832 case GRN_OP_FUZZY:
12833 case GRN_OP_NEAR:
12834 case GRN_OP_NEAR_NO_OFFSET:
12835 break;
12836 default:
12837 ERR(GRN_INVALID_ARGUMENT,
12838 "%s EXACT, FUZZY, NEAR and NEAR_NO_OFFSET are only supported mode: %s",
12839 tag,
12840 grn_operator_to_string(cursor->data.mode));
12841 grn_ii_select_cursor_close(ctx, cursor);
12842 return NULL;
12843 }
12844
12845 if (!grn_ii_select_data_init_token_infos(ctx, &(cursor->data), tag)) {
12846 grn_ii_select_cursor_close(ctx, cursor);
12847 return NULL;
12848 }
12849 if (cursor->data.n_token_infos == 0) {
12850 grn_ii_select_cursor_close(ctx, cursor);
12851 return NULL;
12852 }
12853
12854 GRN_LOG(ctx,
12855 GRN_LOG_INFO,
12856 "%s n=%d <%.*s>",
12857 tag,
12858 cursor->data.n_token_infos,
12859 string_len,
12860 string);
12861
12862 grn_ii_select_cursor_init_internal(ctx, cursor);
12863
12864 return cursor;
12865 }
12866
12867 static void
12868 grn_ii_select_cursor_set_per_occurrence_mode(grn_ctx *ctx,
12869 grn_ii_select_cursor *cursor,
12870 bool mode)
12871 {
12872 cursor->per_occurrence_mode = mode;
12873 }
12874
12875 static inline bool
12876 grn_ii_select_skip_pos(grn_ctx *ctx, grn_ii_select_data *data, int32_t pos)
12877 {
12878 if (token_info_skip_pos(ctx,
12879 data->current_token_info,
12880 data->rid,
12881 data->sid,
12882 pos) != GRN_SUCCESS) {
12883 return false;
12884 }
12885 if (data->current_token_info->p->rid != data->rid ||
12886 data->current_token_info->p->sid != data->sid) {
12887 if (!(data->mode == GRN_OP_NEAR_PHRASE_PRODUCT ||
12888 data->mode == GRN_OP_ORDERED_NEAR_PHRASE_PRODUCT)) {
12889 data->next_rid = data->current_token_info->p->rid;
12890 data->next_sid = data->current_token_info->p->sid;
12891 }
12892 return false;
12893 }
12894 return true;
12895 }
12896
12897 /* This function must return a "must_last" token info if it exists.
12898 * btr::n_must_lasts is the number of "must_last" token infos and
12899 * we use btr::n_must_lasts as the number of phrases that must be
12900 * last. So if this function doesn't return a "must_last" token info,
12901 * we misjudge the number of phrases that must be last.
12902 */
12903 static inline bool
12904 grn_ii_select_data_find_phrase(grn_ctx *ctx,
12905 grn_ii_select_data *data,
12906 uint32_t phrase_id,
12907 int32_t start_pos,
12908 uint32_t start_n_tokens_in_phrase)
12909 {
12910 token_info **tip;
12911 token_info **tis = data->token_infos;
12912 token_info **tie = tis + data->n_token_infos;
12913 token_info **ti_last = NULL;
12914 token_info *must_last_ti = NULL;
12915 uint32_t n_tokens_in_same_pos = 0;
12916 for (tip = tis;; tip++) {
12917 if (tip == tie) {
12918 tip = tis;
12919 }
12920 if (!ti_last) {
12921 ti_last = tip;
12922 } else if (ti_last == tip) {
12923 n_tokens_in_same_pos = 0;
12924 start_pos++;
12925 }
12926 data->current_token_info = *tip;
12927 if (data->current_token_info->phrase_id != phrase_id) {
12928 continue;
12929 }
12930 if (data->current_token_info->must_last) {
12931 must_last_ti = data->current_token_info;
12932 }
12933 if (!grn_ii_select_skip_pos(ctx, data, start_pos)) {
12934 return false;
12935 }
12936 if (data->current_token_info->pos == start_pos &&
12937 data->current_token_info->n_tokens_in_phrase >=
12938 start_n_tokens_in_phrase) {
12939 n_tokens_in_same_pos++;
12940 } else {
12941 n_tokens_in_same_pos = 1;
12942 if (data->current_token_info->pos > start_pos) {
12943 start_n_tokens_in_phrase = 0;
12944 ti_last = tip;
12945 }
12946 start_pos = data->current_token_info->pos;
12947 }
12948 if (n_tokens_in_same_pos ==
12949 data->current_token_info->n_used_tokens_in_phrase &&
12950 data->current_token_info->n_tokens_in_phrase >=
12951 start_n_tokens_in_phrase) {
12952 if (must_last_ti) {
12953 data->current_token_info = must_last_ti;
12954 }
12955 P_NOTE("%s: found: record:%u phrase:%u/%u\n",
12956 __func__,
12957 data->rid,
12958 data->current_token_info->phrase_id,
12959 data->current_token_info->phrase_group_id);
12960 P_TI(ctx, data->current_token_info);
12961 return true;
12962 }
12963 }
12964 return false;
12965 }
12966
12967 static inline bool
12968 grn_ii_select_data_find_phrase_product(grn_ctx *ctx,
12969 grn_ii_select_data *data,
12970 int32_t start_pos,
12971 uint32_t start_n_tokens_in_phrase)
12972 {
12973 uint32_t phrase_group_id = data->current_token_info->phrase_group_id;
12974 phrase_group *group = &(data->phrase_groups[phrase_group_id]);
12975 bool skipped = false;
12976 token_info *min_before = group->btree->min;
12977 while (true) {
12978 data->current_token_info = group->btree->min;
12979 if (grn_ii_select_data_find_phrase(ctx,
12980 data,
12981 data->current_token_info->phrase_id,
12982 start_pos,
12983 start_n_tokens_in_phrase)) {
12984 skipped = true;
12985 bt_reorder_min(group->btree);
12986 token_info *min = group->btree->min;
12987 if (min == min_before) {
12988 break;
12989 }
12990 if (min->pos == min_before->pos &&
12991 min->n_tokens_in_phrase > min_before->n_tokens_in_phrase) {
12992 break;
12993 }
12994 min_before = min;
12995 } else {
12996 bt_pop(group->btree);
12997 if (!group->btree->min) {
12998 break;
12999 }
13000 }
13001 }
13002 if (!skipped) {
13003 return false;
13004 }
13005 P_NOTE("%s: found: record:%u\n", __func__, data->rid);
13006 P_TI(ctx, group->btree->min);
13007 bt_replace_min(data->bt, group->btree->min);
13008 return true;
13009 }
13010
13011 static inline bool
13012 grn_ii_select_data_is_matched_near_phrase_real(grn_ctx *ctx,
13013 grn_ii_select_data *data,
13014 int interval)
13015 {
13016 if (interval < data->min_interval) {
13017 return false;
13018 }
13019 if (data->max_interval < 0) {
13020 return true;
13021 }
13022 if (data->additional_last_interval == 0) {
13023 return (interval <= data->max_interval);
13024 }
13025
13026 token_info *min_token_info = NULL;
13027 int min_without_last_token = -1;
13028 int max_without_last_token = -1;
13029 if (data->mode == GRN_OP_ORDERED_NEAR_PHRASE_PRODUCT) {
13030 uint32_t i;
13031 uint32_t n = data->n_phrase_groups;
13032 for (i = 0; i < n - 1; i++) {
13033 token_info *ti = data->phrase_groups[i].btree->min;
13034 if (min_without_last_token == -1 || ti->pos < min_without_last_token) {
13035 min_without_last_token = ti->pos;
13036 min_token_info = ti;
13037 }
13038 if (max_without_last_token == -1 || ti->pos > max_without_last_token) {
13039 max_without_last_token = ti->pos;
13040 }
13041 }
13042 } else if (data->mode == GRN_OP_NEAR_PHRASE_PRODUCT) {
13043 uint32_t i;
13044 uint32_t n = data->n_phrase_groups;
13045 for (i = 0; i < n; i++) {
13046 token_info *ti = data->phrase_groups[i].btree->min;
13047 if (ti->must_last) {
13048 continue;
13049 }
13050 if (min_without_last_token == -1 || ti->pos < min_without_last_token) {
13051 min_without_last_token = ti->pos;
13052 min_token_info = ti;
13053 }
13054 if (max_without_last_token == -1 || ti->pos > max_without_last_token) {
13055 max_without_last_token = ti->pos;
13056 }
13057 }
13058 } else {
13059 uint32_t i;
13060 uint32_t n = data->n_token_infos;
13061 for (i = 0; i < n; i++) {
13062 token_info *ti = data->token_infos[i];
13063 if (ti->must_last) {
13064 continue;
13065 }
13066 if (min_without_last_token == -1 || ti->pos < min_without_last_token) {
13067 min_without_last_token = ti->pos;
13068 min_token_info = ti;
13069 }
13070 if (max_without_last_token == -1 || ti->pos > max_without_last_token) {
13071 max_without_last_token = ti->pos;
13072 }
13073 }
13074 }
13075 if (!min_token_info) {
13076 return true;
13077 }
13078
13079 int interval_without_last_token = max_without_last_token -
13080 min_without_last_token -
13081 min_token_info->n_tokens_in_phrase;
13082 if (data->additional_last_interval < 0) {
13083 return (interval_without_last_token <= data->max_interval);
13084 } else {
13085 return (
13086 (interval <= (data->max_interval + data->additional_last_interval)) &&
13087 (interval_without_last_token <= data->max_interval));
13088 }
13089 }
13090
13091 static inline bool
13092 grn_ii_select_data_is_matched_near_phrase(grn_ctx *ctx,
13093 grn_ii_select_data *data,
13094 int interval)
13095 {
13096 bool matched =
13097 grn_ii_select_data_is_matched_near_phrase_real(ctx, data, interval);
13098 P_NOTE("%s: %s: record:%u interval:%d min:%d max:%d/%d\n",
13099 __func__,
13100 matched ? "matched" : "not matched",
13101 data->rid,
13102 interval,
13103 data->min_interval,
13104 data->max_interval,
13105 data->additional_last_interval);
13106 return matched;
13107 }
13108
13109 static inline bool
13110 grn_ii_select_data_check_near_element_intervals(grn_ctx *ctx,
13111 grn_ii_select_data *data)
13112 {
13113 if (!data->max_element_intervals) {
13114 return true;
13115 }
13116
13117 uint32_t n_max_element_intervals =
13118 GRN_INT32_VECTOR_SIZE(data->max_element_intervals);
13119 if (n_max_element_intervals == 0) {
13120 return true;
13121 }
13122
13123 if (data->mode == GRN_OP_NEAR || data->mode == GRN_OP_NEAR_PHRASE ||
13124 data->mode == GRN_OP_NEAR_PHRASE_PRODUCT) {
13125 uint32_t i;
13126 uint32_t n = data->bt->n;
13127 bt_zap(data->check_element_intervals_btree);
13128 for (i = 0; i < n; i++) {
13129 bt_push(data->check_element_intervals_btree, data->bt->nodes[i].ti);
13130 }
13131 if (n > n_max_element_intervals + 1) {
13132 n = n_max_element_intervals + 1;
13133 }
13134 int32_t previous_pos = data->check_element_intervals_btree->min->pos;
13135 int32_t previous_n_tokens_in_phrase =
13136 data->check_element_intervals_btree->min->n_tokens_in_phrase;
13137 for (i = 1; i < n; i++) {
13138 bt_pop(data->check_element_intervals_btree);
13139 token_info *min = data->check_element_intervals_btree->min;
13140 int32_t pos = min->pos;
13141 int32_t max_element_interval =
13142 GRN_INT32_VALUE_AT(data->max_element_intervals, i - 1);
13143 int32_t interval = pos - previous_pos - previous_n_tokens_in_phrase;
13144 if (max_element_interval >= 0 && interval > max_element_interval) {
13145 return false;
13146 }
13147 if (interval < data->min_interval) {
13148 return false;
13149 }
13150 previous_pos = pos;
13151 previous_n_tokens_in_phrase = min->n_tokens_in_phrase;
13152 }
13153 return true;
13154 } else if (data->mode == GRN_OP_ORDERED_NEAR_PHRASE) {
13155 uint32_t i_token_info;
13156 uint32_t n_token_infos = data->n_token_infos;
13157 uint32_t i_interval;
13158 uint32_t n_intervals = data->n_phrases - 1;
13159 if (n_intervals > n_max_element_intervals) {
13160 n_intervals = n_max_element_intervals;
13161 }
13162 uint32_t previous_phrase_id = data->token_infos[0]->phrase_id;
13163 int32_t previous_pos = data->token_infos[0]->pos;
13164 int32_t previous_n_tokens_in_phrase =
13165 data->token_infos[0]->n_tokens_in_phrase;
13166 for (i_token_info = 1, i_interval = 0;
13167 i_token_info < n_token_infos && i_interval < n_intervals;
13168 i_token_info++) {
13169 token_info *token_info = data->token_infos[i_token_info];
13170 if (token_info->phrase_id == previous_phrase_id) {
13171 continue;
13172 }
13173 previous_phrase_id = token_info->phrase_id;
13174 int32_t pos = token_info->pos;
13175 int32_t max_element_interval =
13176 GRN_INT32_VALUE_AT(data->max_element_intervals, i_interval);
13177 int32_t interval = pos - previous_pos - previous_n_tokens_in_phrase;
13178 if (max_element_interval >= 0 && interval > max_element_interval) {
13179 return false;
13180 }
13181 if (interval < data->min_interval) {
13182 return false;
13183 }
13184 previous_pos = pos;
13185 previous_n_tokens_in_phrase = token_info->n_tokens_in_phrase;
13186 i_interval++;
13187 }
13188 return true;
13189 } else if (data->mode == GRN_OP_ORDERED_NEAR_PHRASE_PRODUCT) {
13190 uint32_t i;
13191 uint32_t n = data->n_phrase_groups;
13192 if (n > n_max_element_intervals + 1) {
13193 n = n_max_element_intervals + 1;
13194 }
13195 int32_t previous_pos = data->phrase_groups[0].btree->min->pos;
13196 int32_t previous_n_tokens_in_phrase =
13197 data->phrase_groups[0].btree->min->n_tokens_in_phrase;
13198 for (i = 1; i < n; i++) {
13199 token_info *min = data->phrase_groups[i].btree->min;
13200 int32_t pos = min->pos;
13201 int32_t max_element_interval =
13202 GRN_INT32_VALUE_AT(data->max_element_intervals, i - 1);
13203 int32_t interval = pos - previous_pos - previous_n_tokens_in_phrase;
13204 if (max_element_interval >= 0 && interval > max_element_interval) {
13205 return false;
13206 }
13207 if (interval < data->min_interval) {
13208 return false;
13209 }
13210 previous_pos = pos;
13211 previous_n_tokens_in_phrase = min->n_tokens_in_phrase;
13212 }
13213 return true;
13214 } else {
13215 return false;
13216 }
13217 }
13218
13219 static inline bool
13220 grn_ii_select_cursor_next_prepare(grn_ctx *ctx, grn_ii_select_cursor *cursor)
13221 {
13222 grn_ii_select_data *data = &(cursor->data);
13223 uint32_t i;
13224 uint32_t n = data->n_token_infos;
13225 if (data->mode == GRN_OP_NEAR_PHRASE_PRODUCT ||
13226 data->mode == GRN_OP_ORDERED_NEAR_PHRASE_PRODUCT) {
13227 uint32_t min_rid = 0;
13228 uint32_t min_sid = 0;
13229 for (i = 0; i < n; i++) {
13230 token_info *ti = data->token_infos[i];
13231 if (ti->phrase_group_id == 0) {
13232 if ((ti->p->rid < data->next_rid) ||
13233 (ti->p->rid == data->next_rid && ti->p->sid < data->next_sid)) {
13234 continue;
13235 }
13236 if (min_rid == 0 || ti->p->rid < min_rid ||
13237 (ti->p->rid == min_rid && ti->p->sid < min_sid)) {
13238 min_rid = ti->p->rid;
13239 min_sid = ti->p->sid;
13240 }
13241 } else {
13242 token_info_skip(ctx, ti, min_rid, min_sid);
13243 }
13244 }
13245 data->rid = min_rid;
13246 data->sid = min_sid;
13247 data->next_rid = data->rid;
13248 data->next_sid = data->sid + 1;
13249 } else {
13250 data->rid = data->token_infos[0]->p->rid;
13251 data->sid = data->token_infos[0]->p->sid;
13252 data->next_rid = data->rid;
13253 data->next_sid = data->sid + 1;
13254 for (i = 1; i < n; i++) {
13255 data->current_token_info = data->token_infos[i];
13256 if (token_info_skip(ctx,
13257 data->current_token_info,
13258 data->rid,
13259 data->sid) != GRN_SUCCESS) {
13260 return false;
13261 }
13262 if (data->current_token_info->p->rid != data->rid ||
13263 data->current_token_info->p->sid != data->sid) {
13264 data->next_rid = data->current_token_info->p->rid;
13265 data->next_sid = data->current_token_info->p->sid;
13266 break;
13267 }
13268 }
13269 data->may_match = (i == data->n_token_infos);
13270 }
13271 return true;
13272 }
13273
13274 static inline bool
13275 grn_ii_select_cursor_next_skip(grn_ctx *ctx, grn_ii_select_cursor *cursor)
13276 {
13277 grn_ii_select_data *data = &(cursor->data);
13278 if (data->mode == GRN_OP_NEAR_PHRASE_PRODUCT ||
13279 data->mode == GRN_OP_ORDERED_NEAR_PHRASE_PRODUCT) {
13280 bool skipped = false;
13281 uint32_t i;
13282 uint32_t n = data->n_token_infos;
13283 for (i = 0; i < n; i++) {
13284 token_info *ti = data->token_infos[i];
13285 if (ti->phrase_group_id != 0) {
13286 break;
13287 }
13288 if (token_info_skip(ctx, ti, data->next_rid, data->next_sid) ==
13289 GRN_SUCCESS) {
13290 skipped = true;
13291 }
13292 }
13293 return skipped;
13294 } else {
13295 return token_info_skip(ctx,
13296 data->token_infos[0],
13297 data->next_rid,
13298 data->next_sid) == GRN_SUCCESS;
13299 }
13300 }
13301
13302 static inline bool
13303 grn_ii_select_cursor_next_find_one_token(grn_ctx *ctx,
13304 grn_ii_select_cursor *cursor,
13305 const char *tag)
13306 {
13307 grn_ii_select_data *data = &(cursor->data);
13308 token_info *ti = data->token_infos[0];
13309 data->start_pos = data->end_pos = data->pos = ti->p->pos;
13310 if (cursor->per_occurrence_mode) {
13311 data->n_occurrences = 1;
13312 } else {
13313 data->n_occurrences = ti->p->tf;
13314 }
13315 data->total_score = ti->p->weight + ti->cursors->bins[0]->weight;
13316 if (data->score_func) {
13317 GRN_RECORD_PUT(ctx, &(data->record.terms), ti->cursors->bins[0]->id);
13318 GRN_UINT32_PUT(ctx, &(data->record.term_weights), data->total_score);
13319 data->record.n_occurrences = data->n_occurrences;
13320 data->record.n_candidates = ti->size;
13321 data->record.n_tokens = ti->ntoken;
13322 }
13323 return true;
13324 }
13325
13326 static inline bool
13327 grn_ii_select_cursor_next_find_near(grn_ctx *ctx,
13328 grn_ii_select_cursor *cursor,
13329 const char *tag)
13330 {
13331 grn_ii_select_data *data = &(cursor->data);
13332 bt_zap(data->bt);
13333 bool need_check = true;
13334 if (data->mode == GRN_OP_NEAR_PHRASE ||
13335 data->mode == GRN_OP_ORDERED_NEAR_PHRASE) {
13336 uint32_t phrase_id;
13337 for (phrase_id = 0; phrase_id < data->n_phrases; phrase_id++) {
13338 if (!grn_ii_select_data_find_phrase(ctx, data, phrase_id, data->pos, 0)) {
13339 need_check = false;
13340 break;
13341 }
13342 /* TODO: Can we update data->pos to reduce needless search? */
13343 bt_push(data->bt, data->current_token_info);
13344 }
13345 } else if (data->mode == GRN_OP_NEAR_PHRASE_PRODUCT ||
13346 data->mode == GRN_OP_ORDERED_NEAR_PHRASE_PRODUCT) {
13347 uint32_t i;
13348 uint32_t phrase_id = 0;
13349 for (i = 0; i < data->n_phrase_groups; i++) {
13350 phrase_group *group = &(data->phrase_groups[i]);
13351 bt_zap(group->btree);
13352 uint32_t end_phrase_id = phrase_id + group->n_phrases;
13353 bool have_phrase = false;
13354 for (; phrase_id < end_phrase_id; phrase_id++) {
13355 if (grn_ii_select_data_find_phrase(ctx,
13356 data,
13357 phrase_id,
13358 data->pos,
13359 0)) {
13360 have_phrase = true;
13361 bt_push(group->btree, data->current_token_info);
13362 /* TODO: Can we update data->pos to reduce needless search? */
13363 }
13364 }
13365 if (!have_phrase) {
13366 need_check = false;
13367 break;
13368 }
13369 bt_push(data->bt, group->btree->min);
13370 }
13371 } else {
13372 uint32_t i;
13373 uint32_t n = data->n_token_infos;
13374 for (i = 0; i < n; i++) {
13375 token_info *ti = data->token_infos[i];
13376 bt_push(data->bt, ti);
13377 }
13378 }
13379 if (!need_check) {
13380 return true;
13381 }
13382
13383 for (;;) {
13384 data->current_token_info = data->bt->min;
13385 token_info *min_token_info = data->bt->min;
13386 token_info *max_token_info = data->bt->max;
13387 int32_t min = min_token_info->pos;
13388 uint32_t min_n_tokens_in_phrase = min_token_info->n_tokens_in_phrase;
13389 int32_t max = max_token_info->pos;
13390 if (min > max) {
13391 char ii_name[GRN_TABLE_MAX_KEY_SIZE];
13392 int ii_name_size;
13393 ii_name_size = grn_obj_name(ctx,
13394 (grn_obj *)(data->ii),
13395 ii_name,
13396 GRN_TABLE_MAX_KEY_SIZE);
13397 ERR(GRN_FILE_CORRUPT,
13398 "%s[%s] "
13399 "max position must be larger than min position: "
13400 "min:<%d> max:<%d> ii:<%.*s> string:<%.*s>",
13401 tag,
13402 grn_operator_to_string(data->mode),
13403 min,
13404 max,
13405 ii_name_size,
13406 ii_name,
13407 data->query_len,
13408 data->query);
13409 return false;
13410 }
13411 int32_t interval = max - min;
13412 if (data->mode == GRN_OP_NEAR_PHRASE ||
13413 data->mode == GRN_OP_ORDERED_NEAR_PHRASE ||
13414 data->mode == GRN_OP_NEAR_PHRASE_PRODUCT ||
13415 data->mode == GRN_OP_ORDERED_NEAR_PHRASE_PRODUCT) {
13416 interval -= data->current_token_info->n_tokens_in_phrase;
13417 }
13418 P_NOTE("%s record:%u interval:%d min:%d max:%d\n",
13419 __func__,
13420 data->rid,
13421 interval,
13422 min,
13423 max);
13424 P_TI(ctx, min_token_info);
13425 P_TI(ctx, max_token_info);
13426 bool matched = false;
13427 if (data->mode == GRN_OP_ORDERED_NEAR_PHRASE) {
13428 matched = true;
13429 uint32_t i;
13430 uint32_t n = data->n_token_infos;
13431 int32_t pos = data->token_infos[0]->pos;
13432 for (i = 1; i < n; i++) {
13433 token_info *ti = data->token_infos[i];
13434 if (ti->pos < pos) {
13435 matched = false;
13436 break;
13437 }
13438 pos = ti->pos;
13439 }
13440 if (matched) {
13441 matched =
13442 grn_ii_select_data_is_matched_near_phrase(ctx, data, interval);
13443 }
13444 } else if (data->mode == GRN_OP_ORDERED_NEAR_PHRASE_PRODUCT) {
13445 matched = true;
13446 uint32_t i;
13447 uint32_t n = data->n_phrase_groups;
13448 int32_t pos = data->phrase_groups[0].btree->min->pos;
13449 for (i = 1; i < n; i++) {
13450 token_info *ti = data->phrase_groups[i].btree->min;
13451 if (ti->pos < pos) {
13452 matched = false;
13453 break;
13454 }
13455 pos = ti->pos;
13456 }
13457 if (matched) {
13458 matched =
13459 grn_ii_select_data_is_matched_near_phrase(ctx, data, interval);
13460 }
13461 } else if (data->bt->n_must_lasts > 0) {
13462 matched =
13463 (data->bt->n_must_lasts == 1 && data->bt->max->must_last &&
13464 grn_ii_select_data_is_matched_near_phrase(ctx, data, interval));
13465 } else {
13466 matched = ((data->max_interval < 0 || interval <= data->max_interval) &&
13467 interval >= data->min_interval);
13468 }
13469 if (matched) {
13470 matched = grn_ii_select_data_check_near_element_intervals(ctx, data);
13471 }
13472 if (matched) {
13473 data->n_occurrences++;
13474 int32_t next_pos = max + 1;
13475 if (data->mode == GRN_OP_NEAR_PHRASE ||
13476 data->mode == GRN_OP_ORDERED_NEAR_PHRASE) {
13477 if (!grn_ii_select_data_find_phrase(ctx,
13478 data,
13479 data->current_token_info->phrase_id,
13480 next_pos,
13481 0)) {
13482 break;
13483 }
13484 } else if (data->mode == GRN_OP_NEAR_PHRASE_PRODUCT ||
13485 data->mode == GRN_OP_ORDERED_NEAR_PHRASE_PRODUCT) {
13486 if (!grn_ii_select_data_find_phrase_product(ctx, data, next_pos, 0)) {
13487 break;
13488 }
13489 } else {
13490 if (!grn_ii_select_skip_pos(ctx, data, next_pos)) {
13491 break;
13492 }
13493 }
13494 } else {
13495 if (data->mode == GRN_OP_NEAR_PHRASE ||
13496 data->mode == GRN_OP_ORDERED_NEAR_PHRASE) {
13497 int32_t next_pos = min + 1;
13498 if (!grn_ii_select_data_find_phrase(ctx,
13499 data,
13500 data->current_token_info->phrase_id,
13501 next_pos,
13502 0)) {
13503 break;
13504 }
13505 } else if (data->mode == GRN_OP_NEAR_PHRASE_PRODUCT ||
13506 data->mode == GRN_OP_ORDERED_NEAR_PHRASE_PRODUCT) {
13507 uint32_t next_tokens_in_phrase = min_token_info->n_tokens_in_phrase + 1;
13508 if (!grn_ii_select_data_find_phrase_product(ctx,
13509 data,
13510 min,
13511 next_tokens_in_phrase)) {
13512 break;
13513 }
13514 } else {
13515 int32_t next_pos = max - data->max_interval;
13516 if (next_pos <= min) {
13517 next_pos = min + 1;
13518 }
13519 if (!grn_ii_select_skip_pos(ctx, data, next_pos)) {
13520 break;
13521 }
13522 }
13523 }
13524 bt_reorder_min(data->bt);
13525 if ((data->mode == GRN_OP_NEAR_PHRASE ||
13526 data->mode == GRN_OP_ORDERED_NEAR_PHRASE ||
13527 data->mode == GRN_OP_NEAR_PHRASE_PRODUCT ||
13528 data->mode == GRN_OP_ORDERED_NEAR_PHRASE_PRODUCT) &&
13529 data->bt->min->pos == min &&
13530 data->bt->min->n_tokens_in_phrase == min_n_tokens_in_phrase) {
13531 break;
13532 }
13533 }
13534 return true;
13535 }
13536
13537 static inline bool
13538 grn_ii_select_cursor_next_find(grn_ctx *ctx,
13539 grn_ii_select_cursor *cursor,
13540 const char *tag)
13541 {
13542 grn_ii_select_data *data = &(cursor->data);
13543 uint32_t count = 0;
13544 int32_t score = 0;
13545 token_info **tis = data->token_infos;
13546 token_info **tie = data->token_infos + data->n_token_infos;
13547 token_info **tip;
13548 for (tip = tis;; tip++) {
13549 if (tip == tie) {
13550 tip = tis;
13551 }
13552 data->current_token_info = *tip;
13553 if (!grn_ii_select_skip_pos(ctx, data, data->pos)) {
13554 break;
13555 }
13556 if (data->current_token_info->pos == (int32_t)(data->pos)) {
13557 if (count == 0) {
13558 data->start_pos = data->pos;
13559 }
13560 score += data->current_token_info->p->weight +
13561 data->current_token_info->cursors->bins[0]->weight;
13562 count++;
13563 if ((int32_t)(data->current_token_info->p->pos) > data->end_pos) {
13564 data->end_pos = data->current_token_info->p->pos;
13565 }
13566 } else {
13567 score = data->current_token_info->p->weight +
13568 data->current_token_info->cursors->bins[0]->weight;
13569 count = 1;
13570 data->start_pos = data->pos = data->current_token_info->pos;
13571 data->end_pos = data->current_token_info->p->pos;
13572 if (data->n_occurrences == 0 && data->score_func) {
13573 GRN_BULK_REWIND(&(data->record.terms));
13574 GRN_BULK_REWIND(&(data->record.term_weights));
13575 data->record.n_candidates = 0;
13576 data->record.n_tokens = 0;
13577 }
13578 }
13579 if (data->n_occurrences == 0 && data->score_func) {
13580 GRN_RECORD_PUT(ctx,
13581 &(data->record.terms),
13582 data->current_token_info->cursors->bins[0]->id);
13583 GRN_UINT32_PUT(ctx,
13584 &(data->record.term_weights),
13585 data->current_token_info->p->weight +
13586 data->current_token_info->cursors->bins[0]->weight);
13587 data->record.n_candidates += data->current_token_info->size;
13588 data->record.n_tokens += data->current_token_info->ntoken;
13589 }
13590 if (count == data->n_token_infos) {
13591 if ((int32_t)(data->current_token_info->p->pos) > data->end_pos) {
13592 data->end_pos = data->current_token_info->p->pos;
13593 }
13594 data->total_score += score;
13595 score = 0;
13596 count = 0;
13597 data->pos++;
13598 data->n_occurrences++;
13599 if (cursor->per_occurrence_mode) {
13600 break;
13601 }
13602 }
13603 }
13604 return true;
13605 }
13606
13607 extern "C" grn_ii_select_cursor_posting *
13608 grn_ii_select_cursor_next(grn_ctx *ctx, grn_ii_select_cursor *cursor)
13609 {
13610 const char *tag = "[ii][select][cursor][next]";
13611
13612 if (cursor->have_unshifted_posting) {
13613 cursor->have_unshifted_posting = false;
13614 return &(cursor->unshifted_posting);
13615 }
13616
13617 if (cursor->done) {
13618 return NULL;
13619 }
13620
13621 grn_ii_select_data *data = &(cursor->data);
13622 for (;;) {
13623 data->may_match = true;
13624 if (!grn_ii_select_cursor_next_prepare(ctx, cursor)) {
13625 goto exit;
13626 }
13627 float weight = get_weight(ctx, data);
13628 if (data->may_match && fpclassify(weight) == FP_ZERO) {
13629 data->may_match = false;
13630 }
13631 if (data->may_match) {
13632 if (data->op != GRN_OP_OR) {
13633 if (data->result_set) {
13634 grn_rset_posinfo pi = {data->rid, data->sid, 0};
13635 grn_id id = grn_hash_get(ctx,
13636 data->result_set,
13637 &pi,
13638 data->result_set->key_size,
13639 NULL);
13640 data->may_match = (id != GRN_ID_NIL);
13641 }
13642 }
13643 }
13644 if (!data->may_match) {
13645 if (!grn_ii_select_cursor_next_skip(ctx, cursor)) {
13646 goto exit;
13647 }
13648 continue;
13649 }
13650
13651 data->start_pos = 0;
13652 data->end_pos = 0;
13653 data->total_score = 0;
13654 data->n_occurrences = 0;
13655
13656 data->pos = 0;
13657 if (data->score_func) {
13658 GRN_BULK_REWIND(&(data->record.terms));
13659 GRN_BULK_REWIND(&(data->record.term_weights));
13660 data->record.n_candidates = 0;
13661 data->record.n_tokens = 0;
13662 }
13663
13664 if (data->n_token_infos == 1) {
13665 if (!grn_ii_select_cursor_next_find_one_token(ctx, cursor, tag)) {
13666 goto exit;
13667 }
13668 } else if (data->mode == GRN_OP_NEAR || data->mode == GRN_OP_NEAR_PHRASE ||
13669 data->mode == GRN_OP_ORDERED_NEAR_PHRASE ||
13670 data->mode == GRN_OP_NEAR_PHRASE_PRODUCT ||
13671 data->mode == GRN_OP_ORDERED_NEAR_PHRASE_PRODUCT) {
13672 if (!grn_ii_select_cursor_next_find_near(ctx, cursor, tag)) {
13673 goto exit;
13674 }
13675 } else {
13676 if (!grn_ii_select_cursor_next_find(ctx, cursor, tag)) {
13677 goto exit;
13678 }
13679 }
13680
13681 if (data->n_occurrences == 0) {
13682 if (!grn_ii_select_cursor_next_skip(ctx, cursor)) {
13683 goto exit;
13684 }
13685 continue;
13686 }
13687
13688 double record_score;
13689 if (data->score_func) {
13690 data->record.id = data->rid;
13691 data->record.weight = (int)weight;
13692 data->record.n_occurrences = data->n_occurrences;
13693 data->record.total_term_weights = data->total_score;
13694 record_score = data->score_func(ctx, &(data->record)) * (double)weight;
13695 } else {
13696 record_score = (data->n_occurrences + data->total_score) * (double)weight;
13697 }
13698 if (data->set_min_enable_for_and_query) {
13699 if (data->current_min == GRN_ID_NIL) {
13700 data->current_min = data->rid;
13701 }
13702 }
13703
13704 cursor->posting.rid = data->rid;
13705 cursor->posting.sid = data->sid;
13706 cursor->posting.pos = data->pos;
13707 cursor->posting.start_pos = data->start_pos;
13708 cursor->posting.end_pos = data->end_pos;
13709 cursor->posting.tf = data->n_occurrences;
13710 cursor->posting.score = record_score;
13711 if (cursor->per_occurrence_mode) {
13712 if (token_info_skip_pos(ctx,
13713 data->token_infos[0],
13714 data->rid,
13715 data->sid,
13716 data->end_pos + 1) != GRN_SUCCESS) {
13717 cursor->done = true;
13718 }
13719 } else {
13720 if (!grn_ii_select_cursor_next_skip(ctx, cursor)) {
13721 cursor->done = true;
13722 }
13723 }
13724 return &(cursor->posting);
13725 }
13726
13727 exit:
13728 cursor->done = true;
13729 return NULL;
13730 }
13731
13732 static void
13733 grn_ii_select_cursor_unshift(grn_ctx *ctx,
13734 grn_ii_select_cursor *cursor,
13735 grn_ii_select_cursor_posting *posting)
13736 {
13737 cursor->unshifted_posting = *posting;
13738 cursor->have_unshifted_posting = true;
13739 }
13740
13741 extern "C" grn_ii *
13742 grn_ii_select_cursor_get_ii(grn_ctx *ctx, grn_ii_select_cursor *cursor)
13743 {
13744 return cursor->data.ii;
13745 }
13746
13747 static void
13748 grn_ii_parse_regexp_query_flush(grn_ctx *ctx,
13749 grn_obj *parsed_strings,
13750 grn_obj *parsed_n_following_characters,
13751 grn_obj *string,
13752 uint32_t *n_following_characters_start,
13753 uint32_t *n_following_characters_end)
13754 {
13755 if (GRN_TEXT_LEN(string) > 0) {
13756 grn_vector_add_element(ctx,
13757 parsed_strings,
13758 GRN_TEXT_VALUE(string),
13759 GRN_TEXT_LEN(string),
13760 0,
13761 GRN_DB_TEXT);
13762 GRN_BULK_REWIND(string);
13763 GRN_UINT32_PUT(ctx,
13764 parsed_n_following_characters,
13765 *n_following_characters_start);
13766 GRN_UINT32_PUT(ctx,
13767 parsed_n_following_characters,
13768 *n_following_characters_end);
13769 }
13770 *n_following_characters_start = 0;
13771 *n_following_characters_end = 0;
13772 }
13773
13774 static grn_rc
13775 grn_ii_parse_regexp_query(grn_ctx *ctx,
13776 const char *log_tag,
13777 const char *string,
13778 unsigned int string_len,
13779 grn_obj *parsed_strings,
13780 grn_obj *parsed_n_following_characters)
13781 {
13782 bool escaping = false;
13783 bool in_paren = false;
13784 const char *all_off_options = "?-mix:";
13785 size_t all_off_options_len = strlen(all_off_options);
13786 int nth_char = 0;
13787 const char *current = string;
13788 const char *string_end = string + string_len;
13789 grn_obj buffer;
13790 uint32_t n_following_characters_start = 0;
13791 uint32_t n_following_characters_end = 0;
13792
13793 GRN_TEXT_INIT(&buffer, 0);
13794 while (current < string_end) {
13795 const char *target;
13796 int char_len;
13797
13798 char_len = grn_charlen(ctx, current, string_end);
13799 if (char_len == 0) {
13800 GRN_OBJ_FIN(ctx, &buffer);
13801 ERR(GRN_INVALID_ARGUMENT,
13802 "%s invalid encoding character: <%.*s|%#x|>",
13803 log_tag,
13804 (int)(current - string),
13805 string,
13806 *current);
13807 return ctx->rc;
13808 }
13809 target = current;
13810 current += char_len;
13811
13812 if (escaping) {
13813 escaping = false;
13814 if (char_len == 1) {
13815 switch (*target) {
13816 case 'A':
13817 if (nth_char == 0) {
13818 target = GRN_TOKENIZER_BEGIN_MARK_UTF8;
13819 char_len = GRN_TOKENIZER_BEGIN_MARK_UTF8_LEN;
13820 }
13821 break;
13822 case 'z':
13823 if (current == string_end ||
13824 (in_paren && grn_charlen(ctx, current, string_end) == 1 &&
13825 *current == ')' && (current + 1) == string_end)) {
13826 target = GRN_TOKENIZER_END_MARK_UTF8;
13827 char_len = GRN_TOKENIZER_END_MARK_UTF8_LEN;
13828 }
13829 break;
13830 default:
13831 break;
13832 }
13833 }
13834 } else {
13835 if (n_following_characters_start > 0 &&
13836 (!(char_len == 1 && (*target == '.' || *target == '*')))) {
13837 grn_ii_parse_regexp_query_flush(ctx,
13838 parsed_strings,
13839 parsed_n_following_characters,
13840 &buffer,
13841 &n_following_characters_start,
13842 &n_following_characters_end);
13843 }
13844
13845 if (char_len == 1) {
13846 if (*target == '\\') {
13847 escaping = true;
13848 continue;
13849 } else if (*target == '(' &&
13850 (size_t)(string_end - current) >= all_off_options_len &&
13851 memcmp(current, all_off_options, all_off_options_len) == 0) {
13852 current += all_off_options_len;
13853 in_paren = true;
13854 continue;
13855 } else if (*target == ')') {
13856 in_paren = false;
13857 continue;
13858 } else if (*target == '.') {
13859 n_following_characters_start++;
13860 n_following_characters_end++;
13861 continue;
13862 } else if (*target == '*') {
13863 /* ".*" is only supported for now. */
13864 if (n_following_characters_start > 0) {
13865 n_following_characters_start--;
13866 n_following_characters_end--;
13867 }
13868 grn_ii_parse_regexp_query_flush(ctx,
13869 parsed_strings,
13870 parsed_n_following_characters,
13871 &buffer,
13872 &n_following_characters_start,
13873 &n_following_characters_end);
13874 continue;
13875 }
13876 }
13877 }
13878
13879 GRN_TEXT_PUT(ctx, &buffer, target, char_len);
13880 nth_char++;
13881 }
13882 grn_ii_parse_regexp_query_flush(ctx,
13883 parsed_strings,
13884 parsed_n_following_characters,
13885 &buffer,
13886 &n_following_characters_start,
13887 &n_following_characters_end);
13888 size_t parsed_n_following_characters_size =
13889 GRN_UINT32_VECTOR_SIZE(parsed_n_following_characters);
13890 if (parsed_n_following_characters_size > 0 &&
13891 (GRN_UINT32_VALUE_AT(parsed_n_following_characters,
13892 parsed_n_following_characters_size - 1) > 0)) {
13893 /* 0 means no limit for now. It may be changed when we implement full
13894 * the number of following characters range support. */
13895 GRN_UINT32_VALUE_AT(parsed_n_following_characters,
13896 parsed_n_following_characters_size - 1) = 0;
13897 GRN_TEXT_SET(ctx,
13898 &buffer,
13899 GRN_TOKENIZER_END_MARK_UTF8,
13900 GRN_TOKENIZER_END_MARK_UTF8_LEN);
13901 grn_ii_parse_regexp_query_flush(ctx,
13902 parsed_strings,
13903 parsed_n_following_characters,
13904 &buffer,
13905 &n_following_characters_start,
13906 &n_following_characters_end);
13907 }
13908 GRN_OBJ_FIN(ctx, &buffer);
13909
13910 return GRN_SUCCESS;
13911 }
13912
13913 typedef struct {
13914 grn_ii_select_cursor *cursor;
13915 uint32_t n_following_characters_start;
13916 uint32_t n_following_characters_end;
13917 uint32_t next_start_pos_offset;
13918 } grn_ii_select_regexp_chunk;
13919
13920 static grn_rc
13921 grn_ii_select_regexp(grn_ctx *ctx,
13922 grn_ii *ii,
13923 const char *string,
13924 unsigned int string_len,
13925 grn_hash *s,
13926 grn_operator op,
13927 grn_select_optarg *optarg)
13928 {
13929 grn_rc rc;
13930 grn_obj parsed_strings;
13931 grn_obj parsed_n_following_characters;
13932 unsigned int n_parsed_strings;
13933
13934 if (string_len == 0) {
13935 return GRN_SUCCESS;
13936 }
13937
13938 GRN_TEXT_INIT(&parsed_strings, GRN_OBJ_VECTOR);
13939 GRN_UINT32_INIT(&parsed_n_following_characters, GRN_OBJ_VECTOR);
13940 rc = grn_ii_parse_regexp_query(ctx,
13941 "[ii][select][regexp]",
13942 string,
13943 string_len,
13944 &parsed_strings,
13945 &parsed_n_following_characters);
13946 if (rc != GRN_SUCCESS) {
13947 GRN_OBJ_FIN(ctx, &parsed_strings);
13948 return rc;
13949 }
13950
13951 if (optarg) {
13952 optarg->mode = GRN_OP_EXACT;
13953 }
13954
13955 n_parsed_strings = grn_vector_size(ctx, &parsed_strings);
13956 if (n_parsed_strings == 1 &&
13957 GRN_UINT32_VALUE_AT(&parsed_n_following_characters, 0) == 0) {
13958 const char *parsed_string;
13959 unsigned int parsed_string_len;
13960 parsed_string_len = grn_vector_get_element(ctx,
13961 &parsed_strings,
13962 0,
13963 &parsed_string,
13964 NULL,
13965 NULL);
13966 rc =
13967 grn_ii_select(ctx, ii, parsed_string, parsed_string_len, s, op, optarg);
13968 } else {
13969 unsigned int i;
13970 bool have_error = false;
13971
13972 auto chunks = static_cast<grn_ii_select_regexp_chunk *>(
13973 GRN_CALLOC(sizeof(grn_ii_select_regexp_chunk) * n_parsed_strings));
13974 for (i = 0; i < n_parsed_strings; i++) {
13975 const char *parsed_string;
13976 unsigned int parsed_string_len;
13977 parsed_string_len = grn_vector_get_element(ctx,
13978 &parsed_strings,
13979 i,
13980 &parsed_string,
13981 NULL,
13982 NULL);
13983 chunks[i].cursor = grn_ii_select_cursor_open(ctx,
13984 ii,
13985 parsed_string,
13986 parsed_string_len,
13987 optarg);
13988 if (!chunks[i].cursor) {
13989 have_error = true;
13990 break;
13991 }
13992 grn_ii_select_cursor_set_per_occurrence_mode(ctx, chunks[i].cursor, true);
13993 chunks[i].n_following_characters_start =
13994 GRN_UINT32_VALUE_AT(&parsed_n_following_characters, i * 2);
13995 chunks[i].n_following_characters_end =
13996 GRN_UINT32_VALUE_AT(&parsed_n_following_characters, i * 2 + 1);
13997 uint32_t next_start_pos_offset = chunks[i].n_following_characters_start;
13998 if (chunks[i].n_following_characters_start > 0) {
13999 size_t n_characters = 0;
14000 const char *current = parsed_string;
14001 const char *parsed_string_end = parsed_string + parsed_string_len;
14002 while (current < parsed_string_end) {
14003 int char_len = grn_charlen(ctx, current, parsed_string_end);
14004 if (char_len == 0) { /* must not happen */
14005 break;
14006 }
14007 current += char_len;
14008 n_characters++;
14009 }
14010 if (n_characters > 1) {
14011 /* text: "abcd", query: "a." case:
14012 * tokens: "ab", "bc", "cd", "d"
14013 * n_characters: 1
14014 * n_following_characters: 1
14015 * There are no token that is ignored after the "ab" token.
14016 *
14017 * text: "abcd", query: "ab." case:
14018 * tokens: "ab", "bc", "cd", "d"
14019 * n_characters: 2
14020 * n_following_characters: 1
14021 * The "bc" token must be ignored because the cursor returns
14022 * the position for the "ab" token.
14023 */
14024 next_start_pos_offset++;
14025 }
14026 next_start_pos_offset++;
14027 }
14028 chunks[i].next_start_pos_offset = next_start_pos_offset;
14029 }
14030
14031 while (!have_error) {
14032 grn_ii_select_cursor_posting *posting;
14033
14034 posting = grn_ii_select_cursor_next(ctx, chunks[0].cursor);
14035 if (!posting) {
14036 break;
14037 }
14038
14039 uint32_t pos = posting->end_pos;
14040 uint32_t n_following_characters_start =
14041 chunks[0].n_following_characters_start;
14042 uint32_t n_following_characters_end =
14043 chunks[0].n_following_characters_end;
14044 uint32_t next_start_pos = pos + chunks[0].next_start_pos_offset;
14045 for (i = 1; i < n_parsed_strings; i++) {
14046 grn_ii_select_cursor_posting *posting_i;
14047
14048 for (;;) {
14049 posting_i = grn_ii_select_cursor_next(ctx, chunks[i].cursor);
14050 if (!posting_i) {
14051 break;
14052 }
14053
14054 if (posting_i->rid > posting->rid) {
14055 grn_ii_select_cursor_unshift(ctx, chunks[i].cursor, posting_i);
14056 break;
14057 }
14058 if (posting_i->sid > posting->sid) {
14059 grn_ii_select_cursor_unshift(ctx, chunks[i].cursor, posting_i);
14060 break;
14061 }
14062 if (posting_i->rid == posting->rid &&
14063 posting_i->sid == posting->sid) {
14064 if (n_following_characters_start == 0) {
14065 if (posting_i->start_pos > pos) {
14066 grn_ii_select_cursor_unshift(ctx, chunks[i].cursor, posting_i);
14067 break;
14068 }
14069 } else {
14070 if (posting_i->start_pos >= next_start_pos) {
14071 grn_ii_select_cursor_unshift(ctx, chunks[i].cursor, posting_i);
14072 break;
14073 }
14074 }
14075 }
14076 }
14077
14078 if (!posting_i) {
14079 break;
14080 }
14081 if (posting_i->rid != posting->rid) {
14082 break;
14083 }
14084 if (posting_i->sid != posting->sid) {
14085 break;
14086 }
14087 if (n_following_characters_start > 0) {
14088 if (n_following_characters_end == 0) { /* 0 means no limit for now. */
14089 if (posting_i->start_pos < next_start_pos) {
14090 break;
14091 }
14092 } else {
14093 if (posting_i->start_pos != next_start_pos) {
14094 break;
14095 }
14096 }
14097 }
14098
14099 pos = posting_i->end_pos;
14100 n_following_characters_start = chunks[i].n_following_characters_start;
14101 n_following_characters_end = chunks[i].n_following_characters_end;
14102 next_start_pos = pos + chunks[i].next_start_pos_offset;
14103 }
14104
14105 if (i == n_parsed_strings && n_following_characters_start == 0) {
14106 grn_rset_posinfo pi = {posting->rid, posting->sid, pos};
14107 double record_score = 1.0;
14108 res_add(ctx, s, &pi, record_score, op);
14109 if (ctx->rc != GRN_SUCCESS) {
14110 rc = ctx->rc;
14111 break;
14112 }
14113 }
14114 }
14115
14116 for (i = 0; i < n_parsed_strings; i++) {
14117 if (chunks[i].cursor) {
14118 grn_ii_select_cursor_close(ctx, chunks[i].cursor);
14119 }
14120 }
14121 GRN_FREE(chunks);
14122 }
14123 GRN_OBJ_FIN(ctx, &parsed_strings);
14124 GRN_OBJ_FIN(ctx, &parsed_n_following_characters);
14125
14126 if (optarg) {
14127 optarg->mode = GRN_OP_REGEXP;
14128 }
14129
14130 return rc;
14131 }
14132
14133 typedef struct {
14134 uint32_t n_occurs;
14135 double score;
14136 } grn_ii_quorum_match_record_data;
14137
14138 extern "C" grn_rc
14139 grn_ii_quorum_match(grn_ctx *ctx, grn_ii *ii, grn_ii_select_data *data)
14140 {
14141 size_t record_key_size;
14142 grn_hash *n_occurs;
14143 grn_token_cursor *token_cursor;
14144 int ii_cursor_flags = 0;
14145
14146 record_key_size = sizeof(grn_id);
14147 if (ii->header.common->flags & GRN_OBJ_WITH_SECTION) {
14148 record_key_size += sizeof(uint32_t);
14149 ii_cursor_flags |= GRN_OBJ_WITH_SECTION;
14150 }
14151
14152 n_occurs = grn_hash_create(ctx,
14153 NULL,
14154 record_key_size,
14155 sizeof(grn_ii_quorum_match_record_data),
14156 0);
14157 if (!n_occurs) {
14158 return GRN_NO_MEMORY_AVAILABLE;
14159 }
14160
14161 token_cursor = grn_ii_select_data_open_token_cursor(ctx,
14162 data,
14163 data->query,
14164 data->query_len,
14165 GRN_TOKENIZE_GET);
14166 if (!token_cursor) {
14167 grn_rc rc = ctx->rc;
14168 char ii_name[GRN_TABLE_MAX_KEY_SIZE];
14169 int ii_name_len;
14170 char errbuf[GRN_CTX_MSGSIZE];
14171
14172 if (rc == GRN_SUCCESS) {
14173 rc = GRN_UNKNOWN_ERROR;
14174 }
14175 ii_name_len =
14176 grn_obj_name(ctx, (grn_obj *)ii, ii_name, GRN_TABLE_MAX_KEY_SIZE);
14177 grn_strcpy(errbuf, GRN_CTX_MSGSIZE, ctx->errbuf);
14178 ERR(rc,
14179 "[ii][quorum-match] failed to create token cursor: <%.*s>: <%.*s>%s%s",
14180 ii_name_len,
14181 ii_name,
14182 data->query_len,
14183 data->query,
14184 errbuf[0] ? ": " : "",
14185 errbuf[0] ? errbuf : "");
14186 grn_hash_close(ctx, n_occurs);
14187 return rc;
14188 }
14189 while (token_cursor->status != GRN_TOKEN_CURSOR_DONE &&
14190 token_cursor->status != GRN_TOKEN_CURSOR_DONE_SKIP) {
14191 grn_id tid;
14192 if ((tid = grn_token_cursor_next(ctx, token_cursor)) != GRN_ID_NIL) {
14193 grn_ii_cursor *cursor;
14194 cursor = grn_ii_cursor_open(ctx,
14195 ii,
14196 tid,
14197 GRN_ID_NIL,
14198 GRN_ID_MAX,
14199 ii->n_elements,
14200 ii_cursor_flags);
14201 while (grn_ii_cursor_next(ctx, cursor)) {
14202 grn_ii_quorum_match_record_data *record_data;
14203
14204 data->rid = cursor->post->rid;
14205 data->sid = cursor->post->sid;
14206 float weight = get_weight(ctx, data);
14207 if (fpclassify(weight) == FP_ZERO) {
14208 continue;
14209 }
14210 if (grn_hash_add(ctx,
14211 n_occurs,
14212 cursor->post,
14213 record_key_size,
14214 (void **)&record_data,
14215 NULL)) {
14216 record_data->n_occurs++;
14217 record_data->score += weight;
14218 }
14219 }
14220 grn_ii_cursor_close(ctx, cursor);
14221 }
14222 }
14223 grn_token_cursor_close(ctx, token_cursor);
14224
14225 {
14226 grn_rset_posinfo posinfo;
14227 grn_hash_cursor *cursor;
14228
14229 memset(&posinfo, 0, sizeof(grn_rset_posinfo));
14230 cursor = grn_hash_cursor_open(ctx, n_occurs, NULL, 0, NULL, 0, 0, -1, 0);
14231 if (!cursor) {
14232 grn_rc rc = ctx->rc;
14233 char ii_name[GRN_TABLE_MAX_KEY_SIZE];
14234 int ii_name_len;
14235 char errbuf[GRN_CTX_MSGSIZE];
14236
14237 if (rc == GRN_SUCCESS) {
14238 rc = GRN_UNKNOWN_ERROR;
14239 }
14240 ii_name_len =
14241 grn_obj_name(ctx, (grn_obj *)ii, ii_name, GRN_TABLE_MAX_KEY_SIZE);
14242 grn_strcpy(errbuf, GRN_CTX_MSGSIZE, ctx->errbuf);
14243 ERR(
14244 rc,
14245 "[ii][quorum-match] failed to create count cursor: <%.*s>: <%.*s>%s%s",
14246 ii_name_len,
14247 ii_name,
14248 data->query_len,
14249 data->query,
14250 errbuf[0] ? ": " : "",
14251 errbuf[0] ? errbuf : "");
14252 grn_hash_close(ctx, n_occurs);
14253 return rc;
14254 }
14255 {
14256 const uint32_t quorum_threshold = data->optarg->quorum_threshold;
14257 while (grn_hash_cursor_next(ctx, cursor) != GRN_ID_NIL) {
14258 grn_posting *posting;
14259 grn_ii_quorum_match_record_data *record_data;
14260
14261 grn_hash_cursor_get_key_value(ctx,
14262 cursor,
14263 (void **)&posting,
14264 NULL,
14265 (void **)&record_data);
14266 if (record_data->n_occurs >= quorum_threshold) {
14267 double score = record_data->score;
14268 grn_memcpy(&posinfo, posting, record_key_size);
14269 if (data->score_func) {
14270 data->record.id = posting->rid;
14271 data->record.weight = (int)(score / record_data->n_occurs);
14272 data->record.n_occurrences = record_data->n_occurs;
14273 data->record.total_term_weights = data->record.weight;
14274 score =
14275 data->score_func(ctx, &(data->record)) * data->record.weight;
14276 }
14277 res_add(ctx, data->result_set, &posinfo, score, data->op);
14278 }
14279 }
14280 }
14281 grn_hash_cursor_close(ctx, cursor);
14282 }
14283 grn_hash_close(ctx, n_occurs);
14284 grn_ii_resolve_sel_and(ctx, data->result_set, data->op);
14285
14286 return GRN_SUCCESS;
14287 }
14288
14289 static bool
14290 grn_ii_select_sequential_search_reference_should_use(grn_ctx *ctx,
14291 grn_ii_select_data *data)
14292 {
14293 int n_sources;
14294
14295 if (grn_ii_select_too_many_index_match_ratio_reference < 0.0) {
14296 return false;
14297 }
14298
14299 if (data->op != GRN_OP_AND) {
14300 return false;
14301 }
14302
14303 if (data->mode != GRN_OP_EXACT) {
14304 return false;
14305 }
14306
14307 n_sources = DB_OBJ(data->ii)->source_size / sizeof(grn_id);
14308 if (n_sources == 0) {
14309 return false;
14310 }
14311
14312 {
14313 grn_obj *tokenizer;
14314 grn_table_get_info(ctx, data->lexicon, NULL, NULL, &tokenizer, NULL, NULL);
14315 if (tokenizer) {
14316 return false;
14317 }
14318 }
14319
14320 {
14321 int i;
14322 auto source_ids = static_cast<grn_id *>(DB_OBJ(data->ii)->source);
14323
14324 for (i = 0; i < n_sources; i++) {
14325 grn_id source_id = source_ids[i];
14326 grn_obj *source;
14327
14328 source = grn_ctx_at(ctx, source_id);
14329 if (!source) {
14330 return false;
14331 }
14332 const bool is_reference_column = grn_obj_is_reference_column(ctx, source);
14333 grn_obj_unref(ctx, source);
14334 if (!is_reference_column) {
14335 return false;
14336 }
14337 }
14338 }
14339
14340 {
14341 uint32_t n_existing_records = GRN_HASH_SIZE(data->result_set);
14342 uint32_t i;
14343 for (i = 0; i < data->n_token_infos; i++) {
14344 token_info *info = data->token_infos[i];
14345 if (n_existing_records <=
14346 (info->size * grn_ii_select_too_many_index_match_ratio_reference)) {
14347 grn_obj reason;
14348 GRN_TEXT_INIT(&reason, 0);
14349 grn_text_printf(
14350 ctx,
14351 &reason,
14352 "enough filtered and "
14353 "index search will match many records: "
14354 "%u <= %.2f: "
14355 "n-existing-records:%u "
14356 "estimated-size:%u "
14357 "ratio:%.2f%%",
14358 n_existing_records,
14359 info->size * grn_ii_select_too_many_index_match_ratio_reference,
14360 n_existing_records,
14361 info->size,
14362 grn_ii_select_too_many_index_match_ratio_reference * 100);
14363 GRN_TEXT_PUTC(ctx, &reason, '\0');
14364 grn_report_index_not_used(ctx,
14365 "[ii][select]",
14366 "[reference]",
14367 (grn_obj *)(data->ii),
14368 GRN_TEXT_VALUE(&reason));
14369 GRN_OBJ_FIN(ctx, &reason);
14370 return true;
14371 }
14372 }
14373 return false;
14374 }
14375 }
14376
14377 static bool
14378 grn_ii_select_sequential_search_reference(grn_ctx *ctx,
14379 grn_ii_select_data *data)
14380 {
14381 const grn_id query_id = data->token_infos[0]->cursors[0].bins[0]->id;
14382 const grn_id lexicon_id = DB_OBJ(data->ii->lexicon)->id;
14383 auto source_ids = static_cast<grn_id *>(DB_OBJ(data->ii)->source);
14384 const size_t n_sources = DB_OBJ(data->ii)->source_size / sizeof(grn_id);
14385 size_t i;
14386 for (i = 0; i < n_sources; i++) {
14387 const grn_id source_id = source_ids[i];
14388 grn_obj *source = grn_ctx_at(ctx, source_id);
14389
14390 grn_obj value;
14391 switch (source->header.flags & GRN_OBJ_COLUMN_TYPE_MASK) {
14392 case GRN_OBJ_COLUMN_SCALAR:
14393 GRN_RECORD_INIT(&value, 0, lexicon_id);
14394 break;
14395 case GRN_OBJ_COLUMN_VECTOR:
14396 GRN_RECORD_INIT(&value, GRN_OBJ_VECTOR, lexicon_id);
14397 break;
14398 default:
14399 grn_obj_unref(ctx, source);
14400 return false;
14401 }
14402
14403 GRN_HASH_EACH_BEGIN(ctx, data->result_set, cursor, id)
14404 {
14405 void *key;
14406 grn_hash_cursor_get_key(ctx, cursor, &key);
14407 grn_id source_table_id = *((grn_id *)key);
14408 GRN_BULK_REWIND(&value);
14409 grn_obj_get_value(ctx, source, source_table_id, &value);
14410 switch (value.header.type) {
14411 case GRN_BULK:
14412 if (GRN_RECORD_VALUE(&value) == query_id) {
14413 grn_rset_posinfo info;
14414 info.rid = source_table_id;
14415 info.sid = i + 1;
14416 info.pos = 0;
14417 data->rid = info.rid;
14418 data->sid = info.sid;
14419 float score = get_weight(ctx, data);
14420 res_add(ctx, data->result_set, &info, score, data->op);
14421 }
14422 break;
14423 case GRN_UVECTOR:
14424 {
14425 uint32_t n_elements = grn_vector_size(ctx, &value);
14426 uint32_t j;
14427 uint32_t n_founds = 0;
14428 for (j = 0; j < n_elements; j++) {
14429 if (GRN_RECORD_VALUE_AT(&value, j) == query_id) {
14430 n_founds++;
14431 }
14432 }
14433 if (n_founds > 0) {
14434 grn_rset_posinfo info;
14435 info.rid = source_table_id;
14436 info.sid = i + 1;
14437 info.pos = 0;
14438 data->rid = info.rid;
14439 data->sid = info.sid;
14440 float score = get_weight(ctx, data);
14441 res_add(ctx, data->result_set, &info, score * n_founds, data->op);
14442 }
14443 }
14444 break;
14445 default:
14446 break;
14447 }
14448 }
14449 GRN_HASH_EACH_END(ctx, cursor);
14450 GRN_OBJ_FIN(ctx, &value);
14451 grn_obj_unref(ctx, source);
14452 }
14453
14454 return true;
14455 }
14456
14457 #ifdef GRN_II_SELECT_ENABLE_SEQUENTIAL_SEARCH_TEXT
14458 static bool
14459 grn_ii_select_sequential_search_text_should_use(grn_ctx *ctx,
14460 grn_ii_select_data *data)
14461 {
14462 if (grn_ii_select_too_many_index_match_ratio_text < 0.0) {
14463 return false;
14464 }
14465
14466 if (data->op != GRN_OP_AND) {
14467 return false;
14468 }
14469
14470 if (data->mode != GRN_OP_EXACT) {
14471 return false;
14472 }
14473
14474 size_t n_sources = DB_OBJ(data->ii)->source_size / sizeof(grn_id);
14475 if (n_sources == 0) {
14476 return false;
14477 }
14478
14479 {
14480 size_t i;
14481 auto source_ids = static_cast<grn_id *>(DB_OBJ(data->ii)->source);
14482
14483 for (i = 0; i < n_sources; i++) {
14484 grn_id source_id = source_ids[i];
14485 grn_obj *source;
14486
14487 source = grn_ctx_at(ctx, source_id);
14488 if (!source) {
14489 return false;
14490 }
14491 grn_id value_type_id;
14492 if (grn_obj_is_table(ctx, source)) {
14493 value_type_id = source->header.domain;
14494 } else {
14495 value_type_id = grn_obj_get_range(ctx, source);
14496 }
14497 const bool is_text_family =
14498 grn_type_id_is_text_family(ctx, value_type_id);
14499 ;
14500 grn_obj_unref(ctx, source);
14501 if (!is_text_family) {
14502 return false;
14503 }
14504 }
14505 }
14506
14507 {
14508 uint32_t n_existing_records = GRN_HASH_SIZE(data->result_set);
14509 uint32_t i;
14510 for (i = 0; i < data->n_token_infos; i++) {
14511 token_info *info = data->token_infos[i];
14512 if (n_existing_records <=
14513 (info->size * grn_ii_select_too_many_index_match_ratio_text)) {
14514 grn_obj reason;
14515 GRN_TEXT_INIT(&reason, 0);
14516 grn_text_printf(ctx,
14517 &reason,
14518 "enough filtered and "
14519 "index search will match many records: "
14520 "%u <= %.2f: "
14521 "n-existing-records:%u "
14522 "estimated-size:%u "
14523 "ratio:%.2f%%",
14524 n_existing_records,
14525 info->size *
14526 grn_ii_select_too_many_index_match_ratio_text,
14527 n_existing_records,
14528 info->size,
14529 grn_ii_select_too_many_index_match_ratio_text * 100);
14530 GRN_TEXT_PUTC(ctx, &reason, '\0');
14531 grn_report_index_not_used(ctx,
14532 "[ii][select]",
14533 "[text]",
14534 (grn_obj *)(data->ii),
14535 GRN_TEXT_VALUE(&reason));
14536 GRN_OBJ_FIN(ctx, &reason);
14537 return true;
14538 }
14539 }
14540 return false;
14541 }
14542 }
14543
14544 static void
14545 grn_ii_select_sequential_search_text_body(grn_ctx *ctx,
14546 grn_ii_select_data *data,
14547 grn_encoding encoding,
14548 OnigRegex regex)
14549 {
14550 grn_obj buffer;
14551 GRN_TEXT_INIT(&buffer, 0);
14552 auto source_ids = static_cast<grn_id *>(DB_OBJ(data->ii)->source);
14553 const size_t n_sources = DB_OBJ(data->ii)->source_size / sizeof(grn_id);
14554 size_t i;
14555 for (i = 0; i < n_sources; i++) {
14556 const grn_id source_id = source_ids[i];
14557 grn_obj *source = grn_ctx_at(ctx, source_id);
14558 const bool source_is_table = grn_obj_is_table(ctx, source);
14559 GRN_HASH_EACH_BEGIN(ctx, data->result_set, cursor, id)
14560 {
14561 void *key;
14562 grn_hash_cursor_get_key(ctx, cursor, &key);
14563 grn_id source_table_id = *((grn_id *)key);
14564 GRN_BULK_REWIND(&buffer);
14565 if (source_is_table) {
14566 grn_table_get_key2(ctx, source, source_table_id, &buffer);
14567 } else {
14568 grn_obj_get_value(ctx, source, source_table_id, &buffer);
14569 }
14570
14571 OnigPosition position;
14572 grn_obj *value;
14573 const char *normalized_value;
14574 unsigned int normalized_value_length;
14575 value = grn_string_open_(ctx,
14576 GRN_TEXT_VALUE(&buffer),
14577 GRN_TEXT_LEN(&buffer),
14578 data->ii->lexicon,
14579 0,
14580 encoding);
14581 grn_string_get_normalized(ctx,
14582 value,
14583 &normalized_value,
14584 &normalized_value_length,
14585 NULL);
14586 const OnigUChar *onig_value =
14587 reinterpret_cast<const OnigUChar *>(normalized_value);
14588 position = onig_search(regex,
14589 onig_value,
14590 onig_value + normalized_value_length,
14591 onig_value,
14592 onig_value + normalized_value_length,
14593 NULL,
14594 0);
14595 if (position != ONIG_MISMATCH) {
14596 grn_rset_posinfo info;
14597 info.rid = source_table_id;
14598 info.sid = i + 1;
14599 info.pos = 0;
14600 data->rid = info.rid;
14601 data->sid = info.rid;
14602 float score = get_weight(ctx, data);
14603 res_add(ctx, data->result_set, &info, score, data->op);
14604 }
14605 grn_obj_unlink(ctx, value);
14606 }
14607 GRN_HASH_EACH_END(ctx, cursor);
14608 grn_obj_unref(ctx, source);
14609 }
14610 GRN_OBJ_FIN(ctx, &buffer);
14611 }
14612
14613 static bool
14614 grn_ii_select_sequential_search_text(grn_ctx *ctx, grn_ii_select_data *data)
14615 {
14616 bool processed = false;
14617
14618 {
14619 grn_encoding encoding;
14620 grn_table_get_info(ctx,
14621 data->ii->lexicon,
14622 NULL,
14623 &encoding,
14624 NULL,
14625 NULL,
14626 NULL);
14627 int nflags = 0;
14628 grn_obj *query = grn_string_open_(ctx,
14629 data->query,
14630 data->query_len,
14631 data->ii->lexicon,
14632 nflags,
14633 encoding);
14634 const char *normalized_query;
14635 unsigned int normalized_query_length;
14636 grn_string_get_normalized(ctx,
14637 query,
14638 &normalized_query,
14639 &normalized_query_length,
14640 NULL);
14641 {
14642 OnigRegex regex;
14643 regex = grn_onigmo_new(ctx,
14644 normalized_query,
14645 normalized_query_length,
14646 ONIG_OPTION_NONE,
14647 ONIG_SYNTAX_ASIS,
14648 "[ii][select][sequential]");
14649 if (regex) {
14650 grn_ii_select_sequential_search_text_body(ctx, data, encoding, regex);
14651 onig_free(regex);
14652 processed = true;
14653 } else {
14654 processed = false;
14655 }
14656 }
14657 grn_obj_unlink(ctx, query);
14658 }
14659
14660 return processed;
14661 }
14662 #endif
14663
14664 static bool
14665 grn_ii_select_sequential_search(grn_ctx *ctx, grn_ii_select_data *data)
14666 {
14667 if (grn_ii_select_sequential_search_reference_should_use(ctx, data)) {
14668 return grn_ii_select_sequential_search_reference(ctx, data);
14669 }
14670 #ifdef GRN_II_SELECT_ENABLE_SEQUENTIAL_SEARCH_TEXT
14671 else if (grn_ii_select_sequential_search_text_should_use(ctx, data)) {
14672 return grn_ii_select_sequential_search_text(ctx, data);
14673 }
14674 #endif
14675
14676 return false;
14677 }
14678
14679 extern "C" grn_rc
14680 grn_ii_select(grn_ctx *ctx,
14681 grn_ii *ii,
14682 const char *string,
14683 unsigned int string_len,
14684 grn_hash *s,
14685 grn_operator op,
14686 grn_select_optarg *optarg)
14687 {
14688 const char *tag = "[ii][select]";
14689 int rep, orp;
14690
14691 if (!ii) {
14692 return GRN_INVALID_ARGUMENT;
14693 }
14694
14695 grn_ii_select_cursor cursor;
14696 grn_ii_select_data *data;
14697 data = &(cursor.data);
14698 data->ii = ii;
14699 data->lexicon = data->ii->lexicon;
14700 if (!data->lexicon || !s) {
14701 return GRN_INVALID_ARGUMENT;
14702 }
14703
14704 grn_selector_data_current_set_default_tag_raw(ctx, string, string_len);
14705
14706 data->query = string;
14707 data->query_len = string_len;
14708 data->result_set = s;
14709 data->op = op;
14710 grn_ii_select_data_init(ctx, data, optarg);
14711 if (data->mode == GRN_OP_SIMILAR) {
14712 grn_rc rc = grn_ii_similar_search_internal(ctx, data);
14713 grn_ii_select_data_fin(ctx, data);
14714 return rc;
14715 }
14716 if (data->mode == GRN_OP_TERM_EXTRACT) {
14717 grn_rc rc = grn_ii_term_extract_internal(ctx, data);
14718 grn_ii_select_data_fin(ctx, data);
14719 return rc;
14720 }
14721 if (data->mode == GRN_OP_REGEXP) {
14722 grn_rc rc =
14723 grn_ii_select_regexp(ctx, ii, string, string_len, s, op, optarg);
14724 grn_ii_select_data_fin(ctx, data);
14725 return rc;
14726 }
14727 if (data->mode == GRN_OP_QUORUM) {
14728 grn_rc rc = grn_ii_quorum_match(ctx, ii, data);
14729 grn_ii_select_data_fin(ctx, data);
14730 return rc;
14731 }
14732 /* todo : support subrec
14733 rep = (s->record_unit == GRN_REC_POSITION || s->subrec_unit ==
14734 GRN_REC_POSITION); orp = (s->record_unit == GRN_REC_POSITION || op ==
14735 GRN_OP_OR);
14736 */
14737 rep = 0;
14738 orp = op == GRN_OP_OR;
14739 if (!grn_ii_select_data_init_token_infos(ctx, data, tag)) {
14740 goto exit;
14741 }
14742 if (grn_logger_pass(ctx, GRN_LOG_INFO)) {
14743 if (grn_type_id_is_text_family(ctx, ii->lexicon->header.domain)) {
14744 GRN_LOG(ctx,
14745 GRN_LOG_INFO,
14746 "%s n=%d (%.*s)",
14747 tag,
14748 data->n_token_infos,
14749 string_len,
14750 string);
14751 } else {
14752 grn_obj inspected;
14753 GRN_TEXT_INIT(&inspected, 0);
14754 grn_inspect_key(ctx, &inspected, ii->lexicon, string, string_len);
14755 GRN_LOG(ctx,
14756 GRN_LOG_INFO,
14757 "%s n=%d (%.*s)",
14758 tag,
14759 data->n_token_infos,
14760 (int)GRN_TEXT_LEN(&inspected),
14761 GRN_TEXT_VALUE(&inspected));
14762 GRN_OBJ_FIN(ctx, &inspected);
14763 }
14764 }
14765 /* todo : array as result
14766 if (n == 1 && (*tis)->cursors->n_entries == 1 && op == GRN_OP_OR
14767 && !GRN_HASH_SIZE(s) && !s->garbages
14768 && s->record_unit == GRN_REC_DOCUMENT && !s->max_n_subrecs
14769 && grn_ii_max_section(ii) == 1) {
14770 grn_ii_cursor *c = (*tis)->cursors->bins[0];
14771 if ((rc = grn_hash_array_init(s, (*tis)->size + 32768))) { goto exit; }
14772 do {
14773 grn_rset_recinfo *ri;
14774 grn_posting *p = c->post;
14775 if ((weight = get_weight(ctx, s, p->rid, p->sid, wvm, optarg))) {
14776 GRN_HASH_INT_ADD(s, p, ri);
14777 ri->score = (p->tf + p->score) * weight;
14778 ri->n_subrecs = 1;
14779 }
14780 } while (grn_ii_cursor_next(ctx, c));
14781 goto exit;
14782 }
14783 */
14784 if (grn_ii_select_sequential_search(ctx, data)) {
14785 goto exit;
14786 }
14787
14788 grn_ii_select_cursor_init_internal(ctx, &cursor);
14789 grn_result_set_add_ii_select_cursor(ctx, s, &cursor, op);
14790
14791 exit:
14792 if (!data->only_skip_token) {
14793 grn_ii_resolve_sel_and(ctx, s, op);
14794 }
14795
14796 grn_ii_select_data_fin(ctx, data);
14797
14798 // grn_hash_cursor_clear(r);
14799 #ifdef DEBUG
14800 {
14801 uint32_t i;
14802 uint32_t n_segments = ii->seg->header->max_segment;
14803 uint32_t n_nrefs = 0;
14804 grn_io_mapinfo *info = ii->seg->maps;
14805 for (i = 0; i < n_segments; i++, info++) {
14806 if (info->nref > 0) {
14807 n_nrefs++;
14808 }
14809 }
14810 GRN_LOG(ctx, GRN_LOG_INFO, "n_nrefs=%u", n_nrefs);
14811 }
14812 #endif /* DEBUG */
14813 return ctx->rc;
14814 }
14815
14816 static void
14817 grn_select_optarg_init_by_search_optarg(grn_ctx *ctx,
14818 grn_select_optarg *select_optarg,
14819 grn_search_optarg *search_optarg)
14820 {
14821 memset(select_optarg, 0, sizeof(grn_select_optarg));
14822 select_optarg->mode = GRN_OP_EXACT;
14823 if (!search_optarg) {
14824 return;
14825 }
14826
14827 switch (search_optarg->mode) {
14828 case GRN_OP_NEAR:
14829 case GRN_OP_NEAR_NO_OFFSET:
14830 select_optarg->mode = search_optarg->mode;
14831 select_optarg->max_interval = search_optarg->max_interval;
14832 select_optarg->max_element_intervals = search_optarg->max_element_intervals;
14833 select_optarg->min_interval = search_optarg->min_interval
14834 ? *search_optarg->min_interval
14835 : GRN_II_DEFAULT_NEAR_MIN_INTERVAL;
14836 break;
14837 case GRN_OP_NEAR_PHRASE:
14838 case GRN_OP_ORDERED_NEAR_PHRASE:
14839 case GRN_OP_NEAR_PHRASE_PRODUCT:
14840 case GRN_OP_ORDERED_NEAR_PHRASE_PRODUCT:
14841 select_optarg->mode = search_optarg->mode;
14842 select_optarg->max_interval = search_optarg->max_interval;
14843 select_optarg->additional_last_interval =
14844 search_optarg->additional_last_interval;
14845 select_optarg->max_element_intervals = search_optarg->max_element_intervals;
14846 select_optarg->min_interval = search_optarg->min_interval
14847 ? *search_optarg->min_interval
14848 : GRN_II_DEFAULT_NEAR_MIN_INTERVAL;
14849 break;
14850 case GRN_OP_SIMILAR:
14851 select_optarg->mode = search_optarg->mode;
14852 select_optarg->similarity_threshold = search_optarg->similarity_threshold;
14853 break;
14854 case GRN_OP_REGEXP:
14855 select_optarg->mode = search_optarg->mode;
14856 break;
14857 case GRN_OP_FUZZY:
14858 select_optarg->mode = search_optarg->mode;
14859 select_optarg->fuzzy = search_optarg->fuzzy;
14860 break;
14861 case GRN_OP_QUORUM:
14862 select_optarg->mode = search_optarg->mode;
14863 select_optarg->quorum_threshold = search_optarg->quorum_threshold;
14864 break;
14865 default:
14866 break;
14867 }
14868 if (search_optarg->vector_size != 0) {
14869 select_optarg->weight_vector = search_optarg->weight_vector;
14870 select_optarg->weight_vector_float = search_optarg->weight_vector_float;
14871 select_optarg->vector_size = search_optarg->vector_size;
14872 select_optarg->weight_float = search_optarg->weight_float;
14873 }
14874 select_optarg->scorer = search_optarg->scorer;
14875 select_optarg->scorer_args_expr = search_optarg->scorer_args_expr;
14876 select_optarg->scorer_args_expr_offset =
14877 search_optarg->scorer_args_expr_offset;
14878 select_optarg->fuzzy = search_optarg->fuzzy;
14879 select_optarg->match_info = &(search_optarg->match_info);
14880 select_optarg->query_options = search_optarg->query_options;
14881 if (search_optarg->query_domain) {
14882 select_optarg->query_domain = *(search_optarg->query_domain);
14883 } else {
14884 select_optarg->query_domain = GRN_ID_NIL;
14885 }
14886 }
14887
14888 static uint32_t
14889 grn_ii_estimate_size_for_query_regexp(grn_ctx *ctx,
14890 grn_ii *ii,
14891 const char *query,
14892 unsigned int query_len,
14893 grn_search_optarg *optarg)
14894 {
14895 grn_rc rc;
14896 grn_obj parsed_strings;
14897 grn_obj parsed_n_following_characters;
14898 uint32_t size;
14899
14900 GRN_TEXT_INIT(&parsed_strings, GRN_OBJ_VECTOR);
14901 GRN_UINT32_INIT(&parsed_n_following_characters, GRN_OBJ_VECTOR);
14902 rc = grn_ii_parse_regexp_query(ctx,
14903 "[ii][estimate-size][query][regexp]",
14904 query,
14905 query_len,
14906 &parsed_strings,
14907 &parsed_n_following_characters);
14908 if (rc != GRN_SUCCESS) {
14909 GRN_OBJ_FIN(ctx, &parsed_strings);
14910 return 0;
14911 }
14912
14913 if (optarg) {
14914 optarg->mode = GRN_OP_EXACT;
14915 }
14916
14917 unsigned int i;
14918 unsigned int n_parsed_strings = grn_vector_size(ctx, &parsed_strings);
14919 for (i = 0; i < n_parsed_strings; i++) {
14920 const char *parsed_string;
14921 unsigned int parsed_string_len;
14922 parsed_string_len = grn_vector_get_element(ctx,
14923 &parsed_strings,
14924 0,
14925 &parsed_string,
14926 NULL,
14927 NULL);
14928 size_t estimated_size = grn_ii_estimate_size_for_query(ctx,
14929 ii,
14930 parsed_string,
14931 parsed_string_len,
14932 optarg);
14933 if (i == 0) {
14934 size = estimated_size;
14935 } else {
14936 if (estimated_size < size) {
14937 size = estimated_size;
14938 }
14939 }
14940 }
14941 GRN_OBJ_FIN(ctx, &parsed_strings);
14942
14943 if (optarg) {
14944 optarg->mode = GRN_OP_REGEXP;
14945 }
14946
14947 return size;
14948 }
14949
14950 extern "C" uint32_t
14951 grn_ii_estimate_size_for_query(grn_ctx *ctx,
14952 grn_ii *ii,
14953 const char *query,
14954 unsigned int query_len,
14955 grn_search_optarg *optarg)
14956 {
14957 const char *tag = "[ii][estimate][size][query]";
14958
14959 if (query_len == 0) {
14960 return 0;
14961 }
14962
14963 grn_select_optarg select_optarg;
14964 grn_select_optarg_init_by_search_optarg(ctx, &select_optarg, optarg);
14965
14966 grn_ii_select_data data;
14967 data.ii = ii;
14968 data.lexicon = data.ii->lexicon;
14969 data.query = query;
14970 data.query_len = query_len;
14971 grn_ii_select_data_init(ctx, &data, &select_optarg);
14972 if (data.mode == GRN_OP_REGEXP) {
14973 grn_ii_select_data_fin(ctx, &data);
14974 return grn_ii_estimate_size_for_query_regexp(ctx,
14975 ii,
14976 query,
14977 query_len,
14978 optarg);
14979 }
14980
14981 if (!grn_ii_select_data_init_token_infos(ctx, &data, tag)) {
14982 grn_ii_select_data_fin(ctx, &data);
14983 return 0;
14984 }
14985
14986 uint32_t i;
14987 double estimated_size = 0;
14988 double normalized_ratio = 1.0;
14989 for (i = 0; i < data.n_token_infos; i++) {
14990 token_info *ti = data.token_infos[i];
14991 double term_estimated_size;
14992 term_estimated_size = ((double)ti->size / ti->ntoken);
14993 if (i == 0) {
14994 estimated_size = term_estimated_size;
14995 } else {
14996 if (term_estimated_size < estimated_size) {
14997 estimated_size = term_estimated_size;
14998 }
14999 normalized_ratio *= grn_ii_estimate_size_for_query_reduce_ratio;
15000 }
15001 }
15002
15003 estimated_size *= normalized_ratio;
15004 if (estimated_size > 0.0 && estimated_size < 1.0) {
15005 estimated_size = 1.0;
15006 }
15007
15008 grn_ii_select_data_fin(ctx, &data);
15009
15010 return (uint32_t)estimated_size;
15011 }
15012
15013 extern "C" uint32_t
15014 grn_ii_estimate_size_for_lexicon_cursor(grn_ctx *ctx,
15015 grn_ii *ii,
15016 grn_table_cursor *lexicon_cursor)
15017 {
15018 grn_id term_id;
15019 uint32_t estimated_size = 0;
15020
15021 while ((term_id = grn_table_cursor_next(ctx, lexicon_cursor)) != GRN_ID_NIL) {
15022 uint32_t term_estimated_size;
15023 term_estimated_size = grn_ii_estimate_size(ctx, ii, term_id);
15024 estimated_size += term_estimated_size;
15025 }
15026
15027 return estimated_size;
15028 }
15029
15030 extern "C" grn_rc
15031 grn_ii_sel(grn_ctx *ctx,
15032 grn_ii *ii,
15033 const char *string,
15034 unsigned int string_len,
15035 grn_hash *s,
15036 grn_operator op,
15037 grn_search_optarg *optarg)
15038 {
15039 ERRCLR(ctx);
15040 if (grn_logger_pass(ctx, GRN_LOG_INFO)) {
15041 grn_id query_domain = GRN_ID_NIL;
15042 if (optarg && optarg->query_domain) {
15043 query_domain = *(optarg->query_domain);
15044 }
15045 if (query_domain == GRN_ID_NIL) {
15046 query_domain = ii->lexicon->header.domain;
15047 }
15048 if (grn_type_id_is_text_family(ctx, query_domain)) {
15049 GRN_LOG(ctx, GRN_LOG_INFO, "grn_ii_sel > (%.*s)", string_len, string);
15050 } else {
15051 grn_obj inspected;
15052 GRN_TEXT_INIT(&inspected, 0);
15053 if (query_domain == ii->lexicon->header.domain) {
15054 grn_inspect_key(ctx, &inspected, ii->lexicon, string, string_len);
15055 } else {
15056 grn_obj query;
15057 GRN_OBJ_INIT(&query, GRN_BULK, GRN_OBJ_DO_SHALLOW_COPY, query_domain);
15058 GRN_TEXT_SET(ctx, &query, string, string_len);
15059 grn_inspect(ctx, &inspected, &query);
15060 GRN_OBJ_FIN(ctx, &query);
15061 }
15062 GRN_LOG(ctx,
15063 GRN_LOG_INFO,
15064 "grn_ii_sel > (%.*s)",
15065 (int)GRN_TEXT_LEN(&inspected),
15066 GRN_TEXT_VALUE(&inspected));
15067 GRN_OBJ_FIN(ctx, &inspected);
15068 }
15069 }
15070 if (!s) {
15071 return GRN_INVALID_ARGUMENT;
15072 }
15073 uint16_t start_depth = grn_ctx_trace_log_get_current_depth(ctx);
15074 grn_ctx_trace_log_push(ctx);
15075 grn_ctx_trace_log_emit_string(ctx, "ii.select.input", string, string_len);
15076 grn_ctx_trace_log_emit_cstring(ctx,
15077 "ii.select.operator",
15078 grn_operator_to_string(op));
15079 {
15080 grn_select_optarg arg;
15081 grn_select_optarg_init_by_search_optarg(ctx, &arg, optarg);
15082 /* todo : support subrec
15083 grn_rset_init(ctx, s, GRN_REC_DOCUMENT, 0, GRN_REC_NONE, 0, 0);
15084 */
15085 grn_ctx_trace_log_push(ctx);
15086 if (grn_ii_select(ctx, ii, string, string_len, s, op, &arg)) {
15087 GRN_LOG(ctx, GRN_LOG_ERROR, "grn_ii_select on grn_ii_sel() failed!");
15088 goto exit;
15089 }
15090 GRN_LOG(ctx, GRN_LOG_INFO, "exact: %d", GRN_HASH_SIZE(s));
15091 grn_ctx_trace_log_emit_uint32(ctx,
15092 "ii.select.exact.n_hits",
15093 GRN_HASH_SIZE(s));
15094 grn_ctx_trace_log_pop(ctx);
15095 if (op == GRN_OP_OR || ctx->impl->force_match_escalation) {
15096 grn_id min = GRN_ID_NIL;
15097 if (((int64_t)GRN_HASH_SIZE(s) <= ctx->impl->match_escalation_threshold ||
15098 ctx->impl->force_match_escalation) &&
15099 ((arg.fuzzy.flags & GRN_TABLE_FUZZY_SEARCH_USE_MAX_DISTANCE_RATIO)
15100 ? (arg.fuzzy.max_distance_ratio > FLT_EPSILON)
15101 : (arg.fuzzy.max_distance > 0))) {
15102 arg.mode = GRN_OP_FUZZY;
15103 if (arg.match_info) {
15104 if (arg.match_info->flags & GRN_MATCH_INFO_GET_MIN_RECORD_ID) {
15105 min = arg.match_info->min;
15106 arg.match_info->min = GRN_ID_NIL;
15107 }
15108 }
15109 grn_ctx_trace_log_push(ctx);
15110 if (grn_ii_select(ctx, ii, string, string_len, s, op, &arg)) {
15111 GRN_LOG(ctx,
15112 GRN_LOG_ERROR,
15113 "grn_ii_select on grn_ii_sel(fuzzy) failed!");
15114 goto exit;
15115 }
15116 GRN_LOG(ctx, GRN_LOG_INFO, "fuzzy: %d", GRN_HASH_SIZE(s));
15117 grn_ctx_trace_log_emit_uint32(ctx,
15118 "ii.select.fuzzy.n_hits",
15119 GRN_HASH_SIZE(s));
15120 grn_ctx_trace_log_pop(ctx);
15121 if (arg.match_info) {
15122 if (arg.match_info->flags & GRN_MATCH_INFO_GET_MIN_RECORD_ID) {
15123 if (min > GRN_ID_NIL && min < arg.match_info->min) {
15124 arg.match_info->min = min;
15125 }
15126 }
15127 }
15128 }
15129 if ((int64_t)GRN_HASH_SIZE(s) <= ctx->impl->match_escalation_threshold ||
15130 ctx->impl->force_match_escalation) {
15131 arg.mode = GRN_OP_UNSPLIT;
15132 if (arg.match_info) {
15133 if (arg.match_info->flags & GRN_MATCH_INFO_GET_MIN_RECORD_ID) {
15134 min = arg.match_info->min;
15135 arg.match_info->min = GRN_ID_NIL;
15136 }
15137 }
15138 if (grn_ii_select(ctx, ii, string, string_len, s, op, &arg)) {
15139 GRN_LOG(ctx,
15140 GRN_LOG_ERROR,
15141 "grn_ii_select on grn_ii_sel(unsplit) failed!");
15142 goto exit;
15143 }
15144 GRN_LOG(ctx, GRN_LOG_INFO, "unsplit: %d", GRN_HASH_SIZE(s));
15145 grn_ctx_trace_log_emit_uint32(ctx,
15146 "ii.select.unsplit.n_hits",
15147 GRN_HASH_SIZE(s));
15148 grn_ctx_trace_log_pop(ctx);
15149 if (arg.match_info) {
15150 if (arg.match_info->flags & GRN_MATCH_INFO_GET_MIN_RECORD_ID) {
15151 if (min > GRN_ID_NIL && min < arg.match_info->min) {
15152 arg.match_info->min = min;
15153 }
15154 }
15155 }
15156 }
15157 if ((int64_t)GRN_HASH_SIZE(s) <= ctx->impl->match_escalation_threshold ||
15158 ctx->impl->force_match_escalation) {
15159 arg.mode = GRN_OP_PARTIAL;
15160 if (arg.match_info) {
15161 if (arg.match_info->flags & GRN_MATCH_INFO_GET_MIN_RECORD_ID) {
15162 min = arg.match_info->min;
15163 arg.match_info->min = GRN_ID_NIL;
15164 }
15165 }
15166 grn_ctx_trace_log_push(ctx);
15167 if (grn_ii_select(ctx, ii, string, string_len, s, op, &arg)) {
15168 GRN_LOG(ctx,
15169 GRN_LOG_ERROR,
15170 "grn_ii_select on grn_ii_sel(partial) failed!");
15171 goto exit;
15172 }
15173 GRN_LOG(ctx, GRN_LOG_INFO, "partial: %d", GRN_HASH_SIZE(s));
15174 grn_ctx_trace_log_emit_uint32(ctx,
15175 "ii.select.partial.n_hits",
15176 GRN_HASH_SIZE(s));
15177 grn_ctx_trace_log_pop(ctx);
15178 if (arg.match_info) {
15179 if (arg.match_info->flags & GRN_MATCH_INFO_GET_MIN_RECORD_ID) {
15180 if (min > GRN_ID_NIL && min < arg.match_info->min) {
15181 arg.match_info->min = min;
15182 }
15183 }
15184 }
15185 }
15186 }
15187 GRN_LOG(ctx, GRN_LOG_INFO, "hits=%d", GRN_HASH_SIZE(s));
15188 grn_ctx_trace_log_emit_uint32(ctx, "ii.select.n_hits", GRN_HASH_SIZE(s));
15189 grn_ctx_trace_log_pop(ctx);
15190 }
15191 exit:
15192 grn_ctx_trace_log_set_current_depth(ctx, start_depth);
15193 return ctx->rc;
15194 }
15195
15196 extern "C" grn_rc
15197 grn_ii_select_by_id(
15198 grn_ctx *ctx, grn_ii *ii, grn_id id, grn_hash *result_set, grn_operator op)
15199 {
15200 GRN_API_ENTER;
15201 grn_rc rc = grn_ii_at(ctx, ii, id, result_set, op);
15202 GRN_API_RETURN(rc);
15203 }
15204
15205 extern "C" grn_rc
15206 grn_ii_at(grn_ctx *ctx, grn_ii *ii, grn_id id, grn_hash *s, grn_operator op)
15207 {
15208 int rep = 0;
15209 grn_ii_cursor *c;
15210 if ((c = grn_ii_cursor_open(ctx,
15211 ii,
15212 id,
15213 GRN_ID_NIL,
15214 GRN_ID_MAX,
15215 rep ? ii->n_elements : ii->n_elements - 1,
15216 0))) {
15217 grn_result_set_add_ii_cursor(ctx, s, c, 1, 1, op);
15218 grn_ii_cursor_close(ctx, c);
15219 }
15220 return ctx->rc;
15221 }
15222
15223 extern "C" void
15224 grn_ii_resolve_sel_and(grn_ctx *ctx, grn_hash *s, grn_operator op)
15225 {
15226 if (op == GRN_OP_AND &&
15227 !(ctx->flags & GRN_CTX_TEMPORARY_DISABLE_II_RESOLVE_SEL_AND)) {
15228 grn_id eid;
15229 grn_rset_recinfo *ri;
15230 grn_hash_cursor *c =
15231 grn_hash_cursor_open(ctx, s, NULL, 0, NULL, 0, 0, -1, 0);
15232 if (c) {
15233 while ((eid = grn_hash_cursor_next(ctx, c))) {
15234 grn_hash_cursor_get_value(ctx, c, (void **)&ri);
15235 if ((ri->n_subrecs & GRN_RSET_UTIL_BIT)) {
15236 ri->n_subrecs &= ~GRN_RSET_UTIL_BIT;
15237 } else {
15238 grn_hash_delete_by_id(ctx, s, eid, NULL);
15239 }
15240 }
15241 grn_hash_cursor_close(ctx, c);
15242 }
15243 }
15244 }
15245
15246 extern "C" void
15247 grn_ii_cursor_inspect(grn_ctx *ctx, grn_ii_cursor *c, grn_obj *buf)
15248 {
15249 grn_obj key_buf;
15250 char key[GRN_TABLE_MAX_KEY_SIZE];
15251 int key_size;
15252 int i = 0;
15253 grn_ii_cursor_next_options options = {/* .include_garbage = */ true};
15254
15255 GRN_TEXT_PUTS(ctx, buf, " #<");
15256 key_size =
15257 grn_table_get_key(ctx, c->ii->lexicon, c->id, key, GRN_TABLE_MAX_KEY_SIZE);
15258 GRN_OBJ_INIT(&key_buf, GRN_BULK, 0, c->ii->lexicon->header.domain);
15259 GRN_TEXT_SET(ctx, &key_buf, key, key_size);
15260 grn_inspect(ctx, buf, &key_buf);
15261 GRN_OBJ_FIN(ctx, &key_buf);
15262
15263 GRN_TEXT_PUTS(ctx, buf, "\n elements:[\n ");
15264 while (grn_ii_cursor_next_internal(ctx, c, &options)) {
15265 grn_posting *pos = c->post;
15266 if (i > 0) {
15267 GRN_TEXT_PUTS(ctx, buf, ",\n ");
15268 }
15269 i++;
15270 GRN_TEXT_PUTS(ctx, buf, "{status:");
15271 if (pos->tf && pos->sid) {
15272 GRN_TEXT_PUTS(ctx, buf, "available");
15273 } else {
15274 GRN_TEXT_PUTS(ctx, buf, "garbage");
15275 }
15276 GRN_TEXT_PUTS(ctx, buf, ", rid:");
15277 grn_text_lltoa(ctx, buf, pos->rid);
15278 GRN_TEXT_PUTS(ctx, buf, ", sid:");
15279 grn_text_lltoa(ctx, buf, pos->sid);
15280 GRN_TEXT_PUTS(ctx, buf, ", pos:");
15281 grn_text_lltoa(ctx, buf, pos->pos);
15282 GRN_TEXT_PUTS(ctx, buf, ", tf:");
15283 grn_text_lltoa(ctx, buf, pos->tf);
15284 GRN_TEXT_PUTS(ctx, buf, ", weight:");
15285 grn_text_f32toa(ctx, buf, grn_posting_get_weight_float(ctx, pos));
15286 GRN_TEXT_PUTS(ctx, buf, ", rest:");
15287 grn_text_lltoa(ctx, buf, pos->rest);
15288 GRN_TEXT_PUTS(ctx, buf, "}");
15289 }
15290 GRN_TEXT_PUTS(ctx, buf, "\n ]\n >");
15291 }
15292
15293 extern "C" void
15294 grn_ii_inspect_values(grn_ctx *ctx, grn_ii *ii, grn_obj *buf)
15295 {
15296 grn_table_cursor *tc;
15297 GRN_TEXT_PUTS(ctx, buf, "[");
15298 if ((tc = grn_table_cursor_open(ctx,
15299 ii->lexicon,
15300 NULL,
15301 0,
15302 NULL,
15303 0,
15304 0,
15305 -1,
15306 GRN_CURSOR_ASCENDING))) {
15307 int i = 0;
15308 grn_id tid;
15309 grn_ii_cursor *c;
15310 while ((tid = grn_table_cursor_next(ctx, tc))) {
15311 if (i > 0) {
15312 GRN_TEXT_PUTS(ctx, buf, ",");
15313 }
15314 i++;
15315 GRN_TEXT_PUTS(ctx, buf, "\n");
15316 if ((c = grn_ii_cursor_open(ctx,
15317 ii,
15318 tid,
15319 GRN_ID_NIL,
15320 GRN_ID_MAX,
15321 ii->n_elements,
15322 GRN_OBJ_WITH_POSITION |
15323 GRN_OBJ_WITH_SECTION))) {
15324 grn_ii_cursor_inspect(ctx, c, buf);
15325 grn_ii_cursor_close(ctx, c);
15326 }
15327 }
15328 grn_table_cursor_close(ctx, tc);
15329 }
15330 GRN_TEXT_PUTS(ctx, buf, "]");
15331 }
15332
15333 /********************** buffered index builder ***********************/
15334
15335 typedef struct {
15336 unsigned int sid; /* Section ID */
15337 uint32_t weight; /* Weight */
15338 const char *p; /* Value address */
15339 uint32_t len; /* Value length */
15340 char *buf; /* Buffer address */
15341 uint32_t cap; /* Buffer size */
15342 } ii_buffer_value;
15343
15344 /* ii_buffer_counter is associated with a combination of a block an a term. */
15345 typedef struct {
15346 uint32_t nrecs; /* Number of records or sections */
15347 uint32_t nposts; /* Number of occurrences */
15348
15349 /* Information of the last value */
15350 grn_id last_rid; /* Record ID */
15351 uint32_t last_sid; /* Section ID */
15352 uint32_t last_tf; /* Term frequency */
15353 uint32_t last_weight; /* Total weight */
15354 uint32_t last_pos; /* Token position */
15355
15356 /* Meaning of offset_* is different before/after encoding. */
15357 /* Before encoding: size in encoded sequence */
15358 /* After encoding: Offset in encoded sequence */
15359 uint32_t offset_rid; /* Record ID */
15360 uint32_t offset_sid; /* Section ID */
15361 uint32_t offset_tf; /* Term frequency */
15362 uint32_t offset_weight; /* Weight */
15363 uint32_t offset_pos; /* Token position */
15364 } ii_buffer_counter;
15365
15366 typedef struct {
15367 off64_t head;
15368 off64_t tail;
15369 uint32_t nextsize;
15370 uint8_t *buffer;
15371 uint32_t buffersize;
15372 uint8_t *bufcur;
15373 uint32_t rest;
15374 grn_id tid;
15375 uint32_t nrecs;
15376 uint32_t nposts;
15377 grn_id *recs;
15378 uint32_t *tfs;
15379 uint32_t *posts;
15380 } ii_buffer_block;
15381
15382 struct _grn_ii_buffer {
15383 grn_obj *lexicon; /* Global lexicon */
15384 grn_obj *tmp_lexicon; /* Temporary lexicon for each block */
15385 ii_buffer_block *blocks; /* Blocks */
15386 uint32_t nblocks; /* Number of blocks */
15387 int tmpfd; /* Descriptor of temporary file */
15388 char tmpfpath[PATH_MAX]; /* Path of temporary file */
15389 uint64_t update_buffer_size;
15390
15391 // stuff for parsing
15392 off64_t filepos; /* Write position of temporary file */
15393 grn_id *block_buf; /* Buffer for the current block */
15394 size_t block_buf_size; /* Size of block_buf */
15395 size_t block_pos; /* Write position of block_buf */
15396 ii_buffer_counter *counters; /* Status of terms */
15397 uint32_t ncounters; /* Number of counters */
15398 size_t total_size;
15399 size_t curr_size;
15400 ii_buffer_value *values; /* Values in block */
15401 unsigned int nvalues; /* Number of values in block */
15402 unsigned int max_nvalues; /* Size of values */
15403 grn_id last_rid;
15404
15405 // stuff for merging
15406 grn_ii *ii;
15407 uint32_t lseg;
15408 uint32_t dseg;
15409 buffer *term_buffer;
15410 datavec data_vectors[MAX_N_ELEMENTS + 1];
15411 uint8_t *packed_buf;
15412 size_t packed_buf_size;
15413 size_t packed_len;
15414 size_t total_chunk_size;
15415 };
15416
15417 /*
15418 * The temporary file format is roughly as follows:
15419 *
15420 * File = Block...
15421 * Block = Unit...
15422 * Unit = TermChunk (key order)
15423 * NextUnitSize (The first unit size is kept on memory)
15424 * Chunk = Term...
15425 * Term = ID (gtid)
15426 * NumRecordsOrSections (nrecs), NumOccurrences (nposts)
15427 * RecordID... (rid, diff)
15428 * [SectionID... (sid, diff)]
15429 * TermFrequency... (tf, diff)
15430 * [Weight... (weight, diff)]
15431 * [Position... (pos, diff)]
15432 */
15433
15434 /*
15435 * ==========================================================================
15436 * The following part provides constants, structures and functions for static
15437 * indexing.
15438 * ==========================================================================
15439 */
15440
15441 #define GRN_II_BUILDER_BUFFER_CHUNK_SIZE (S_CHUNK >> 2)
15442
15443 #define GRN_II_BUILDER_MAX_LEXICON_CACHE_SIZE (1 << 24)
15444
15445 #define GRN_II_BUILDER_MIN_BLOCK_THRESHOLD 1
15446 #define GRN_II_BUILDER_MAX_BLOCK_THRESHOLD (1 << 28)
15447
15448 #define GRN_II_BUILDER_MIN_FILE_BUF_SIZE (1 << 12)
15449 #define GRN_II_BUILDER_MAX_FILE_BUF_SIZE (1 << 30)
15450
15451 #define GRN_II_BUILDER_MIN_BLOCK_BUF_SIZE (1 << 12)
15452 #define GRN_II_BUILDER_MAX_BLOCK_BUF_SIZE (1 << 30)
15453
15454 #define GRN_II_BUILDER_MIN_CHUNK_THRESHOLD 1
15455 #define GRN_II_BUILDER_MAX_CHUNK_THRESHOLD (1 << 28)
15456
15457 #define GRN_II_BUILDER_MIN_BUFFER_MAX_N_TERMS 1
15458 #define GRN_II_BUILDER_MAX_BUFFER_MAX_N_TERMS \
15459 ((S_SEGMENT - sizeof(buffer_header)) / sizeof(buffer_term))
15460
15461 struct grn_ii_builder_options {
15462 uint32_t lexicon_cache_size; /* Cache size of temporary lexicon */
15463 /* A block is flushed if builder->n reaches this value. */
15464 uint32_t block_threshold;
15465 uint32_t file_buf_size; /* Buffer size for buffered output */
15466 uint32_t block_buf_size; /* Buffer size for buffered input */
15467 /* A chunk is flushed if chunk->n reaches this value. */
15468 uint32_t chunk_threshold;
15469 uint32_t buffer_max_n_terms; /* Maximum number of terms in each buffer */
15470 };
15471
15472 static const grn_ii_builder_options grn_ii_builder_default_options = {
15473 0x80000, /* lexicon_cache_size */
15474 0x4000000, /* block_threshold */
15475 0x10000, /* file_buf_size */
15476 0x10000, /* block_buf_size */
15477 0x1000, /* chunk_threshold */
15478 0x3000, /* buffer_max_n_terms */
15479 };
15480
15481 /* grn_ii_builder_options_init fills options with the default options. */
15482 void
15483 grn_ii_builder_options_init(grn_ii_builder_options *options)
15484 {
15485 *options = grn_ii_builder_default_options;
15486 }
15487
15488 /* grn_ii_builder_options_fix fixes out-of-range options. */
15489 static void
15490 grn_ii_builder_options_fix(grn_ii_builder_options *options)
15491 {
15492 if (options->lexicon_cache_size > GRN_II_BUILDER_MAX_LEXICON_CACHE_SIZE) {
15493 options->lexicon_cache_size = GRN_II_BUILDER_MAX_LEXICON_CACHE_SIZE;
15494 }
15495
15496 if (options->block_threshold < GRN_II_BUILDER_MIN_BLOCK_THRESHOLD) {
15497 options->block_threshold = GRN_II_BUILDER_MIN_BLOCK_THRESHOLD;
15498 }
15499 if (options->block_threshold > GRN_II_BUILDER_MAX_BLOCK_THRESHOLD) {
15500 options->block_threshold = GRN_II_BUILDER_MAX_BLOCK_THRESHOLD;
15501 }
15502
15503 if (options->file_buf_size < GRN_II_BUILDER_MIN_FILE_BUF_SIZE) {
15504 options->file_buf_size = GRN_II_BUILDER_MIN_FILE_BUF_SIZE;
15505 }
15506 if (options->file_buf_size > GRN_II_BUILDER_MAX_FILE_BUF_SIZE) {
15507 options->file_buf_size = GRN_II_BUILDER_MAX_FILE_BUF_SIZE;
15508 }
15509
15510 if (options->block_buf_size < GRN_II_BUILDER_MIN_BLOCK_BUF_SIZE) {
15511 options->block_buf_size = GRN_II_BUILDER_MIN_BLOCK_BUF_SIZE;
15512 }
15513 if (options->block_buf_size > GRN_II_BUILDER_MAX_BLOCK_BUF_SIZE) {
15514 options->block_buf_size = GRN_II_BUILDER_MAX_BLOCK_BUF_SIZE;
15515 }
15516
15517 if (options->chunk_threshold < GRN_II_BUILDER_MIN_CHUNK_THRESHOLD) {
15518 options->chunk_threshold = GRN_II_BUILDER_MIN_CHUNK_THRESHOLD;
15519 }
15520 if (options->chunk_threshold > GRN_II_BUILDER_MAX_CHUNK_THRESHOLD) {
15521 options->chunk_threshold = GRN_II_BUILDER_MAX_CHUNK_THRESHOLD;
15522 }
15523
15524 if (options->buffer_max_n_terms < GRN_II_BUILDER_MIN_BUFFER_MAX_N_TERMS) {
15525 options->buffer_max_n_terms = GRN_II_BUILDER_MIN_BUFFER_MAX_N_TERMS;
15526 }
15527 if (options->buffer_max_n_terms > GRN_II_BUILDER_MAX_BUFFER_MAX_N_TERMS) {
15528 options->buffer_max_n_terms = GRN_II_BUILDER_MAX_BUFFER_MAX_N_TERMS;
15529 }
15530 }
15531
15532 #define GRN_II_BUILDER_TERM_INPLACE_SIZE \
15533 (sizeof(grn_ii_builder_term) - offsetof(grn_ii_builder_term, dummy))
15534
15535 typedef struct {
15536 grn_id rid; /* Last record ID */
15537 uint32_t sid; /* Last section ID */
15538 /* Last position (GRN_OBJ_WITH_POSITION) or frequency. */
15539 uint32_t pos_or_freq;
15540 uint32_t offset; /* Buffer write offset */
15541 uint32_t size; /* Buffer size */
15542 uint32_t dummy; /* Padding */
15543 uint8_t *buf; /* Buffer (to be freed) */
15544 } grn_ii_builder_term;
15545
15546 /* grn_ii_builder_term_is_inplace returns whether a term buffer is inplace. */
15547 static inline bool
15548 grn_ii_builder_term_is_inplace(grn_ii_builder_term *term)
15549 {
15550 return term->size == GRN_II_BUILDER_TERM_INPLACE_SIZE;
15551 }
15552
15553 /* grn_ii_builder_term_get_buf returns a term buffer. */
15554 static inline uint8_t *
15555 grn_ii_builder_term_get_buf(grn_ii_builder_term *term)
15556 {
15557 if (grn_ii_builder_term_is_inplace(term)) {
15558 return (uint8_t *)&term->dummy;
15559 } else {
15560 return term->buf;
15561 }
15562 }
15563
15564 /*
15565 * grn_ii_builder_term_init initializes a term. Note that an initialized term
15566 * must be finalized by grn_ii_builder_term_fin.
15567 */
15568 static void
15569 grn_ii_builder_term_init(grn_ctx *ctx, grn_ii_builder_term *term)
15570 {
15571 term->rid = GRN_ID_NIL;
15572 term->sid = 0;
15573 term->pos_or_freq = 0;
15574 term->offset = 0;
15575 term->size = GRN_II_BUILDER_TERM_INPLACE_SIZE;
15576 }
15577
15578 /* grn_ii_builder_term_fin finalizes a term. */
15579 static void
15580 grn_ii_builder_term_fin(grn_ctx *ctx, grn_ii_builder_term *term)
15581 {
15582 if (!grn_ii_builder_term_is_inplace(term)) {
15583 GRN_FREE(term->buf);
15584 }
15585 }
15586
15587 /* grn_ii_builder_term_reinit reinitializes a term. */
15588 static void
15589 grn_ii_builder_term_reinit(grn_ctx *ctx, grn_ii_builder_term *term)
15590 {
15591 grn_ii_builder_term_fin(ctx, term);
15592 grn_ii_builder_term_init(ctx, term);
15593 }
15594
15595 /* grn_ii_builder_term_extend extends a term buffer. */
15596 static grn_rc
15597 grn_ii_builder_term_extend(grn_ctx *ctx, grn_ii_builder_term *term)
15598 {
15599 uint8_t *buf;
15600 uint32_t size = term->size * 2;
15601 if (grn_ii_builder_term_is_inplace(term)) {
15602 buf = (uint8_t *)GRN_MALLOC(size);
15603 if (!buf) {
15604 ERR(GRN_NO_MEMORY_AVAILABLE,
15605 "failed to allocate memory for term buffer: size = %u",
15606 size);
15607 return ctx->rc;
15608 }
15609 grn_memcpy(buf, &term->dummy, term->offset);
15610 } else {
15611 buf = (uint8_t *)GRN_REALLOC(term->buf, size);
15612 if (!buf) {
15613 ERR(GRN_NO_MEMORY_AVAILABLE,
15614 "failed to reallocate memory for term buffer: size = %u",
15615 size);
15616 return ctx->rc;
15617 }
15618 }
15619 term->buf = buf;
15620 term->size = size;
15621 return GRN_SUCCESS;
15622 }
15623
15624 /* grn_ii_builder_term_append appends an integer to a term buffer. */
15625 static inline grn_rc
15626 grn_ii_builder_term_append(grn_ctx *ctx,
15627 grn_ii_builder_term *term,
15628 uint64_t value)
15629 {
15630 uint8_t *p;
15631 if (value < (uint64_t)1 << 5) {
15632 if (term->offset + 1 > term->size) {
15633 grn_rc rc = grn_ii_builder_term_extend(ctx, term);
15634 if (rc != GRN_SUCCESS) {
15635 return rc;
15636 }
15637 }
15638 p = grn_ii_builder_term_get_buf(term) + term->offset;
15639 p[0] = (uint8_t)value;
15640 term->offset++;
15641 return GRN_SUCCESS;
15642 } else if (value < (uint64_t)1 << 13) {
15643 if (term->offset + 2 > term->size) {
15644 grn_rc rc = grn_ii_builder_term_extend(ctx, term);
15645 if (rc != GRN_SUCCESS) {
15646 return rc;
15647 }
15648 }
15649 p = grn_ii_builder_term_get_buf(term) + term->offset;
15650 p[0] = (uint8_t)((value & 0x1f) | (1 << 5));
15651 p[1] = (uint8_t)(value >> 5);
15652 term->offset += 2;
15653 return GRN_SUCCESS;
15654 } else {
15655 uint8_t i, n;
15656 if (value < (uint64_t)1 << 21) {
15657 n = 3;
15658 } else if (value < (uint64_t)1 << 29) {
15659 n = 4;
15660 } else if (value < (uint64_t)1 << 37) {
15661 n = 5;
15662 } else if (value < (uint64_t)1 << 45) {
15663 n = 6;
15664 } else if (value < (uint64_t)1 << 53) {
15665 n = 7;
15666 } else {
15667 n = 8;
15668 }
15669 if (term->offset + n > term->size) {
15670 grn_rc rc = grn_ii_builder_term_extend(ctx, term);
15671 if (rc != GRN_SUCCESS) {
15672 return rc;
15673 }
15674 }
15675 p = grn_ii_builder_term_get_buf(term) + term->offset;
15676 p[0] = (uint8_t)(value & 0x1f) | ((n - 1) << 5);
15677 value >>= 5;
15678 for (i = 1; i < n; i++) {
15679 p[i] = (uint8_t)value;
15680 value >>= 8;
15681 }
15682 term->offset += n;
15683 return GRN_SUCCESS;
15684 }
15685 }
15686
15687 typedef struct {
15688 uint64_t offset; /* File offset */
15689 uint32_t rest; /* Remaining size */
15690 uint8_t *buf; /* Buffer (to be freed) */
15691 uint8_t *cur; /* Current pointer */
15692 uint8_t *end; /* End pointer */
15693 uint32_t tid; /* Term ID */
15694 } grn_ii_builder_block;
15695
15696 /*
15697 * grn_ii_builder_block_init initializes a block. Note that an initialized
15698 * block must be finalized by grn_ii_builder_block_fin.
15699 */
15700 static void
15701 grn_ii_builder_block_init(grn_ctx *ctx, grn_ii_builder_block *block)
15702 {
15703 block->offset = 0;
15704 block->rest = 0;
15705 block->buf = NULL;
15706 block->cur = NULL;
15707 block->end = NULL;
15708 block->tid = GRN_ID_NIL;
15709 }
15710
15711 /* grn_ii_builder_block_fin finalizes a block. */
15712 static void
15713 grn_ii_builder_block_fin(grn_ctx *ctx, grn_ii_builder_block *block)
15714 {
15715 if (block->buf) {
15716 GRN_FREE(block->buf);
15717 }
15718 }
15719
15720 /*
15721 * grn_ii_builder_block_next reads the next integer. Note that this function
15722 * returns GRN_END_OF_DATA if it reaches the end of a block.
15723 */
15724 static inline grn_rc
15725 grn_ii_builder_block_next(grn_ctx *ctx,
15726 grn_ii_builder_block *block,
15727 uint64_t *value)
15728 {
15729 uint8_t n;
15730 if (block->cur == block->end) {
15731 return GRN_END_OF_DATA;
15732 }
15733 n = (*block->cur >> 5) + 1;
15734 if (n > block->end - block->cur) {
15735 return GRN_END_OF_DATA;
15736 }
15737 *value = 0;
15738 switch (n) {
15739 case 8:
15740 *value |= (uint64_t)block->cur[7] << 53;
15741 case 7:
15742 *value |= (uint64_t)block->cur[6] << 45;
15743 case 6:
15744 *value |= (uint64_t)block->cur[5] << 37;
15745 case 5:
15746 *value |= (uint64_t)block->cur[4] << 29;
15747 case 4:
15748 *value |= (uint64_t)block->cur[3] << 21;
15749 case 3:
15750 *value |= (uint64_t)block->cur[2] << 13;
15751 case 2:
15752 *value |= (uint64_t)block->cur[1] << 5;
15753 case 1:
15754 *value |= block->cur[0] & 0x1f;
15755 break;
15756 }
15757 block->cur += n;
15758 return GRN_SUCCESS;
15759 }
15760
15761 typedef struct {
15762 grn_ii *ii; /* Inverted index */
15763 uint32_t buf_id; /* Buffer ID */
15764 uint32_t buf_seg_id; /* Buffer segment ID */
15765 buffer *buf; /* Buffer (to be unreferenced) */
15766 uint32_t chunk_id; /* Chunk ID */
15767 uint32_t chunk_seg_id; /* Chunk segment ID */
15768 uint8_t *chunk; /* Chunk (to be unreferenced) */
15769 uint32_t chunk_offset; /* Chunk write position */
15770 uint32_t chunk_size; /* Chunk size */
15771 } grn_ii_builder_buffer;
15772
15773 /*
15774 * grn_ii_builder_buffer_init initializes a buffer. Note that a buffer must be
15775 * finalized by grn_ii_builder_buffer_fin.
15776 */
15777 static void
15778 grn_ii_builder_buffer_init(grn_ctx *ctx, grn_ii_builder_buffer *buf, grn_ii *ii)
15779 {
15780 buf->ii = ii;
15781 buf->buf_id = 0;
15782 buf->buf_seg_id = 0;
15783 buf->buf = NULL;
15784 buf->chunk_id = 0;
15785 buf->chunk_seg_id = 0;
15786 buf->chunk = NULL;
15787 buf->chunk_offset = 0;
15788 buf->chunk_size = 0;
15789 }
15790
15791 /* grn_ii_builder_buffer_fin finalizes a buffer. */
15792 static void
15793 grn_ii_builder_buffer_fin(grn_ctx *ctx, grn_ii_builder_buffer *buf)
15794 {
15795 if (buf->buf) {
15796 grn_io_seg_unref(ctx, buf->ii->seg, buf->buf_seg_id);
15797 }
15798 if (buf->chunk) {
15799 grn_io_seg_unref(ctx, buf->ii->chunk, buf->chunk_seg_id);
15800 }
15801 }
15802
15803 /* grn_ii_builder_buffer_is_assigned returns whether a buffer is assigned. */
15804 static bool
15805 grn_ii_builder_buffer_is_assigned(grn_ctx *ctx, grn_ii_builder_buffer *buf)
15806 {
15807 return buf->buf != NULL;
15808 }
15809
15810 /* grn_ii_builder_buffer_assign assigns a buffer. */
15811 static grn_rc
15812 grn_ii_builder_buffer_assign(grn_ctx *ctx,
15813 grn_ii_builder_buffer *buf,
15814 size_t min_chunk_size)
15815 {
15816 void *seg;
15817 size_t chunk_size;
15818 grn_rc rc;
15819
15820 /* Create a buffer. */
15821 buf->buf_id = GRN_II_PSEG_NOT_ASSIGNED;
15822 rc = buffer_segment_new(ctx, buf->ii, &buf->buf_id);
15823 if (rc != GRN_SUCCESS) {
15824 if (ctx->rc != GRN_SUCCESS) {
15825 ERR(rc,
15826 "[ii][builder][buffer][assign] "
15827 "failed to allocate segment for buffer");
15828 }
15829 return rc;
15830 }
15831 buf->buf_seg_id = grn_ii_get_buffer_pseg_inline(buf->ii, buf->buf_id);
15832 seg = grn_io_seg_ref(ctx, buf->ii->seg, buf->buf_seg_id);
15833 if (!seg) {
15834 if (ctx->rc == GRN_SUCCESS) {
15835 ERR(GRN_UNKNOWN_ERROR,
15836 "[ii][builder][buffer][assign] "
15837 "failed to access buffer segment: buffer_id=<%u> segment_id=<%u>",
15838 buf->buf_id,
15839 buf->buf_seg_id);
15840 }
15841 return ctx->rc;
15842 }
15843 buf->buf = (buffer *)seg;
15844
15845 /* Create a chunk. */
15846 chunk_size = GRN_II_BUILDER_BUFFER_CHUNK_SIZE;
15847 while (chunk_size < min_chunk_size) {
15848 chunk_size *= 2;
15849 }
15850 rc = chunk_new(ctx, buf->ii, &buf->chunk_id, chunk_size);
15851 if (rc != GRN_SUCCESS) {
15852 return rc;
15853 }
15854
15855 const size_t seg_offset =
15856 (buf->chunk_id & ((1 << GRN_II_N_CHUNK_VARIATION) - 1))
15857 << GRN_II_W_LEAST_CHUNK;
15858 const uint32_t chunk_capacity =
15859 buf->ii->chunk->header->segment_size - seg_offset;
15860 if (chunk_capacity < chunk_size) {
15861 ERR(GRN_NOT_ENOUGH_SPACE,
15862 "[ii][builder][buffer][assign] "
15863 "too large chunk size: "
15864 "chunk_size=<%" GRN_FMT_SIZE "> "
15865 "chunk_capacity=<%u> "
15866 "chunk_id=<%u> "
15867 "segment_id=<%u>",
15868 chunk_size,
15869 chunk_capacity,
15870 buf->chunk_id,
15871 buf->chunk_seg_id);
15872 return ctx->rc;
15873 }
15874
15875 buf->chunk_seg_id = buf->chunk_id >> GRN_II_N_CHUNK_VARIATION;
15876 seg = grn_io_seg_ref(ctx, buf->ii->chunk, buf->chunk_seg_id);
15877 if (!seg) {
15878 if (ctx->rc == GRN_SUCCESS) {
15879 ERR(GRN_UNKNOWN_ERROR,
15880 "[ii][builder][buffer][assign] "
15881 "failed to access chunk segment: chunk_id=<%u> segment_id=<%u>",
15882 buf->chunk_id,
15883 buf->chunk_seg_id);
15884 }
15885 return ctx->rc;
15886 }
15887 buf->chunk = ((uint8_t *)seg) + seg_offset;
15888 buf->chunk_offset = 0;
15889 buf->chunk_size = chunk_size;
15890
15891 buf->buf->header.chunk = buf->chunk_id;
15892 buf->buf->header.chunk_size = chunk_size;
15893 buf->buf->header.buffer_free = S_SEGMENT - sizeof(buffer_header);
15894 buf->buf->header.nterms = 0;
15895 buf->buf->header.nterms_void = 0;
15896 buf->ii->header.common->total_chunk_size += chunk_size;
15897 return GRN_SUCCESS;
15898 }
15899
15900 /* grn_ii_builder_buffer_flush flushes a buffer. */
15901 static grn_rc
15902 grn_ii_builder_buffer_flush(grn_ctx *ctx, grn_ii_builder_buffer *buf)
15903 {
15904 grn_ii *ii;
15905
15906 buf->buf->header.buffer_free = S_SEGMENT - sizeof(buffer_header) -
15907 buf->buf->header.nterms * sizeof(buffer_term);
15908 GRN_LOG(ctx,
15909 GRN_LOG_DEBUG,
15910 "[ii][builder][buffer][flush] "
15911 "n_terms=<%u> "
15912 "chunk_offset=<%u> "
15913 "chunk_size=<%u> "
15914 "total=<%" GRN_FMT_INT64U "KB>",
15915 buf->buf->header.nterms,
15916 buf->chunk_offset,
15917 buf->buf->header.chunk_size,
15918 buf->ii->header.common->total_chunk_size >> 10);
15919
15920 ii = buf->ii;
15921 grn_ii_builder_buffer_fin(ctx, buf);
15922 grn_ii_builder_buffer_init(ctx, buf, ii);
15923 return GRN_SUCCESS;
15924 }
15925
15926 typedef struct {
15927 grn_ii *ii; /* Building inverted index */
15928 grn_id tid; /* Term ID */
15929 uint32_t n; /* Number of integers in buffers */
15930 grn_id rid; /* Record ID */
15931 uint32_t rid_gap; /* Record ID gap */
15932 uint64_t pos_sum; /* Sum of position gaps */
15933
15934 uint32_t offset; /* Write offset */
15935 uint32_t size; /* Buffer size */
15936 grn_id *rid_buf; /* Buffer for record IDs (to be freed) */
15937 uint32_t *sid_buf; /* Buffer for section IDs (to be freed) */
15938 uint32_t *freq_buf; /* Buffer for frequencies (to be freed) */
15939 uint32_t *weight_buf; /* Buffer for weights (to be freed) */
15940
15941 uint32_t pos_offset; /* Write offset of pos_buf */
15942 uint32_t pos_size; /* Buffer size of pos_buf */
15943 uint32_t *pos_buf; /* Buffer for positions (to be freed) */
15944
15945 size_t enc_offset; /* Write offset of enc_buf */
15946 size_t enc_size; /* Buffer size of enc_buf */
15947 uint8_t *enc_buf; /* Buffer for encoded data (to be freed) */
15948 } grn_ii_builder_chunk;
15949
15950 /*
15951 * grn_ii_builder_chunk_init initializes a chunk. Note that an initialized
15952 * chunk must be finalized by grn_ii_builder_chunk_fin.
15953 */
15954 static void
15955 grn_ii_builder_chunk_init(grn_ctx *ctx, grn_ii_builder_chunk *chunk, grn_ii *ii)
15956 {
15957 chunk->ii = ii;
15958
15959 chunk->tid = GRN_ID_NIL;
15960 chunk->n = 0;
15961 chunk->rid = GRN_ID_NIL;
15962 chunk->rid_gap = 0;
15963 chunk->pos_sum = 0;
15964
15965 chunk->offset = 0;
15966 chunk->size = 0;
15967 chunk->rid_buf = NULL;
15968 chunk->sid_buf = NULL;
15969 chunk->freq_buf = NULL;
15970 chunk->weight_buf = NULL;
15971
15972 chunk->pos_offset = 0;
15973 chunk->pos_size = 0;
15974 chunk->pos_buf = NULL;
15975
15976 chunk->enc_offset = 0;
15977 chunk->enc_size = 0;
15978 chunk->enc_buf = NULL;
15979 }
15980
15981 /* grn_ii_builder_chunk_fin finalizes a chunk. */
15982 static void
15983 grn_ii_builder_chunk_fin(grn_ctx *ctx, grn_ii_builder_chunk *chunk)
15984 {
15985 if (chunk->enc_buf) {
15986 GRN_FREE(chunk->enc_buf);
15987 }
15988 if (chunk->pos_buf) {
15989 GRN_FREE(chunk->pos_buf);
15990 }
15991 if (chunk->weight_buf) {
15992 GRN_FREE(chunk->weight_buf);
15993 }
15994 if (chunk->freq_buf) {
15995 GRN_FREE(chunk->freq_buf);
15996 }
15997 if (chunk->sid_buf) {
15998 GRN_FREE(chunk->sid_buf);
15999 }
16000 if (chunk->rid_buf) {
16001 GRN_FREE(chunk->rid_buf);
16002 }
16003 }
16004
16005 /*
16006 * grn_ii_builder_chunk_clear clears stats except rid and buffers except
16007 * enc_buf.
16008 */
16009 static void
16010 grn_ii_builder_chunk_clear(grn_ctx *ctx, grn_ii_builder_chunk *chunk)
16011 {
16012 chunk->n = 0;
16013 chunk->rid_gap = 0;
16014 chunk->pos_sum = 0;
16015 chunk->offset = 0;
16016 chunk->pos_offset = 0;
16017 }
16018
16019 /*
16020 * grn_ii_builder_chunk_extend_bufs extends buffers except pos_buf and enc_buf.
16021 */
16022 static grn_rc
16023 grn_ii_builder_chunk_extend_bufs(grn_ctx *ctx,
16024 grn_ii_builder_chunk *chunk,
16025 uint32_t ii_flags)
16026 {
16027 uint32_t *buf;
16028 uint32_t size = chunk->size ? chunk->size * 2 : 1;
16029 size_t n_bytes = size * sizeof(uint32_t);
16030
16031 buf = (uint32_t *)GRN_REALLOC(chunk->rid_buf, n_bytes);
16032 if (!buf) {
16033 ERR(GRN_NO_MEMORY_AVAILABLE,
16034 "failed to allocate memory for record IDs: n_bytes = %" GRN_FMT_SIZE,
16035 n_bytes);
16036 return ctx->rc;
16037 }
16038 chunk->rid_buf = buf;
16039
16040 if (ii_flags & GRN_OBJ_WITH_SECTION) {
16041 buf = (uint32_t *)GRN_REALLOC(chunk->sid_buf, n_bytes);
16042 if (!buf) {
16043 ERR(GRN_NO_MEMORY_AVAILABLE,
16044 "failed to allocate memory for section IDs:"
16045 " n_bytes = %" GRN_FMT_SIZE,
16046 n_bytes);
16047 return ctx->rc;
16048 }
16049 chunk->sid_buf = buf;
16050 }
16051
16052 buf = (uint32_t *)GRN_REALLOC(chunk->freq_buf, n_bytes);
16053 if (!buf) {
16054 ERR(GRN_NO_MEMORY_AVAILABLE,
16055 "failed to allocate memory for frequencies: n_bytes = %" GRN_FMT_SIZE,
16056 n_bytes);
16057 return ctx->rc;
16058 }
16059 chunk->freq_buf = buf;
16060
16061 if (ii_flags & GRN_OBJ_WITH_WEIGHT) {
16062 buf = (uint32_t *)GRN_REALLOC(chunk->weight_buf, n_bytes);
16063 if (!buf) {
16064 ERR(GRN_NO_MEMORY_AVAILABLE,
16065 "failed to allocate memory for weights: n_bytes = %" GRN_FMT_SIZE,
16066 n_bytes);
16067 return ctx->rc;
16068 }
16069 chunk->weight_buf = buf;
16070 }
16071
16072 chunk->size = size;
16073 return GRN_SUCCESS;
16074 }
16075
16076 /* grn_ii_builder_chunk_extend_pos_buf extends pos_buf. */
16077 static grn_rc
16078 grn_ii_builder_chunk_extend_pos_buf(grn_ctx *ctx, grn_ii_builder_chunk *chunk)
16079 {
16080 uint32_t *buf;
16081 uint32_t size = chunk->pos_size ? chunk->pos_size * 2 : 1;
16082 size_t n_bytes = size * sizeof(uint32_t);
16083 buf = (uint32_t *)GRN_REALLOC(chunk->pos_buf, n_bytes);
16084 if (!buf) {
16085 ERR(GRN_NO_MEMORY_AVAILABLE,
16086 "failed to allocate memory for positions: n_bytes = %" GRN_FMT_SIZE,
16087 n_bytes);
16088 return ctx->rc;
16089 }
16090 chunk->pos_buf = buf;
16091 chunk->pos_size = size;
16092 return GRN_SUCCESS;
16093 }
16094
16095 /*
16096 * grn_ii_builder_chunk_reserve_enc_buf estimates a size that is enough to
16097 * store encoded data and allocates memory to enc_buf.
16098 */
16099 static grn_rc
16100 grn_ii_builder_chunk_reserve_enc_buf(grn_ctx *ctx,
16101 grn_ii_builder_chunk *chunk,
16102 uint32_t n_cinfos)
16103 {
16104 size_t rich_size =
16105 (chunk->n + 4) * sizeof(uint32_t) + n_cinfos * sizeof(chunk_info);
16106 if (chunk->enc_size < rich_size) {
16107 size_t size = chunk->enc_size ? chunk->enc_size * 2 : 1;
16108 while (size < rich_size) {
16109 size *= 2;
16110 }
16111 auto buf = static_cast<uint8_t *>(GRN_REALLOC(chunk->enc_buf, size));
16112 if (!buf) {
16113 ERR(GRN_NO_MEMORY_AVAILABLE,
16114 "failed to allocate memory for encoding: size = %" GRN_FMT_SIZE,
16115 size);
16116 return ctx->rc;
16117 }
16118 chunk->enc_buf = buf;
16119 chunk->enc_size = size;
16120 }
16121 chunk->enc_offset = 0;
16122 return GRN_SUCCESS;
16123 }
16124
16125 /* grn_ii_builder_chunk_encode encodes a chunk buffer. */
16126 static void
16127 grn_ii_builder_chunk_encode_buf(grn_ctx *ctx,
16128 grn_ii_builder_chunk *chunk,
16129 grn_codec_data *data)
16130 {
16131 data->offset = chunk->enc_size - (data->output - chunk->enc_buf);
16132 if (data->flags & DATA_USE_P_FOR_ENC) {
16133 data->output = grn_enc_p_for(ctx, data);
16134 } else {
16135 data->output = grn_enc_byte(ctx, data);
16136 }
16137 chunk->enc_offset = data->output - chunk->enc_buf;
16138 }
16139
16140 /* grn_ii_builder_chunk_encode encodes a chunk. */
16141 static grn_rc
16142 grn_ii_builder_chunk_encode(grn_ctx *ctx,
16143 grn_ii_builder_chunk *chunk,
16144 chunk_info *cinfos,
16145 uint32_t n_cinfos)
16146 {
16147 grn_rc rc;
16148 uint8_t *p;
16149 uint8_t shift = 0, use_p_for_enc_flags = 0;
16150
16151 /* Choose an encoding. */
16152 uint32_t rid_flags = 0;
16153 if (data_records_use_p_for_enc(chunk->offset, chunk->rid)) {
16154 rid_flags |= DATA_USE_P_FOR_ENC;
16155 }
16156 uint32_t rest_flags = 0;
16157 if (data_sections_use_p_for_enc(chunk->offset)) {
16158 rest_flags |= DATA_USE_P_FOR_ENC;
16159 }
16160 uint32_t pos_flags = DATA_ODD;
16161
16162 /* record IDs */
16163 if (rid_flags & DATA_USE_P_FOR_ENC) {
16164 use_p_for_enc_flags |= 1 << shift;
16165 }
16166 shift++;
16167 /* section IDs */
16168 if (chunk->sid_buf) {
16169 if (rest_flags & DATA_USE_P_FOR_ENC) {
16170 use_p_for_enc_flags |= 1 << shift;
16171 }
16172 shift++;
16173 }
16174 /* term frequencies */
16175 if (rest_flags & DATA_USE_P_FOR_ENC) {
16176 use_p_for_enc_flags |= 1 << shift;
16177 }
16178 shift++;
16179 /* weights */
16180 if (chunk->weight_buf) {
16181 if (rest_flags & DATA_USE_P_FOR_ENC) {
16182 use_p_for_enc_flags |= 1 << shift;
16183 }
16184 shift++;
16185 }
16186 /* positions */
16187 if (chunk->pos_buf) {
16188 if (data_positions_use_p_for_enc(chunk->pos_offset, chunk->pos_sum)) {
16189 pos_flags |= DATA_USE_P_FOR_ENC;
16190 use_p_for_enc_flags |= 1 << shift;
16191 }
16192 shift++;
16193 }
16194
16195 rc = grn_ii_builder_chunk_reserve_enc_buf(ctx, chunk, n_cinfos);
16196 if (rc != GRN_SUCCESS) {
16197 return rc;
16198 }
16199
16200 /* Encode a header. */
16201 p = chunk->enc_buf;
16202 if (n_cinfos > 0) {
16203 uint32_t i;
16204 GRN_B_ENC(n_cinfos, p);
16205 for (i = 0; i < n_cinfos; i++) {
16206 GRN_B_ENC(cinfos[i].segno, p);
16207 GRN_B_ENC(cinfos[i].size, p);
16208 GRN_B_ENC(cinfos[i].dgap, p);
16209 }
16210 }
16211 if (use_p_for_enc_flags) {
16212 GRN_B_ENC(use_p_for_enc_flags << 1, p);
16213 GRN_B_ENC(chunk->offset, p);
16214 if (chunk->pos_buf) {
16215 GRN_B_ENC(chunk->pos_offset - chunk->offset, p);
16216 }
16217 } else {
16218 GRN_B_ENC((chunk->offset << 1) | 1, p);
16219 }
16220 chunk->enc_offset = p - chunk->enc_buf;
16221
16222 /* Encode a body. */
16223 grn_codec_data data = {};
16224 data.ii = chunk->ii;
16225 data.term_id = chunk->tid;
16226 data.values = chunk->rid_buf;
16227 data.n_values = chunk->offset;
16228 data.flags = rid_flags;
16229 data.output = chunk->enc_buf + chunk->enc_offset;
16230 grn_ii_builder_chunk_encode_buf(ctx, chunk, &data);
16231 data.flags = rest_flags;
16232 if (chunk->sid_buf) {
16233 data.values = chunk->sid_buf;
16234 grn_ii_builder_chunk_encode_buf(ctx, chunk, &data);
16235 }
16236 data.values = chunk->freq_buf;
16237 grn_ii_builder_chunk_encode_buf(ctx, chunk, &data);
16238 if (chunk->weight_buf) {
16239 data.values = chunk->weight_buf;
16240 grn_ii_builder_chunk_encode_buf(ctx, chunk, &data);
16241 }
16242 if (chunk->pos_buf) {
16243 data.values = chunk->pos_buf;
16244 data.n_values = chunk->pos_offset;
16245 data.flags = pos_flags;
16246 grn_ii_builder_chunk_encode_buf(ctx, chunk, &data);
16247 }
16248
16249 return GRN_SUCCESS;
16250 }
16251
16252 namespace grn::ii {
16253 template <typename Each>
16254 grn_rc
16255 table_each_by_key(grn_ctx *ctx, grn_obj *table, Each &&each)
16256 {
16257 switch (table->header.type) {
16258 case GRN_TABLE_HASH_KEY:
16259 {
16260 auto hash = reinterpret_cast<grn_hash *>(table);
16261 if (grn_hash_size(ctx, hash) == 0) {
16262 return GRN_SUCCESS;
16263 }
16264
16265 // grn_hash can't use GRN_CURSOR_BY_KEY. So we sort by key
16266 // manually. This will not be an ignorable overhead but it's
16267 // an easy implementation for now. We may use an offline index
16268 // construction algorithm that doesn't rely on
16269 // GRN_CURSOR_BY_KEY in a future but we haven't done it.
16270 auto sorted = grn_array_create(ctx, nullptr, sizeof(grn_id), 0);
16271 if (!sorted) {
16272 return ctx->rc;
16273 }
16274 grn_table_sort_optarg arg = {
16275 GRN_TABLE_SORT_ASC | GRN_TABLE_SORT_BY_KEY,
16276 nullptr,
16277 nullptr,
16278 nullptr,
16279 0,
16280 };
16281 grn_hash_sort(ctx, hash, -1, sorted, &arg);
16282 grn_rc rc = GRN_SUCCESS;
16283 GRN_ARRAY_EACH_BEGIN(ctx, sorted, cursor, GRN_ID_NIL, GRN_ID_MAX, id)
16284 {
16285 grn_id hash_id = GRN_ID_NIL;
16286 auto value_size =
16287 grn_array_get_value(ctx,
16288 sorted,
16289 id,
16290 reinterpret_cast<void *>(&hash_id));
16291 if (value_size == 0) {
16292 continue;
16293 }
16294 rc = each(hash_id);
16295 if (rc != GRN_SUCCESS) {
16296 break;
16297 }
16298 }
16299 GRN_ARRAY_EACH_END(ctx, cursor);
16300 grn_array_close(ctx, sorted);
16301 return rc;
16302 }
16303 case GRN_TABLE_PAT_KEY:
16304 {
16305 auto pat = reinterpret_cast<grn_pat *>(table);
16306 grn_rc rc = GRN_SUCCESS;
16307 GRN_PAT_EACH_BEGIN(ctx, pat, cursor, id)
16308 {
16309 rc = each(id);
16310 if (rc != GRN_SUCCESS) {
16311 break;
16312 }
16313 }
16314 GRN_PAT_EACH_END(ctx, cursor);
16315 return rc;
16316 }
16317 case GRN_TABLE_DAT_KEY:
16318 {
16319 auto dat = reinterpret_cast<grn_dat *>(table);
16320 grn_rc rc = GRN_SUCCESS;
16321 GRN_DAT_EACH_BEGIN(ctx, dat, cursor, id)
16322 {
16323 rc = each(id);
16324 if (rc != GRN_SUCCESS) {
16325 break;
16326 }
16327 }
16328 GRN_DAT_EACH_END(ctx, cursor);
16329 return rc;
16330 }
16331 default:
16332 // must not happen
16333 return GRN_INVALID_ARGUMENT;
16334 }
16335 }
16336
16337 // Builds a block from multiple records. You can build a block by
16338 // calling flush() after you append multiple records by
16339 // append_record().
16340 class BlockBuilder {
16341 public:
16342 BlockBuilder(grn_ctx *parent_ctx,
16343 grn_ctx *ctx,
16344 grn_ii *ii,
16345 const grn_ii_builder_options *options,
16346 grn_obj *src_table,
16347 grn_obj *srcs,
16348 grn_obj **src_token_columns,
16349 uint8_t sid_bits)
16350 : parent_ctx_(parent_ctx),
16351 ctx_(ctx),
16352 ii_(ii),
16353 options_(options),
16354 lexicon_(nullptr),
16355 have_tokenizer_(false),
16356 have_normalizers_(false),
16357 get_key_optimizable_(false),
16358 n_(0),
16359 rid_(GRN_ID_NIL),
16360 sid_(0),
16361 pos_(0),
16362 terms_(nullptr),
16363 n_terms_(0),
16364 max_n_terms_(0),
16365 terms_size_(0),
16366 src_table_(src_table),
16367 srcs_(srcs),
16368 src_token_columns_(src_token_columns),
16369 sid_bits_(sid_bits),
16370 values_(GRN_PTR_VECTOR_SIZE(srcs_)),
16371 casted_token_value_(),
16372 n_processed_records_(0)
16373 {
16374 const size_t n = GRN_PTR_VECTOR_SIZE(srcs_);
16375 for (size_t i = 0; i < n; i++) {
16376 GRN_VOID_INIT(&values_[i]);
16377 }
16378 GRN_OBJ_INIT(&casted_token_value_,
16379 GRN_BULK,
16380 0,
16381 ii_->lexicon->header.domain);
16382 }
16383
16384 ~BlockBuilder()
16385 {
16386 GRN_OBJ_FIN(ctx_, &casted_token_value_);
16387 const size_t n = GRN_PTR_VECTOR_SIZE(srcs_);
16388 for (size_t i = 0; i < n; i++) {
16389 GRN_OBJ_FIN(ctx_, &values_[i]);
16390 }
16391 if (lexicon_) {
16392 grn_obj_close(ctx_, lexicon_);
16393 }
16394 finalize_terms();
16395 if (parent_ctx_) {
16396 grn_ctx_release_child(parent_ctx_, ctx_);
16397 }
16398 }
16399
16400 // Prepares this builder.
16401 //
16402 // This must be called once before you call append_record().
16403 grn_rc
16404 prepare()
16405 {
16406 auto rc = create_lexicon();
16407 if (rc != GRN_SUCCESS) {
16408 return rc;
16409 }
16410 return GRN_SUCCESS;
16411 }
16412
16413 // Appends a record.
16414 //
16415 // `rid` must be ordered by ascending. The following is valid:
16416 //
16417 // block_builder.append_record(1);
16418 // block_builder.append_record(2);
16419 // block_builder.append_record(3);
16420 //
16421 // But the following is invalid:
16422 //
16423 // block_builder.append_record(1);
16424 // block_builder.append_record(3);
16425 // block_builder.append_record(2); // 2 is smaller than 3
16426 grn_rc
16427 append_record(grn_id rid)
16428 {
16429 const size_t n = GRN_PTR_VECTOR_SIZE(srcs_);
16430 for (size_t i = 0; i < n; i++) {
16431 grn_obj *value = &values_[i];
16432 grn_obj *src = GRN_PTR_VALUE_AT(srcs_, i);
16433 grn_obj *token_column = src_token_columns_[i];
16434 if (token_column) {
16435 auto rc = grn_obj_reinit_for(ctx_, value, token_column);
16436 if (rc != GRN_SUCCESS) {
16437 return rc;
16438 }
16439 if (!grn_obj_get_value(ctx_, token_column, rid, value)) {
16440 if (ctx_->rc == GRN_SUCCESS) {
16441 auto ctx = ctx_;
16442 ERR(GRN_UNKNOWN_ERROR, "failed to get tokens: rid = %u", rid);
16443 }
16444 return ctx_->rc;
16445 }
16446 auto sid = static_cast<uint32_t>(i + 1);
16447 rc = append_tokens(rid, sid, value);
16448 if (rc != GRN_SUCCESS) {
16449 return rc;
16450 }
16451 } else {
16452 auto rc = grn_obj_reinit_for(ctx_, value, src);
16453 if (rc != GRN_SUCCESS) {
16454 return rc;
16455 }
16456 if (GRN_OBJ_TABLEP(src)) {
16457 auto len = grn_table_get_key2(ctx_, src, rid, value);
16458 if (len <= 0) {
16459 if (ctx_->rc == GRN_SUCCESS) {
16460 auto ctx = ctx_;
16461 ERR(GRN_UNKNOWN_ERROR,
16462 "failed to get key: rid = %u, len = %d",
16463 rid,
16464 len);
16465 }
16466 return ctx_->rc;
16467 }
16468 } else {
16469 if (!grn_obj_get_value(ctx_, src, rid, value)) {
16470 if (ctx_->rc == GRN_SUCCESS) {
16471 auto ctx = ctx_;
16472 ERR(GRN_UNKNOWN_ERROR, "failed to get value: rid = %u", rid);
16473 }
16474 return ctx_->rc;
16475 }
16476 }
16477 auto sid = static_cast<uint32_t>(i + 1);
16478 auto extracted_value = grn_table_extract(ctx_, lexicon_, value);
16479 if (ctx_->rc != GRN_SUCCESS) {
16480 return ctx_->rc;
16481 }
16482 if (extracted_value == value) {
16483 rc = append_obj(src, rid, sid, value);
16484 } else {
16485 rc = append_obj(src, rid, sid, extracted_value);
16486 grn_obj_close(ctx_, extracted_value);
16487 }
16488 if (rc != GRN_SUCCESS) {
16489 return rc;
16490 }
16491 }
16492 }
16493 return finish_record();
16494 }
16495
16496 // Whether we need to flush this block.
16497 bool
16498 need_flush()
16499 {
16500 return n_ >= options_->block_threshold;
16501 }
16502
16503 // Whether there are any data in this block.
16504 bool
16505 have_data()
16506 {
16507 return n_ > 0;
16508 }
16509
16510 // Number of processed records in this block.
16511 size_t
16512 n_processed_records()
16513 {
16514 return n_processed_records_;
16515 }
16516
16517 // Flushes all terms in this block.
16518 template <typename FlushTerm>
16519 grn_rc
16520 flush(FlushTerm &&flush_term)
16521 {
16522 if (n_ == 0) {
16523 /* Do nothing if there are no output data. */
16524 return GRN_SUCCESS;
16525 }
16526
16527 // Flush terms.
16528 //
16529 // This assumes that both of each block builder (here) and
16530 // reader (see Builder::commit()) use the same order to write
16531 // built blocks and read the written blocks. This is implemented
16532 // by sorting by key (term) in both of local lexicons and the
16533 // global lexicon (ii_->lexicon). Sorting by key is efficient
16534 // with grn_pat and grn_dat but not with grn_hash. So we may
16535 // change this algorithm later.
16536 auto rc = table_each_by_key(ctx_, lexicon_, [&](grn_id tid) {
16537 return flush_term(&(terms_[tid - 1]), lexicon_, tid);
16538 });
16539
16540 /* Clear the current data. */
16541 rc = grn_table_truncate(ctx_, lexicon_);
16542 if (rc != GRN_SUCCESS) {
16543 return rc;
16544 }
16545 rid_ = GRN_ID_NIL;
16546 n_terms_ = 0;
16547 n_ = 0;
16548 n_processed_records_ = 0;
16549 return GRN_SUCCESS;
16550 }
16551
16552 grn_rc
16553 append_tokens(grn_id rid, uint32_t sid, grn_obj *tokens)
16554 {
16555 start_value(rid, sid);
16556 grn_obj *src_lexicon = ii_->lexicon;
16557 size_t n_tokens = grn_uvector_size(ctx_, tokens);
16558 size_t i;
16559 for (i = 0; i < n_tokens; i++) {
16560 float weight;
16561 grn_id tid;
16562 grn_id src_tid =
16563 grn_uvector_get_element_record(ctx_, tokens, i, &weight);
16564 uint32_t token_value_size;
16565 const char *token_value =
16566 _grn_table_key(ctx_, src_lexicon, src_tid, &token_value_size);
16567
16568 switch (lexicon_->header.type) {
16569 case GRN_TABLE_PAT_KEY:
16570 tid = grn_pat_add(ctx_,
16571 reinterpret_cast<grn_pat *>(lexicon_),
16572 token_value,
16573 token_value_size,
16574 NULL,
16575 NULL);
16576 break;
16577 case GRN_TABLE_DAT_KEY:
16578 tid = grn_dat_add(ctx_,
16579 reinterpret_cast<grn_dat *>(lexicon_),
16580 token_value,
16581 token_value_size,
16582 NULL,
16583 NULL);
16584 break;
16585 case GRN_TABLE_HASH_KEY:
16586 tid = grn_hash_add(ctx_,
16587 reinterpret_cast<grn_hash *>(lexicon_),
16588 token_value,
16589 token_value_size,
16590 NULL,
16591 NULL);
16592 break;
16593 default:
16594 /* This case must not be happen. */
16595 tid = GRN_ID_NIL;
16596 break;
16597 }
16598
16599 if (tid == GRN_ID_NIL) {
16600 /* TODO: Token value may not be a string. */
16601 auto ctx = ctx_;
16602 ERR(GRN_INVALID_ARGUMENT,
16603 "[ii][builder][append-tokens] failed to add a token: <%.*s>",
16604 static_cast<int>(token_value_size),
16605 token_value);
16606 return ctx->rc;
16607 }
16608 uint32_t pos = pos_ + i;
16609 grn_rc rc =
16610 append_token(rid, sid, static_cast<uint32_t>(weight), tid, pos);
16611 if (rc != GRN_SUCCESS) {
16612 return rc;
16613 }
16614 }
16615 return GRN_SUCCESS;
16616 }
16617
16618 grn_rc
16619 finish_record()
16620 {
16621 ++n_processed_records_;
16622 return GRN_SUCCESS;
16623 }
16624
16625 private:
16626 grn_ctx *parent_ctx_;
16627 grn_ctx *ctx_;
16628 grn_ii *ii_;
16629 const grn_ii_builder_options *options_;
16630
16631 grn_obj *lexicon_; /* Block lexicon (to be closed) */
16632 bool have_tokenizer_; /* Whether lexicon has tokenizer */
16633 bool have_normalizers_; /* Whether lexicon has at least one normalizers */
16634 bool get_key_optimizable_; /* Whether grn_table_get_key() is optimizable */
16635
16636 uint32_t n_; /* Number of integers appended to the current block */
16637 grn_id rid_; /* Record ID */
16638 uint32_t sid_; /* Section ID */
16639 uint32_t pos_; /* Position */
16640
16641 grn_ii_builder_term *terms_; /* Terms (to be freed) */
16642 uint32_t n_terms_; /* Number of distinct terms */
16643 uint32_t max_n_terms_; /* Maximum number of distinct terms */
16644 uint32_t terms_size_; /* Buffer size of terms */
16645
16646 grn_obj *src_table_; /* Source table */
16647 // Source columns. This refers source columns in Builder. So this
16648 // should not be freed.
16649 grn_obj *srcs_;
16650 // Source token columns. This refers source token columns in
16651 // Builder. So this should not be freed.
16652 grn_obj **src_token_columns_;
16653 uint8_t sid_bits_; /* Number of bits for section ID */
16654
16655 // Buffers for source column values. We use one grn_obj per column
16656 // to reuse effectively.
16657 std::vector<grn_obj> values_;
16658
16659 // Buffer for token value cast.
16660 grn_obj casted_token_value_;
16661
16662 size_t n_processed_records_; /* Number of processed records */
16663
16664 // Creates a block lexicon.
16665 grn_rc
16666 create_lexicon()
16667 {
16668 grn_table_flags flags;
16669 grn_obj *domain = grn_ctx_at(ctx_, ii_->lexicon->header.domain);
16670 grn_obj *range = grn_ctx_at(ctx_, DB_OBJ(ii_->lexicon)->range);
16671
16672 auto rc = grn_table_get_info(ctx_,
16673 ii_->lexicon,
16674 &flags,
16675 nullptr,
16676 nullptr,
16677 nullptr,
16678 nullptr);
16679 if (rc != GRN_SUCCESS) {
16680 return rc;
16681 }
16682 flags &= ~GRN_OBJ_PERSISTENT;
16683 lexicon_ =
16684 grn_table_create(ctx_, nullptr, 0, nullptr, flags, domain, range);
16685 if (!lexicon_) {
16686 if (ctx_->rc == GRN_SUCCESS) {
16687 auto ctx = ctx_;
16688 ERR(GRN_UNKNOWN_ERROR, "[index] failed to create a block lexicon");
16689 }
16690 return ctx_->rc;
16691 }
16692 {
16693 grn_obj tokenizer;
16694 GRN_TEXT_INIT(&tokenizer, 0);
16695 grn_table_get_default_tokenizer_string(ctx_, ii_->lexicon, &tokenizer);
16696 if (GRN_TEXT_LEN(&tokenizer) > 0) {
16697 have_tokenizer_ = true;
16698 rc = grn_obj_set_info(ctx_,
16699 lexicon_,
16700 GRN_INFO_DEFAULT_TOKENIZER,
16701 &tokenizer);
16702 }
16703 GRN_OBJ_FIN(ctx_, &tokenizer);
16704 }
16705 if (rc == GRN_SUCCESS) {
16706 grn_obj normalizers;
16707 GRN_TEXT_INIT(&normalizers, 0);
16708 grn_table_get_normalizers_string(ctx_, ii_->lexicon, &normalizers);
16709 if (GRN_TEXT_LEN(&normalizers) > 0) {
16710 have_normalizers_ = true;
16711 rc = grn_obj_set_info(ctx_,
16712 lexicon_,
16713 GRN_INFO_NORMALIZERS,
16714 &normalizers);
16715 }
16716 GRN_OBJ_FIN(ctx_, &normalizers);
16717 }
16718 if (rc == GRN_SUCCESS) {
16719 grn_obj token_filters;
16720 GRN_TEXT_INIT(&token_filters, 0);
16721 grn_table_get_token_filters_string(ctx_, ii_->lexicon, &token_filters);
16722 if (GRN_TEXT_LEN(&token_filters) > 0) {
16723 rc = grn_obj_set_info(ctx_,
16724 lexicon_,
16725 GRN_INFO_TOKEN_FILTERS,
16726 &token_filters);
16727 }
16728 GRN_OBJ_FIN(ctx_, &token_filters);
16729 }
16730 if (rc == GRN_SUCCESS) {
16731 grn_obj extractors;
16732 GRN_TEXT_INIT(&extractors, 0);
16733 grn_table_get_extractors_string(ctx_, ii_->lexicon, &extractors);
16734 if (GRN_TEXT_LEN(&extractors) > 0) {
16735 rc =
16736 grn_obj_set_info(ctx_, lexicon_, GRN_INFO_EXTRACTORS, &extractors);
16737 }
16738 GRN_OBJ_FIN(ctx_, &extractors);
16739 }
16740 if (rc != GRN_SUCCESS) {
16741 return rc;
16742 }
16743 if ((flags & GRN_OBJ_TABLE_TYPE_MASK) == GRN_OBJ_TABLE_PAT_KEY) {
16744 auto lexicon_pat = reinterpret_cast<grn_pat *>(lexicon_);
16745 get_key_optimizable_ = !grn_pat_is_key_encoded(ctx_, lexicon_pat);
16746 if (options_->lexicon_cache_size) {
16747 rc = grn_pat_cache_enable(ctx_,
16748 lexicon_pat,
16749 options_->lexicon_cache_size);
16750 if (rc != GRN_SUCCESS) {
16751 return rc;
16752 }
16753 }
16754 } else {
16755 get_key_optimizable_ = true;
16756 }
16757 return GRN_SUCCESS;
16758 }
16759
16760 void
16761 finalize_terms()
16762 {
16763 if (!terms_) {
16764 return;
16765 }
16766
16767 uint32_t i;
16768 for (i = 0; i < max_n_terms_; i++) {
16769 grn_ii_builder_term_fin(ctx_, &(terms_[i]));
16770 }
16771 auto ctx = ctx_;
16772 GRN_FREE(terms_);
16773 /* To avoid double finalization. */
16774 terms_ = nullptr;
16775 }
16776
16777 // Extends a buffer for terms in order to make terms[n_terms - 1]
16778 // available.
16779 grn_rc
16780 extend_terms(uint32_t new_n_terms)
16781 {
16782 if (new_n_terms <= n_terms_) {
16783 return GRN_SUCCESS;
16784 }
16785
16786 if (new_n_terms > max_n_terms_) {
16787 uint32_t i;
16788 if (new_n_terms > terms_size_) {
16789 /* Resize builder->terms_ for new terms. */
16790 uint32_t new_terms_size = terms_size_ ? terms_size_ * 2 : 1;
16791 while (new_terms_size < new_n_terms) {
16792 new_terms_size *= 2;
16793 }
16794 auto ctx = ctx_;
16795 auto new_n_bytes = new_terms_size * sizeof(grn_ii_builder_term);
16796 auto new_terms = static_cast<grn_ii_builder_term *>(
16797 GRN_REALLOC(terms_, new_n_bytes));
16798 if (!new_terms) {
16799 ERR(GRN_NO_MEMORY_AVAILABLE,
16800 "failed to allocate memory for terms: n_bytes = %" GRN_FMT_SIZE,
16801 new_n_bytes);
16802 return ctx->rc;
16803 }
16804 terms_ = new_terms;
16805 terms_size_ = new_terms_size;
16806 }
16807 /* Initialize new terms. */
16808 for (i = max_n_terms_; i < new_n_terms; i++) {
16809 grn_ii_builder_term_init(ctx_, &(terms_[i]));
16810 }
16811 max_n_terms_ = new_n_terms;
16812 }
16813
16814 n_ += new_n_terms - n_terms_;
16815 n_terms_ = new_n_terms;
16816 return GRN_SUCCESS;
16817 }
16818
16819 // Gets a term associated with tid.
16820 grn_rc
16821 get_term(grn_id tid, grn_ii_builder_term **term)
16822 {
16823 uint32_t n_terms = tid;
16824 if (n_terms > n_terms_) {
16825 grn_rc rc = extend_terms(n_terms);
16826 if (rc != GRN_SUCCESS) {
16827 return rc;
16828 }
16829 }
16830 *term = &(terms_[tid - 1]);
16831 return GRN_SUCCESS;
16832 }
16833
16834 // Appends a token.
16835 grn_rc
16836 append_token(
16837 grn_id rid, uint32_t sid, uint32_t weight, grn_id tid, uint32_t pos)
16838 {
16839 uint32_t ii_flags = ii_->header.common->flags;
16840 grn_ii_builder_term *term;
16841 {
16842 auto rc = get_term(tid, &term);
16843 if (rc != GRN_SUCCESS) {
16844 return rc;
16845 }
16846 }
16847 if (rid != term->rid || sid != term->sid) {
16848 uint64_t rsid;
16849 if (term->rid != GRN_ID_NIL) {
16850 if (ii_flags & GRN_OBJ_WITH_POSITION) {
16851 /* Append the end of positions. */
16852 auto rc = grn_ii_builder_term_append(ctx_, term, 0);
16853 if (rc != GRN_SUCCESS) {
16854 return rc;
16855 }
16856 n_++;
16857 } else {
16858 /* Append a frequency if positions are not available. */
16859 auto rc = grn_ii_builder_term_append(ctx_, term, term->pos_or_freq);
16860 if (rc != GRN_SUCCESS) {
16861 return rc;
16862 }
16863 n_++;
16864 }
16865 }
16866 rsid =
16867 (static_cast<uint64_t>(rid - term->rid) << sid_bits_) | (sid - 1);
16868 auto rc = grn_ii_builder_term_append(ctx_, term, rsid);
16869 if (rc != GRN_SUCCESS) {
16870 return rc;
16871 }
16872 n_++;
16873 if (ii_flags & GRN_OBJ_WITH_WEIGHT) {
16874 auto rc = grn_ii_builder_term_append(ctx_, term, weight);
16875 if (rc != GRN_SUCCESS) {
16876 return rc;
16877 }
16878 n_++;
16879 }
16880 term->rid = rid;
16881 term->sid = sid;
16882 term->pos_or_freq = 0;
16883 }
16884 if (ii_flags & GRN_OBJ_WITH_POSITION) {
16885 auto rc =
16886 grn_ii_builder_term_append(ctx_, term, pos - term->pos_or_freq);
16887 if (rc != GRN_SUCCESS) {
16888 return rc;
16889 }
16890 n_++;
16891 term->pos_or_freq = pos;
16892 } else {
16893 term->pos_or_freq++;
16894 }
16895 return GRN_SUCCESS;
16896 }
16897
16898 void
16899 start_value(grn_id rid, uint32_t sid)
16900 {
16901 if (rid != rid_) {
16902 rid_ = rid;
16903 sid_ = sid;
16904 pos_ = 1;
16905 } else if (sid != sid_) {
16906 sid_ = sid;
16907 pos_ = 1;
16908 } else if (have_tokenizer_) {
16909 /* Insert a space between values. */
16910 pos_++;
16911 }
16912 }
16913
16914 // Appends a value. Note that values must be appended in ascending
16915 // rid and sid order.
16916 grn_rc
16917 append_value(grn_obj *src,
16918 grn_id rid,
16919 uint32_t sid,
16920 uint32_t weight,
16921 const char *value,
16922 uint32_t value_size,
16923 grn_id value_domain,
16924 bool force_as_is)
16925 {
16926 uint32_t pos = 0;
16927 grn_token_cursor *cursor;
16928 start_value(rid, sid);
16929 if (value_size == 0) {
16930 pos = pos_;
16931 } else {
16932 if (force_as_is || (!have_tokenizer_ && !have_normalizers_)) {
16933 grn_id tid;
16934 uint32_t max_key_size = 0;
16935 bool too_large_key = false;
16936 if (value_domain != lexicon_->header.domain &&
16937 !(grn_type_id_is_text_family(ctx_, value_domain) &&
16938 grn_type_id_is_text_family(ctx_, lexicon_->header.domain))) {
16939 grn_obj original_value;
16940 GRN_OBJ_INIT(&original_value,
16941 GRN_BULK,
16942 GRN_OBJ_DO_SHALLOW_COPY,
16943 value_domain);
16944 GRN_TEXT_SET(ctx_, &original_value, value, value_size);
16945 GRN_BULK_REWIND(&casted_token_value_);
16946 grn_rc rc =
16947 grn_obj_cast(ctx_, &original_value, &casted_token_value_, false);
16948 GRN_OBJ_FIN(ctx_, &original_value);
16949 if (rc != GRN_SUCCESS) {
16950 return rc;
16951 }
16952 value = GRN_BULK_HEAD(&casted_token_value_);
16953 value_size = GRN_BULK_VSIZE(&casted_token_value_);
16954 }
16955 switch (lexicon_->header.type) {
16956 case GRN_TABLE_PAT_KEY:
16957 if (value_size >= GRN_TABLE_MAX_KEY_SIZE) {
16958 tid = GRN_ID_NIL;
16959 max_key_size = GRN_TABLE_MAX_KEY_SIZE;
16960 too_large_key = true;
16961 } else {
16962 tid = grn_pat_add(ctx_,
16963 reinterpret_cast<grn_pat *>(lexicon_),
16964 value,
16965 value_size,
16966 NULL,
16967 NULL);
16968 }
16969 break;
16970 case GRN_TABLE_DAT_KEY:
16971 if (value_size >= GRN_TABLE_MAX_KEY_SIZE) {
16972 tid = GRN_ID_NIL;
16973 max_key_size = GRN_TABLE_MAX_KEY_SIZE;
16974 too_large_key = true;
16975 } else {
16976 tid = grn_dat_add(ctx_,
16977 reinterpret_cast<grn_dat *>(lexicon_),
16978 value,
16979 value_size,
16980 NULL,
16981 NULL);
16982 }
16983 break;
16984 case GRN_TABLE_HASH_KEY:
16985 {
16986 auto lexicon_hash = reinterpret_cast<grn_hash *>(lexicon_);
16987 if (value_size > lexicon_hash->key_size) {
16988 tid = GRN_ID_NIL;
16989 max_key_size = lexicon_hash->key_size;
16990 too_large_key = true;
16991 } else {
16992 tid = grn_hash_add(ctx_,
16993 lexicon_hash,
16994 value,
16995 value_size,
16996 NULL,
16997 NULL);
16998 }
16999 }
17000 break;
17001 case GRN_TABLE_NO_KEY:
17002 tid = *reinterpret_cast<const grn_id *>(value);
17003 break;
17004 default:
17005 tid = GRN_ID_NIL;
17006 break;
17007 }
17008 if (too_large_key) {
17009 auto ctx = ctx_;
17010 GRN_DEFINE_NAME(src);
17011 grn_obj record;
17012 GRN_RECORD_INIT(&record, 0, DB_OBJ(src_table_)->id);
17013 GRN_RECORD_SET(ctx, &record, rid);
17014 grn_obj inspected_record;
17015 GRN_TEXT_INIT(&inspected_record, 0);
17016 grn_inspect(ctx, &inspected_record, &record);
17017 GRN_LOG(ctx,
17018 GRN_LOG_WARNING,
17019 "[ii][builder][append-value][%.*s] ignore too long token. "
17020 "Token must be less than or equal to %u: <%u>: %.*s",
17021 name_size,
17022 name,
17023 max_key_size,
17024 value_size,
17025 (int)GRN_TEXT_LEN(&inspected_record),
17026 GRN_TEXT_VALUE(&inspected_record));
17027 GRN_OBJ_FIN(ctx, &inspected_record);
17028 GRN_OBJ_FIN(ctx, &record);
17029 }
17030 if (tid != GRN_ID_NIL) {
17031 pos = pos_;
17032 auto rc = append_token(rid, sid, weight, tid, pos);
17033 if (rc != GRN_SUCCESS) {
17034 return rc;
17035 }
17036 }
17037 } else {
17038 cursor = grn_token_cursor_open(ctx_,
17039 lexicon_,
17040 value,
17041 value_size,
17042 GRN_TOKEN_ADD,
17043 0);
17044 if (!cursor) {
17045 if (ctx_->rc == GRN_SUCCESS) {
17046 auto ctx = ctx_;
17047 ERR(GRN_UNKNOWN_ERROR,
17048 "grn_token_cursor_open failed: value = <%.*s>",
17049 value_size,
17050 value);
17051 }
17052 return ctx_->rc;
17053 }
17054 grn_token_cursor_set_query_domain(ctx_, cursor, value_domain);
17055 while (cursor->status == GRN_TOKEN_CURSOR_DOING) {
17056 grn_id tid = grn_token_cursor_next(ctx_, cursor);
17057 if (tid != GRN_ID_NIL) {
17058 pos = pos_ + cursor->pos;
17059 auto rc = append_token(rid, sid, weight, tid, pos);
17060 if (rc != GRN_SUCCESS) {
17061 break;
17062 }
17063 }
17064 }
17065 grn_token_cursor_close(ctx_, cursor);
17066 }
17067 }
17068 pos_ = pos + 1;
17069 return ctx_->rc;
17070 }
17071
17072 // Appends a BULK, UVECTOR or VECTOR object.
17073 grn_rc
17074 append_obj(grn_obj *src, grn_id rid, uint32_t sid, grn_obj *obj)
17075 {
17076 switch (obj->header.type) {
17077 case GRN_BULK:
17078 if (grn_id_maybe_table(ctx_, obj->header.domain)) {
17079 grn_id id = GRN_RECORD_VALUE(obj);
17080 grn_obj key_buffer;
17081 GRN_VOID_INIT(&key_buffer);
17082 uint32_t key_size;
17083 const char *key;
17084 if (get_key_optimizable_) {
17085 key = _grn_table_key(ctx_, ii_->lexicon, id, &key_size);
17086 } else {
17087 GRN_BULK_REWIND(&key_buffer);
17088 grn_table_get_key2(ctx_, ii_->lexicon, id, &key_buffer);
17089 key = GRN_BULK_HEAD(&key_buffer);
17090 key_size = GRN_BULK_VSIZE(&key_buffer);
17091 }
17092 grn_rc rc = append_value(src,
17093 rid,
17094 sid,
17095 0,
17096 key,
17097 key_size,
17098 ii_->lexicon->header.domain,
17099 true);
17100 GRN_OBJ_FIN(ctx_, &key_buffer);
17101 return rc;
17102 } else {
17103 return append_value(src,
17104 rid,
17105 sid,
17106 0,
17107 GRN_TEXT_VALUE(obj),
17108 GRN_TEXT_LEN(obj),
17109 obj->header.domain,
17110 false);
17111 }
17112 case GRN_UVECTOR:
17113 {
17114 grn_rc rc = GRN_SUCCESS;
17115 uint32_t i, n_values = grn_uvector_size(ctx_, obj);
17116 if (grn_id_maybe_table(ctx_, obj->header.domain)) {
17117 grn_obj key_buffer;
17118 GRN_VOID_INIT(&key_buffer);
17119 for (i = 0; i < n_values; i++) {
17120 grn_id id;
17121 float weight;
17122 id = grn_uvector_get_element_record(ctx_, obj, i, &weight);
17123 const char *key = nullptr;
17124 uint32_t key_size = 0;
17125 if (id == GRN_ID_NIL) {
17126 key = nullptr;
17127 key_size = 0;
17128 } else if (get_key_optimizable_) {
17129 key = _grn_table_key(ctx_, ii_->lexicon, id, &key_size);
17130 } else {
17131 GRN_BULK_REWIND(&key_buffer);
17132 grn_table_get_key2(ctx_, ii_->lexicon, id, &key_buffer);
17133 key = GRN_BULK_HEAD(&key_buffer);
17134 key_size = GRN_BULK_VSIZE(&key_buffer);
17135 }
17136 rc = append_value(src,
17137 rid,
17138 sid,
17139 (uint32_t)weight,
17140 key,
17141 key_size,
17142 ii_->lexicon->header.domain,
17143 true);
17144 if (rc != GRN_SUCCESS) {
17145 break;
17146 }
17147 }
17148 GRN_OBJ_FIN(ctx_, &key_buffer);
17149 } else {
17150 const char *p = GRN_BULK_HEAD(obj);
17151 uint32_t value_size = grn_uvector_element_size(ctx_, obj);
17152 for (i = 0; i < n_values; i++) {
17153 rc = append_value(src,
17154 rid,
17155 sid,
17156 0,
17157 p,
17158 value_size,
17159 obj->header.domain,
17160 false);
17161 if (rc != GRN_SUCCESS) {
17162 break;
17163 }
17164 p += value_size;
17165 }
17166 }
17167 return rc;
17168 }
17169 case GRN_VECTOR:
17170 if (obj->u.v.body) {
17171 /*
17172 * Note that the following sections and n_sections don't correspond to
17173 * source columns.
17174 */
17175 int i, n_secs = obj->u.v.n_sections;
17176 grn_section *secs = obj->u.v.sections;
17177 const char *head = GRN_BULK_HEAD(obj->u.v.body);
17178 for (i = 0; i < n_secs; i++) {
17179 grn_rc rc;
17180 grn_section *sec = &secs[i];
17181 if (sec->length == 0) {
17182 continue;
17183 }
17184 if ((ii_->header.common->flags & GRN_OBJ_WITH_SECTION) &&
17185 have_tokenizer_) {
17186 sid = i + 1;
17187 }
17188 rc = append_value(src,
17189 rid,
17190 sid,
17191 (uint32_t)(sec->weight),
17192 head + sec->offset,
17193 sec->length,
17194 sec->domain,
17195 false);
17196 if (rc != GRN_SUCCESS) {
17197 return rc;
17198 }
17199 }
17200 }
17201 return GRN_SUCCESS;
17202 default:
17203 {
17204 auto ctx = ctx_;
17205 ERR(GRN_INVALID_ARGUMENT, "[index] invalid object assigned as value");
17206 return ctx->rc;
17207 }
17208 }
17209 }
17210 };
17211
17212 struct Builder {
17213 Builder(grn_ctx *ctx, grn_ii *ii, const grn_ii_builder_options *options)
17214 : ctx_(ctx),
17215 ii_(ii)
17216 {
17217 progress_needed_ = (grn_ctx_get_progress_callback(ctx_) != nullptr);
17218 if (progress_needed_) {
17219 progress_.type = GRN_PROGRESS_INDEX;
17220 progress_.value.index.phase = GRN_PROGRESS_INDEX_INITIALIZE;
17221 progress_.value.index.n_target_records = 0;
17222 progress_.value.index.n_processed_records = 0;
17223 progress_.value.index.n_target_terms = 0;
17224 progress_.value.index.n_processed_terms = 0;
17225 grn_ctx_call_progress_callback(ctx, &progress_);
17226 }
17227
17228 if (options) {
17229 options_ = *options;
17230 } else {
17231 options_ = grn_ii_builder_default_options;
17232 }
17233
17234 if (grn_ii_builder_block_threshold_force > 0) {
17235 options_.block_threshold = grn_ii_builder_block_threshold_force;
17236 }
17237 grn_ii_builder_options_fix(&options_);
17238
17239 src_table_ = nullptr;
17240 n_records_ = 0;
17241 GRN_PTR_INIT(&srcs_, GRN_OBJ_VECTOR, GRN_ID_NIL);
17242 src_token_columns_ = nullptr;
17243 sid_bits_ = 0;
17244 sid_mask_ = 0;
17245
17246 path_[0] = '\0';
17247 fd_ = -1;
17248 file_buf_ = nullptr;
17249 file_buf_offset_ = 0;
17250
17251 blocks_ = nullptr;
17252 n_blocks_ = 0;
17253 blocks_size_ = 0;
17254
17255 grn_ii_builder_buffer_init(ctx, &buf_, ii);
17256 grn_ii_builder_chunk_init(ctx, &chunk_, ii);
17257
17258 df_ = 0;
17259 cinfos_ = nullptr;
17260 n_cinfos_ = 0;
17261 cinfos_size_ = 0;
17262 }
17263
17264 ~Builder()
17265 {
17266 if (progress_needed_) {
17267 progress_.value.index.phase = GRN_PROGRESS_INDEX_FINALIZE;
17268 grn_ctx_call_progress_callback(ctx_, &progress_);
17269 }
17270
17271 if (cinfos_) {
17272 auto ctx = ctx_;
17273 GRN_FREE(cinfos_);
17274 }
17275 grn_ii_builder_chunk_fin(ctx_, &chunk_);
17276 grn_ii_builder_buffer_fin(ctx_, &buf_);
17277 if (blocks_) {
17278 uint32_t i;
17279 for (i = 0; i < n_blocks_; i++) {
17280 grn_ii_builder_block_fin(ctx_, &(blocks_[i]));
17281 }
17282 auto ctx = ctx_;
17283 GRN_FREE(blocks_);
17284 }
17285 if (file_buf_) {
17286 auto ctx = ctx_;
17287 GRN_FREE(file_buf_);
17288 }
17289 if (fd_ != -1) {
17290 grn_close(fd_);
17291 if (grn_unlink(path_) == 0) {
17292 GRN_LOG(ctx_,
17293 GRN_LOG_INFO,
17294 "[ii][builder][fin] removed path: <%s>",
17295 path_);
17296 } else {
17297 auto ctx = ctx_;
17298 ERRNO_ERR("[ii][builder][fin] failed to remove path: <%s>", path_);
17299 }
17300 }
17301 const uint32_t n_srcs = GRN_PTR_VECTOR_SIZE(&srcs_);
17302 if (n_srcs > 0) {
17303 uint32_t i;
17304 for (i = 0; i < n_srcs; i++) {
17305 grn_obj_unref(ctx_, GRN_PTR_VALUE_AT(&srcs_, i));
17306 }
17307 }
17308 GRN_OBJ_FIN(ctx_, &srcs_);
17309 if (src_token_columns_) {
17310 uint32_t i;
17311 for (i = 0; i < n_srcs; i++) {
17312 grn_obj_unref(ctx_, src_token_columns_[i]);
17313 }
17314 auto ctx = ctx_;
17315 GRN_FREE(src_token_columns_);
17316 }
17317 if (src_table_) {
17318 grn_obj_unref(ctx_, src_table_);
17319 }
17320 if (progress_needed_) {
17321 progress_.value.index.phase = GRN_PROGRESS_INDEX_DONE;
17322 grn_ctx_call_progress_callback(ctx_, &progress_);
17323 }
17324 }
17325
17326 // Flushes buffered data as a block.
17327 grn_rc
17328 flush_file_buf()
17329 {
17330 if (file_buf_offset_) {
17331 auto size = grn_write(fd_, file_buf_, file_buf_offset_);
17332 if (static_cast<uint64_t>(size) != file_buf_offset_) {
17333 auto ctx = ctx_;
17334 SERR("failed to write data: expected = %u, actual = %" GRN_FMT_INT64D,
17335 file_buf_offset_,
17336 static_cast<int64_t>(size));
17337 }
17338 file_buf_offset_ = 0;
17339 }
17340 return GRN_SUCCESS;
17341 }
17342
17343 // Creates a temporary file and allocates memory for buffered
17344 // output.
17345 grn_rc
17346 create_file()
17347 {
17348 auto ctx = ctx_;
17349 grn_snprintf(path_,
17350 PATH_MAX,
17351 PATH_MAX,
17352 "%sXXXXXX",
17353 grn_io_path(ii_->seg));
17354 fd_ = grn_mkstemp(path_);
17355 if (fd_ == -1) {
17356 SERR("failed to create a temporary file: path = \"%s\"", path_);
17357 return ctx->rc;
17358 }
17359 file_buf_ =
17360 reinterpret_cast<uint8_t *>(GRN_MALLOC(options_.file_buf_size));
17361 if (!file_buf_) {
17362 ERR(GRN_NO_MEMORY_AVAILABLE,
17363 "failed to allocate memory for buffered output: size = %u",
17364 options_.file_buf_size);
17365 return ctx->rc;
17366 }
17367 return GRN_SUCCESS;
17368 }
17369
17370 // Flushes a term and clears it
17371 grn_rc
17372 flush_term(grn_ii_builder_term *term,
17373 grn_obj *local_lexicon,
17374 grn_id local_tid)
17375 {
17376 /* Append sentinels. */
17377 if (term->rid != GRN_ID_NIL) {
17378 grn_rc rc;
17379 if (ii_->header.common->flags & GRN_OBJ_WITH_POSITION) {
17380
17381 rc = grn_ii_builder_term_append(ctx_, term, 0);
17382 } else {
17383 rc = grn_ii_builder_term_append(ctx_, term, term->pos_or_freq);
17384 }
17385 if (rc != GRN_SUCCESS) {
17386 return rc;
17387 }
17388 }
17389 {
17390 auto rc = grn_ii_builder_term_append(ctx_, term, 0);
17391 if (rc != GRN_SUCCESS) {
17392 return rc;
17393 }
17394 }
17395
17396 {
17397 /* Put the global term ID. */
17398 int key_size;
17399 char key[GRN_TABLE_MAX_KEY_SIZE];
17400 uint8_t *p;
17401 uint32_t rest, value;
17402 grn_id global_tid = GRN_ID_NIL;
17403 key_size = grn_table_get_key(ctx_,
17404 local_lexicon,
17405 local_tid,
17406 key,
17407 GRN_TABLE_MAX_KEY_SIZE);
17408 if (!key_size) {
17409 if (ctx_->rc == GRN_SUCCESS) {
17410 auto ctx = ctx_;
17411 ERR(GRN_UNKNOWN_ERROR, "failed to get key: tid = %u", local_tid);
17412 }
17413 return ctx_->rc;
17414 }
17415 /* Don't normalize key. */
17416 switch (ii_->lexicon->header.type) {
17417 case GRN_TABLE_PAT_KEY:
17418 GRN_TABLE_LOCK_BEGIN(ctx_, ii_->lexicon)
17419 {
17420 global_tid = grn_pat_add(ctx_,
17421 reinterpret_cast<grn_pat *>(ii_->lexicon),
17422 key,
17423 key_size,
17424 nullptr,
17425 nullptr);
17426 }
17427 GRN_TABLE_LOCK_END(ctx_);
17428 break;
17429 case GRN_TABLE_DAT_KEY:
17430 GRN_TABLE_LOCK_BEGIN(ctx_, ii_->lexicon)
17431 {
17432 global_tid = grn_dat_add(ctx_,
17433 reinterpret_cast<grn_dat *>(ii_->lexicon),
17434 key,
17435 key_size,
17436 nullptr,
17437 nullptr);
17438 }
17439 GRN_TABLE_LOCK_END(ctx_);
17440 break;
17441 case GRN_TABLE_HASH_KEY:
17442 GRN_TABLE_LOCK_BEGIN(ctx_, ii_->lexicon)
17443 {
17444 global_tid =
17445 grn_hash_add(ctx_,
17446 reinterpret_cast<grn_hash *>(ii_->lexicon),
17447 key,
17448 key_size,
17449 nullptr,
17450 nullptr);
17451 }
17452 GRN_TABLE_LOCK_END(ctx_);
17453 break;
17454 default:
17455 global_tid = GRN_ID_NIL;
17456 break;
17457 }
17458 if (global_tid == GRN_ID_NIL) {
17459 if (ctx_->rc == GRN_SUCCESS) {
17460 auto ctx = ctx_;
17461 ERR(GRN_UNKNOWN_ERROR,
17462 "failed to get global term ID: tid = %u, key = \"%.*s\"",
17463 local_tid,
17464 key_size,
17465 key);
17466 }
17467 return ctx_->rc;
17468 }
17469
17470 rest = options_.file_buf_size - file_buf_offset_;
17471 if (rest < 10) {
17472 auto rc = flush_file_buf();
17473 if (rc != GRN_SUCCESS) {
17474 return rc;
17475 }
17476 }
17477 value = global_tid;
17478 p = file_buf_ + file_buf_offset_;
17479 if (value < 1U << 5) {
17480 p[0] = static_cast<uint8_t>(value);
17481 file_buf_offset_++;
17482 } else if (value < 1U << 13) {
17483 p[0] = static_cast<uint8_t>((value & 0x1f) | (1 << 5));
17484 p[1] = static_cast<uint8_t>(value >> 5);
17485 file_buf_offset_ += 2;
17486 } else {
17487 uint8_t i, n;
17488 if (value < 1U << 21) {
17489 n = 3;
17490 } else if (value < 1U << 29) {
17491 n = 4;
17492 } else {
17493 n = 5;
17494 }
17495 p[0] = static_cast<uint8_t>(value & 0x1f) | ((n - 1) << 5);
17496 value >>= 5;
17497 for (i = 1; i < n; i++) {
17498 p[i] = static_cast<uint8_t>(value);
17499 value >>= 8;
17500 }
17501 file_buf_offset_ += n;
17502 }
17503 }
17504
17505 /* Flush a term buffer. */
17506 auto term_buf = grn_ii_builder_term_get_buf(term);
17507 if (term->offset > options_.file_buf_size) {
17508 ssize_t size;
17509 auto rc = flush_file_buf();
17510 if (rc != GRN_SUCCESS) {
17511 return rc;
17512 }
17513 size = grn_write(fd_, term_buf, term->offset);
17514 if (static_cast<uint64_t>(size) != term->offset) {
17515 auto ctx = ctx_;
17516 SERR("failed to write data: expected = %u, actual = %" GRN_FMT_INT64D,
17517 term->offset,
17518 static_cast<int64_t>(size));
17519 }
17520 } else {
17521 uint32_t rest = options_.file_buf_size - file_buf_offset_;
17522 if (term->offset <= rest) {
17523 grn_memcpy(file_buf_ + file_buf_offset_, term_buf, term->offset);
17524 file_buf_offset_ += term->offset;
17525 } else {
17526 grn_memcpy(file_buf_ + file_buf_offset_, term_buf, rest);
17527 file_buf_offset_ += rest;
17528 auto rc = flush_file_buf();
17529 if (rc != GRN_SUCCESS) {
17530 return rc;
17531 }
17532 file_buf_offset_ = term->offset - rest;
17533 grn_memcpy(file_buf_, term_buf + rest, file_buf_offset_);
17534 }
17535 }
17536 grn_ii_builder_term_reinit(ctx_, term);
17537 return GRN_SUCCESS;
17538 }
17539
17540 // Registers a block.
17541 grn_rc
17542 register_block()
17543 {
17544 uint64_t file_offset = grn_lseek(fd_, 0, SEEK_CUR);
17545 if (file_offset == static_cast<uint64_t>(-1)) {
17546 auto ctx = ctx_;
17547 SERR("failed to get file offset");
17548 return ctx->rc;
17549 }
17550 if (n_blocks_ >= blocks_size_) {
17551 uint32_t new_blocks_size = 1;
17552 while (new_blocks_size <= n_blocks_) {
17553 new_blocks_size *= 2;
17554 }
17555 auto ctx = ctx_;
17556 auto n_bytes = new_blocks_size * sizeof(grn_ii_builder_block);
17557 auto new_blocks = reinterpret_cast<grn_ii_builder_block *>(
17558 GRN_REALLOC(blocks_, n_bytes));
17559 if (!new_blocks) {
17560 ERR(GRN_NO_MEMORY_AVAILABLE,
17561 "failed to allocate memory for block: n_bytes = %" GRN_FMT_SIZE,
17562 n_bytes);
17563 return ctx->rc;
17564 }
17565 blocks_ = new_blocks;
17566 blocks_size_ = new_blocks_size;
17567 }
17568 auto block = &(blocks_[n_blocks_]);
17569 grn_ii_builder_block_init(ctx_, block);
17570 if (n_blocks_ == 0) {
17571 block->offset = 0;
17572 } else {
17573 auto prev_block = &(blocks_[n_blocks_ - 1]);
17574 block->offset = prev_block->offset + prev_block->rest;
17575 }
17576 block->rest = static_cast<uint32_t>(file_offset - block->offset);
17577 n_blocks_++;
17578 return GRN_SUCCESS;
17579 }
17580
17581 // Flushes a block to a temporary file.
17582 grn_rc
17583 flush_block_builder(BlockBuilder *block_builder)
17584 {
17585 auto rc = block_builder->flush(
17586 [&](grn_ii_builder_term *term, grn_obj *lexicon, grn_id tid) {
17587 if (fd_ == -1) {
17588 auto rc = create_file();
17589 if (rc != GRN_SUCCESS) {
17590 return rc;
17591 }
17592 }
17593 return flush_term(term, lexicon, tid);
17594 });
17595 if (rc == GRN_SUCCESS) {
17596 rc = flush_file_buf();
17597 }
17598 if (rc == GRN_SUCCESS) {
17599 // Register a block in a temporary file.
17600 rc = register_block();
17601 }
17602 return rc;
17603 }
17604
17605 // Reads values from source columns and appends the values in parallel.
17606 grn_rc
17607 append_srcs_parallel(grn::TaskExecutor *executor, size_t n_records_per_task)
17608 {
17609 std::mutex mutex;
17610 std::condition_variable cv;
17611 std::map<int, std::unique_ptr<BlockBuilder>> processed_block_builders;
17612 auto limit = static_cast<int>(n_records_per_task);
17613 for (int offset = 0; offset < static_cast<int>(n_records_);
17614 offset += limit) {
17615 auto execute = [&, offset, limit]() {
17616 auto child_ctx = grn_ctx_pull_child(ctx_);
17617 auto block_builder =
17618 std::make_unique<BlockBuilder>(ctx_,
17619 child_ctx,
17620 ii_,
17621 &options_,
17622 src_table_,
17623 &srcs_,
17624 src_token_columns_,
17625 sid_bits_);
17626 auto rc = block_builder->prepare();
17627 if (rc != GRN_SUCCESS) {
17628 return false;
17629 }
17630 auto cursor = grn_table_cursor_open(child_ctx,
17631 src_table_,
17632 nullptr,
17633 0,
17634 nullptr,
17635 0,
17636 offset,
17637 limit,
17638 GRN_CURSOR_BY_ID);
17639 if (cursor) {
17640 while (true) {
17641 auto rid = grn_table_cursor_next(child_ctx, cursor);
17642 if (rid == GRN_ID_NIL) {
17643 break;
17644 }
17645 rc = block_builder->append_record(rid);
17646 if (rc != GRN_SUCCESS) {
17647 break;
17648 }
17649 }
17650 grn_table_cursor_close(child_ctx, cursor);
17651 }
17652 {
17653 std::lock_guard<std::mutex> lock(mutex);
17654 processed_block_builders.insert(
17655 std::make_pair(offset, std::move(block_builder)));
17656 }
17657 cv.notify_one();
17658 return rc == GRN_SUCCESS;
17659 };
17660 if (!executor->execute(offset,
17661 execute,
17662 "[index][builder][append-src][parallel]")) {
17663 executor->wait_all();
17664 return ctx_->rc;
17665 }
17666 }
17667
17668 for (int offset = 0; offset < static_cast<int>(n_records_);
17669 offset += limit) {
17670 std::unique_ptr<BlockBuilder> block_builder;
17671 {
17672 std::unique_lock<std::mutex> lock(mutex);
17673 cv.wait(lock, [&] {
17674 return ctx_->rc != GRN_SUCCESS ||
17675 processed_block_builders.find(offset) !=
17676 processed_block_builders.end();
17677 });
17678 if (ctx_->rc == GRN_SUCCESS) {
17679 auto iter = processed_block_builders.find(offset);
17680 block_builder = std::move(iter->second);
17681 processed_block_builders.erase(iter);
17682 }
17683 }
17684 if (ctx_->rc != GRN_SUCCESS) {
17685 break;
17686 }
17687 if (!block_builder) {
17688 break;
17689 }
17690 auto n_processed_records = block_builder->n_processed_records();
17691 if (block_builder->have_data()) {
17692 auto rc = flush_block_builder(block_builder.get());
17693 if (rc != GRN_SUCCESS) {
17694 break;
17695 }
17696 }
17697 if (progress_needed_) {
17698 progress_.value.index.n_processed_records += n_processed_records;
17699 grn_ctx_call_progress_callback(ctx_, &progress_);
17700 }
17701 }
17702 executor->wait_all();
17703 return ctx_->rc;
17704 }
17705
17706 // Reads values from source columns and appends the values in sequential.
17707 grn_rc
17708 append_srcs_sequential()
17709 {
17710 BlockBuilder block_builder(nullptr,
17711 ctx_,
17712 ii_,
17713 &options_,
17714 src_table_,
17715 &srcs_,
17716 src_token_columns_,
17717 sid_bits_);
17718 auto rc = block_builder.prepare();
17719 if (rc != GRN_SUCCESS) {
17720 return rc;
17721 }
17722
17723 /* Create a cursor to get records in the ID order. */
17724 GRN_TABLE_EACH_BEGIN_FLAGS(ctx_,
17725 src_table_,
17726 cursor,
17727 rid,
17728 GRN_CURSOR_BY_ID)
17729 {
17730 /* Read source values and append it. */
17731 rc = block_builder.append_record(rid);
17732 if (rc == GRN_SUCCESS && block_builder.need_flush()) {
17733 rc = flush_block_builder(&block_builder);
17734 }
17735 if (rc != GRN_SUCCESS) {
17736 break;
17737 }
17738 if (progress_needed_) {
17739 progress_.value.index.n_processed_records++;
17740 grn_ctx_call_progress_callback(ctx_, &progress_);
17741 }
17742 }
17743 GRN_TABLE_EACH_END(ctx_, cursor);
17744 if (rc == GRN_SUCCESS && block_builder.have_data()) {
17745 rc = flush_block_builder(&block_builder);
17746 }
17747 return rc;
17748 }
17749
17750 grn_rc
17751 build(grn_obj *tokenizer)
17752 {
17753 grn_tokenizer_build_data data;
17754 data.source_table = src_table_;
17755 data.source_columns = &srcs_;
17756 data.lexicon = ii_->lexicon;
17757 data.index_column = reinterpret_cast<grn_obj *>(ii_);
17758 BlockBuilder block_builder(nullptr,
17759 ctx_,
17760 ii_,
17761 &options_,
17762 src_table_,
17763 &srcs_,
17764 src_token_columns_,
17765 sid_bits_);
17766 auto rc = block_builder.prepare();
17767 if (rc != GRN_SUCCESS) {
17768 return rc;
17769 }
17770 struct UserData {
17771 Builder *builder;
17772 BlockBuilder *block_builder;
17773 grn_id current_rid;
17774 uint32_t current_sid;
17775 bool progress_needed;
17776 grn_progress *progress;
17777 } user_data;
17778 user_data.builder = this;
17779 user_data.block_builder = &block_builder;
17780 user_data.current_rid = GRN_ID_NIL;
17781 user_data.current_sid = 0;
17782 user_data.progress_needed = progress_needed_;
17783 user_data.progress = &progress_;
17784 data.processed_n_records_func = [](grn_ctx *ctx,
17785 grn_tokenizer_build_data *data,
17786 uint32_t n_records,
17787 void *user_data) {
17788 auto user_data_ = static_cast<UserData *>(user_data);
17789 if (user_data_->progress_needed) {
17790 user_data_->progress->value.index.n_processed_records += n_records;
17791 grn_ctx_call_progress_callback(ctx, user_data_->progress);
17792 }
17793 return GRN_SUCCESS;
17794 };
17795 data.start_vectorize_func = [](grn_ctx *ctx,
17796 grn_tokenizer_build_data *data,
17797 uint32_t n_total_records,
17798 void *user_data) {
17799 auto user_data_ = static_cast<UserData *>(user_data);
17800 if (user_data_->progress_needed) {
17801 user_data_->progress->value.index.phase =
17802 GRN_PROGRESS_INDEX_VECTORIZE;
17803 user_data_->progress->value.index.n_target_records = n_total_records;
17804 user_data_->progress->value.index.n_processed_records = 0;
17805 grn_ctx_call_progress_callback(ctx, user_data_->progress);
17806 }
17807 return GRN_SUCCESS;
17808 };
17809 data.start_cluster_func = [](grn_ctx *ctx,
17810 grn_tokenizer_build_data *data,
17811 uint32_t n_total_records,
17812 void *user_data) {
17813 auto user_data_ = static_cast<UserData *>(user_data);
17814 if (user_data_->progress_needed) {
17815 user_data_->progress->value.index.phase = GRN_PROGRESS_INDEX_CLUSTER;
17816 user_data_->progress->value.index.n_target_records = n_total_records;
17817 user_data_->progress->value.index.n_processed_records = 0;
17818 grn_ctx_call_progress_callback(ctx, user_data_->progress);
17819 }
17820 return GRN_SUCCESS;
17821 };
17822 data.start_load_func = [](grn_ctx *ctx,
17823 grn_tokenizer_build_data *data,
17824 uint32_t n_total_records,
17825 void *user_data) {
17826 auto user_data_ = static_cast<UserData *>(user_data);
17827 if (user_data_->progress_needed) {
17828 user_data_->progress->value.index.phase = GRN_PROGRESS_INDEX_LOAD;
17829 user_data_->progress->value.index.n_target_records = n_total_records;
17830 user_data_->progress->value.index.n_processed_records = 0;
17831 grn_ctx_call_progress_callback(ctx, user_data_->progress);
17832 }
17833 return GRN_SUCCESS;
17834 };
17835 data.start_record_func = [](grn_ctx *ctx,
17836 grn_tokenizer_build_data *data,
17837 grn_id rid,
17838 void *user_data) {
17839 auto user_data_ = static_cast<UserData *>(user_data);
17840 user_data_->current_rid = rid;
17841 return GRN_SUCCESS;
17842 };
17843 data.start_section_func = [](grn_ctx *ctx,
17844 grn_tokenizer_build_data *data,
17845 uint32_t sid,
17846 void *user_data) {
17847 auto user_data_ = static_cast<UserData *>(user_data);
17848 user_data_->current_sid = sid;
17849 return GRN_SUCCESS;
17850 };
17851 data.append_tokens_func = [](grn_ctx *ctx,
17852 grn_tokenizer_build_data *data,
17853 grn_obj *tokens,
17854 void *user_data) {
17855 auto user_data_ = static_cast<UserData *>(user_data);
17856 return user_data_->block_builder->append_tokens(user_data_->current_rid,
17857 user_data_->current_sid,
17858 tokens);
17859 };
17860 data.finish_section_func = [](grn_ctx *ctx,
17861 grn_tokenizer_build_data *data,
17862 void *user_data) { return GRN_SUCCESS; };
17863 data.finish_record_func = [](grn_ctx *ctx,
17864 grn_tokenizer_build_data *data,
17865 void *user_data) {
17866 auto user_data_ = static_cast<UserData *>(user_data);
17867 user_data_->block_builder->finish_record();
17868 if (user_data_->block_builder->need_flush()) {
17869 auto rc =
17870 user_data_->builder->flush_block_builder(user_data_->block_builder);
17871 if (rc != GRN_SUCCESS) {
17872 return rc;
17873 }
17874 }
17875 if (user_data_->builder->progress_needed_) {
17876 user_data_->builder->progress_.value.index.n_processed_records++;
17877 grn_ctx_call_progress_callback(ctx,
17878 &(user_data_->builder->progress_));
17879 }
17880 return GRN_SUCCESS;
17881 };
17882 data.user_data = &user_data;
17883 rc = grn_tokenizer_build(ctx_, tokenizer, &data);
17884 if (rc == GRN_SUCCESS && block_builder.have_data()) {
17885 rc = flush_block_builder(&block_builder);
17886 }
17887 return rc;
17888 }
17889
17890 // Reads values from source columns and appends the values.
17891 grn_rc
17892 append_srcs()
17893 {
17894 if (grn_table_have_tokenizer(ctx_, ii_->lexicon)) {
17895 auto tokenizer = grn_obj_get_info(ctx_,
17896 ii_->lexicon,
17897 GRN_INFO_DEFAULT_TOKENIZER,
17898 nullptr);
17899 if (grn_tokenizer_have_build_func(ctx_, tokenizer)) {
17900 return build(tokenizer);
17901 }
17902 }
17903
17904 if (progress_needed_) {
17905 progress_.value.index.phase = GRN_PROGRESS_INDEX_LOAD;
17906 progress_.value.index.n_target_records = n_records_;
17907 progress_.value.index.n_processed_records = 0;
17908 grn_ctx_call_progress_callback(ctx_, &progress_);
17909 }
17910
17911 auto task_executor = grn_ctx_get_task_executor(ctx_);
17912 if (!task_executor->is_parallel()) {
17913 return append_srcs_sequential();
17914 }
17915
17916 // This is a heuristic rule. We may want to revisit this.
17917 const size_t n_postings_per_source = 1024; // No reason.
17918 const size_t max_n_records_per_task =
17919 options_.block_threshold /
17920 (n_postings_per_source * GRN_PTR_VECTOR_SIZE(&srcs_));
17921 const size_t max_n_records_per_worker =
17922 n_records_ / task_executor->get_n_workers();
17923 const size_t min_n_records_per_task = 10240; // No reason.
17924 const size_t n_records_per_task =
17925 std::max(std::min(max_n_records_per_task, max_n_records_per_worker),
17926 min_n_records_per_task);
17927 if (n_records_ < n_records_per_task) {
17928 return append_srcs_sequential();
17929 } else {
17930 return append_srcs_parallel(task_executor, n_records_per_task);
17931 }
17932 }
17933
17934 // Sets a source table.
17935 grn_rc
17936 set_src_table()
17937 {
17938 src_table_ = grn_ctx_at(ctx_, DB_OBJ(ii_)->range);
17939 if (!src_table_) {
17940 if (ctx_->rc == GRN_SUCCESS) {
17941 auto ctx = ctx_;
17942 ERR(GRN_INVALID_ARGUMENT,
17943 "source table is null: range = %d",
17944 DB_OBJ(ii_)->range);
17945 }
17946 return ctx_->rc;
17947 }
17948 n_records_ = grn_table_size(ctx_, src_table_);
17949 return GRN_SUCCESS;
17950 }
17951
17952 // Calculates sid_bits_ and sid_mask_.
17953 grn_rc
17954 set_sid_bits()
17955 {
17956 /* Calculate the number of bits required to represent a section ID. */
17957 if (GRN_PTR_VECTOR_SIZE(&srcs_) == 1 &&
17958 grn_table_have_tokenizer(ctx_, ii_->lexicon) &&
17959 (GRN_PTR_VALUE_AT(&srcs_, 0)->header.flags & GRN_OBJ_COLUMN_VECTOR) !=
17960 0) {
17961 /* If the source column is a vector column and the index has a
17962 * tokenizer, the maximum sid equals to the maximum number of
17963 * elements. */
17964 size_t max_elems = 0;
17965 grn_table_cursor *cursor;
17966 grn_obj obj;
17967 cursor = grn_table_cursor_open(ctx_,
17968 src_table_,
17969 NULL,
17970 0,
17971 NULL,
17972 0,
17973 0,
17974 -1,
17975 GRN_CURSOR_BY_ID);
17976 if (!cursor) {
17977 if (ctx_->rc == GRN_SUCCESS) {
17978 auto ctx = ctx_;
17979 ERR(GRN_OBJECT_CORRUPT, "[index] failed to open table cursor");
17980 }
17981 return ctx_->rc;
17982 }
17983 GRN_TEXT_INIT(&obj, 0);
17984 for (;;) {
17985 grn_id rid = grn_table_cursor_next(ctx_, cursor);
17986 if (rid == GRN_ID_NIL) {
17987 break;
17988 }
17989 GRN_BULK_REWIND(&obj);
17990 if (!grn_obj_get_value(ctx_,
17991 GRN_PTR_VALUE_AT(&srcs_, 0),
17992 rid,
17993 &obj)) {
17994 continue;
17995 }
17996 if (obj.u.v.n_sections > max_elems) {
17997 max_elems = obj.u.v.n_sections;
17998 }
17999 }
18000 GRN_OBJ_FIN(ctx_, &obj);
18001 grn_table_cursor_close(ctx_, cursor);
18002 while ((static_cast<uint32_t>(1) << sid_bits_) < max_elems) {
18003 sid_bits_++;
18004 }
18005 }
18006 if (sid_bits_ == 0) {
18007 const uint32_t n_srcs = GRN_PTR_VECTOR_SIZE(&srcs_);
18008 while ((static_cast<uint32_t>(1) << sid_bits_) < n_srcs) {
18009 sid_bits_++;
18010 }
18011 }
18012 sid_mask_ = (static_cast<uint64_t>(1) << sid_bits_) - 1;
18013 return GRN_SUCCESS;
18014 }
18015
18016 // Sets source columns.
18017 grn_rc
18018 set_srcs()
18019 {
18020 uint32_t n_srcs = ii_->obj.source_size / sizeof(grn_id);
18021 auto source = static_cast<grn_id *>(ii_->obj.source);
18022 if (!source || n_srcs == 0) {
18023 auto ctx = ctx_;
18024 ERR(GRN_INVALID_ARGUMENT,
18025 "source is not available: source = %p, source_size = %u",
18026 ii_->obj.source,
18027 ii_->obj.source_size);
18028 return ctx->rc;
18029 }
18030 for (size_t i = 0; i < n_srcs; i++) {
18031 grn_obj *src = grn_ctx_at(ctx_, source[i]);
18032 if (!src) {
18033 if (ctx_->rc == GRN_SUCCESS) {
18034 auto ctx = ctx_;
18035 ERR(GRN_OBJECT_CORRUPT, "source not found: id = %d", source[i]);
18036 }
18037 return ctx_->rc;
18038 }
18039 GRN_PTR_PUT(ctx_, &srcs_, src);
18040 }
18041 {
18042 auto ctx = ctx_;
18043 src_token_columns_ = GRN_MALLOCN(grn_obj *, n_srcs);
18044 }
18045 if (!src_token_columns_) {
18046 return GRN_NO_MEMORY_AVAILABLE;
18047 }
18048 {
18049 grn_obj token_columns;
18050 GRN_PTR_INIT(&token_columns, GRN_OBJ_VECTOR, GRN_ID_NIL);
18051 for (size_t i = 0; i < n_srcs; i++) {
18052 src_token_columns_[i] = nullptr;
18053 auto src = GRN_PTR_VALUE_AT(&srcs_, i);
18054 grn_column_get_all_token_columns(ctx_, src, &token_columns);
18055 size_t n_token_columns = GRN_PTR_VECTOR_SIZE(&token_columns);
18056 for (size_t j = 0; j < n_token_columns; j++) {
18057 grn_obj *token_column = GRN_PTR_VALUE_AT(&token_columns, j);
18058 if (!src_token_columns_[i] &&
18059 DB_OBJ(token_column)->range == DB_OBJ(ii_->lexicon)->id) {
18060 src_token_columns_[i] = token_column;
18061 } else {
18062 grn_obj_unref(ctx_, token_column);
18063 }
18064 }
18065 GRN_BULK_REWIND(&token_columns);
18066 }
18067 GRN_OBJ_FIN(ctx_, &token_columns);
18068 }
18069 return set_sid_bits();
18070 }
18071
18072 // Appends values in source columns.
18073 grn_rc
18074 append_source()
18075 {
18076 auto rc = set_src_table();
18077 if (rc != GRN_SUCCESS) {
18078 return rc;
18079 }
18080 if (n_records_ == 0) {
18081 /* Nothing to do because there are no values. */
18082 return ctx_->rc;
18083 }
18084 rc = set_srcs();
18085 if (rc != GRN_SUCCESS) {
18086 return rc;
18087 }
18088 rc = append_srcs();
18089 if (rc != GRN_SUCCESS) {
18090 return rc;
18091 }
18092 return GRN_SUCCESS;
18093 }
18094
18095 // Reads the next data from a temporary file and fill a block
18096 // buffer.
18097 grn_rc
18098 fill_block(uint32_t block_id)
18099 {
18100 grn_ii_builder_block *block = &(blocks_[block_id]);
18101 if (!block->rest) {
18102 return GRN_END_OF_DATA;
18103 }
18104 if (!block->buf) {
18105 auto ctx = ctx_;
18106 block->buf =
18107 reinterpret_cast<uint8_t *>(GRN_MALLOC(options_.block_buf_size));
18108 if (!block->buf) {
18109 ERR(GRN_NO_MEMORY_AVAILABLE,
18110 "failed to allocate memory for buffered input: size = %u",
18111 options_.block_buf_size);
18112 return ctx->rc;
18113 }
18114 }
18115
18116 /* Move the remaining data to the head. */
18117 uint32_t buf_rest = block->end - block->cur;
18118 if (buf_rest) {
18119 grn_memmove(block->buf, block->cur, buf_rest);
18120 }
18121 block->cur = block->buf;
18122 block->end = block->buf + buf_rest;
18123
18124 /* Read the next data. */
18125 uint64_t file_offset = grn_lseek(fd_, block->offset, SEEK_SET);
18126 if (file_offset != block->offset) {
18127 auto ctx = ctx_;
18128 SERR("failed to seek file: expected = %" GRN_FMT_INT64U
18129 ", actual = %" GRN_FMT_INT64D,
18130 block->offset,
18131 file_offset);
18132 return ctx->rc;
18133 }
18134 buf_rest = options_.block_buf_size - buf_rest;
18135 if (block->rest < buf_rest) {
18136 buf_rest = block->rest;
18137 }
18138 ssize_t size = grn_read(fd_, block->end, buf_rest);
18139 if (size <= 0) {
18140 auto ctx = ctx_;
18141 SERR("failed to read data: expected = %u, actual = %" GRN_FMT_INT64D,
18142 buf_rest,
18143 static_cast<int64_t>(size));
18144 return ctx->rc;
18145 }
18146 block->offset += size;
18147 block->rest -= size;
18148 block->end += size;
18149 return GRN_SUCCESS;
18150 }
18151
18152 // Reads the next value from a block.
18153 grn_rc
18154 read_from_block(uint32_t block_id, uint64_t *value)
18155 {
18156 grn_ii_builder_block *block = &(blocks_[block_id]);
18157 grn_rc rc = grn_ii_builder_block_next(ctx_, block, value);
18158 if (rc == GRN_SUCCESS) {
18159 return GRN_SUCCESS;
18160 } else if (rc == GRN_END_OF_DATA) {
18161 rc = fill_block(block_id);
18162 if (rc != GRN_SUCCESS) {
18163 return rc;
18164 }
18165 return grn_ii_builder_block_next(ctx_, block, value);
18166 }
18167 return rc;
18168 }
18169
18170 // Tries to pack a chunk.
18171 grn_rc
18172 pack_chunk(bool *packed)
18173 {
18174 *packed = false;
18175 if (chunk_.offset != 1) { /* df != 1 */
18176 return GRN_SUCCESS;
18177 }
18178 if (chunk_.weight_buf && chunk_.weight_buf[0]) { /* weight != 0 */
18179 return GRN_SUCCESS;
18180 }
18181 if (chunk_.freq_buf[0] != 0) { /* freq != 1 */
18182 return GRN_SUCCESS;
18183 }
18184 grn_id rid = chunk_.rid_buf[0];
18185 uint32_t *a = nullptr;
18186 if (chunk_.sid_buf) {
18187 if (rid >= 0x100000) {
18188 return GRN_SUCCESS;
18189 }
18190 uint32_t sid = chunk_.sid_buf[0] + 1;
18191 if (sid >= 0x800) {
18192 return GRN_SUCCESS;
18193 }
18194 a = array_get(ctx_, ii_, chunk_.tid);
18195 if (!a) {
18196 auto ctx = ctx_;
18197 GRN_DEFINE_NAME(ii_);
18198 grn_obj token;
18199 GRN_TEXT_INIT(&token, 0);
18200 grn_ii_get_term(ctx, ii_, chunk_.tid, &token);
18201 MERR("[ii][builder][chunk][pack] failed to allocate an array: "
18202 "<%.*s>: "
18203 "<%.*s>(%u): "
18204 "(%u:%u)",
18205 name_size,
18206 name,
18207 static_cast<int>(GRN_TEXT_LEN(&token)),
18208 GRN_TEXT_VALUE(&token),
18209 chunk_.tid,
18210 rid,
18211 sid);
18212 GRN_OBJ_FIN(ctx, &token);
18213 return ctx->rc;
18214 }
18215 a[0] = POS_EMBED_RID_SID(rid, sid);
18216 } else {
18217 a = array_get(ctx_, ii_, chunk_.tid);
18218 if (!a) {
18219 auto ctx = ctx_;
18220 GRN_DEFINE_NAME(ii_);
18221 grn_obj token;
18222 GRN_TEXT_INIT(&token, 0);
18223 grn_ii_get_term(ctx, ii_, chunk_.tid, &token);
18224 MERR("[ii][builder][chunk][pack] failed to allocate an array: "
18225 "<%.*s>: "
18226 "<%.*s>(%u): "
18227 "(%u)",
18228 name_size,
18229 name,
18230 static_cast<int>(GRN_TEXT_LEN(&token)),
18231 GRN_TEXT_VALUE(&token),
18232 chunk_.tid,
18233 rid);
18234 GRN_OBJ_FIN(ctx, &token);
18235 return ctx->rc;
18236 }
18237 a[0] = POS_EMBED_RID(rid);
18238 }
18239 uint32_t pos = 0;
18240 if (chunk_.pos_buf) {
18241 pos = chunk_.pos_buf[0];
18242 }
18243 a[1] = pos;
18244 array_unref(ctx_, ii_, chunk_.tid);
18245 *packed = true;
18246
18247 grn_ii_builder_chunk_clear(ctx_, &chunk_);
18248 return GRN_SUCCESS;
18249 }
18250
18251 // Returns a new cinfo.
18252 grn_rc
18253 get_cinfo(chunk_info **cinfo)
18254 {
18255 if (n_cinfos_ == cinfos_size_) {
18256 uint32_t size = (cinfos_size_ > 0) ? (cinfos_size_ * 2) : 1;
18257 size_t n_bytes = size * sizeof(chunk_info);
18258 auto ctx = ctx_;
18259 auto cinfos =
18260 reinterpret_cast<chunk_info *>(GRN_REALLOC(cinfos_, n_bytes));
18261 if (!cinfos) {
18262 ERR(GRN_NO_MEMORY_AVAILABLE,
18263 "failed to allocate memory for cinfos: n_bytes = %" GRN_FMT_SIZE,
18264 n_bytes);
18265 return ctx->rc;
18266 }
18267 cinfos_ = cinfos;
18268 cinfos_size_ = size;
18269 }
18270 *cinfo = &(cinfos_[n_cinfos_++]);
18271 return GRN_SUCCESS;
18272 }
18273
18274 // Flushes a chunk.
18275 grn_rc
18276 flush_chunk()
18277 {
18278 auto rc = grn_ii_builder_chunk_encode(ctx_, &chunk_, NULL, 0);
18279 if (rc != GRN_SUCCESS) {
18280 return rc;
18281 }
18282 uint8_t *in = chunk_.enc_buf;
18283 uint32_t in_size = chunk_.enc_offset;
18284
18285 uint32_t chunk_id;
18286 rc = chunk_new(ctx_, ii_, &chunk_id, chunk_.enc_offset);
18287 if (rc != GRN_SUCCESS) {
18288 return rc;
18289 }
18290
18291 /* Copy to the first segment. */
18292 uint32_t seg_id = chunk_id >> GRN_II_N_CHUNK_VARIATION;
18293 uint32_t seg_offset = (chunk_id & ((1 << GRN_II_N_CHUNK_VARIATION) - 1))
18294 << GRN_II_W_LEAST_CHUNK;
18295 void *seg = grn_io_seg_ref(ctx_, ii_->chunk, seg_id);
18296 if (!seg) {
18297 if (ctx_->rc == GRN_SUCCESS) {
18298 auto ctx = ctx_;
18299 ERR(GRN_UNKNOWN_ERROR,
18300 "failed access chunk segment: chunk_id = %u, seg_id = %u",
18301 chunk_id,
18302 seg_id);
18303 }
18304 return ctx_->rc;
18305 }
18306 uint32_t seg_rest = S_CHUNK - seg_offset;
18307 if (in_size <= seg_rest) {
18308 grn_memcpy(static_cast<uint8_t *>(seg) + seg_offset, in, in_size);
18309 in_size = 0;
18310 } else {
18311 grn_memcpy(static_cast<uint8_t *>(seg) + seg_offset, in, seg_rest);
18312 in += seg_rest;
18313 in_size -= seg_rest;
18314 }
18315 grn_io_seg_unref(ctx_, ii_->chunk, seg_id);
18316
18317 /* Copy to the next segments. */
18318 while (in_size) {
18319 seg_id++;
18320 seg = grn_io_seg_ref(ctx_, ii_->chunk, seg_id);
18321 if (!seg) {
18322 if (ctx_->rc == GRN_SUCCESS) {
18323 auto ctx = ctx_;
18324 ERR(GRN_UNKNOWN_ERROR,
18325 "failed access chunk segment: chunk_id = %u, seg_id = %u",
18326 chunk_id,
18327 seg_id);
18328 }
18329 return ctx_->rc;
18330 }
18331 if (in_size <= S_CHUNK) {
18332 grn_memcpy(seg, in, in_size);
18333 in_size = 0;
18334 } else {
18335 grn_memcpy(seg, in, S_CHUNK);
18336 in += S_CHUNK;
18337 in_size -= S_CHUNK;
18338 }
18339 grn_io_seg_unref(ctx_, ii_->chunk, seg_id);
18340 }
18341
18342 /* Append a cinfo. */
18343 chunk_info *cinfo = nullptr;
18344 rc = get_cinfo(&cinfo);
18345 if (rc != GRN_SUCCESS) {
18346 return rc;
18347 }
18348 cinfo->segno = chunk_id;
18349 cinfo->size = chunk_.enc_offset;
18350 cinfo->dgap = chunk_.rid_gap;
18351
18352 buf_.ii->header.common->total_chunk_size += chunk_.enc_offset;
18353 grn_ii_builder_chunk_clear(ctx_, &chunk_);
18354 return GRN_SUCCESS;
18355 }
18356
18357 // Reads values from a block to a chunk.
18358 grn_rc
18359 read_to_chunk(uint32_t block_id)
18360 {
18361 const uint32_t ii_flags = ii_->header.common->flags;
18362
18363 uint32_t rid = GRN_ID_NIL;
18364 uint32_t last_sid = 0;
18365 for (;;) {
18366 uint64_t value;
18367 auto rc = read_from_block(block_id, &value);
18368 if (rc != GRN_SUCCESS) {
18369 return rc;
18370 }
18371 if (!value) {
18372 break;
18373 }
18374 if (chunk_.offset == chunk_.size) {
18375 rc = grn_ii_builder_chunk_extend_bufs(ctx_, &chunk_, ii_flags);
18376 if (rc != GRN_SUCCESS) {
18377 return rc;
18378 }
18379 }
18380
18381 /* Read record ID. */
18382 uint32_t gap =
18383 static_cast<uint32_t>(value >> sid_bits_); /* In-block gap */
18384 uint32_t freq;
18385 if (gap) {
18386 if (chunk_.n >= options_.chunk_threshold) {
18387 const double threshold_scale = 1 + log(df_ + 1);
18388 const double threshold = options_.chunk_threshold * threshold_scale;
18389 if (chunk_.n >= threshold) {
18390 if (grn_logger_pass(ctx_, GRN_LOG_DEBUG)) {
18391 auto ctx = ctx_;
18392 GRN_DEFINE_NAME(ii_);
18393 grn_obj token;
18394 GRN_TEXT_INIT(&token, 0);
18395 grn_ii_get_term(ctx_, ii_, chunk_.tid, &token);
18396 GRN_LOG(ctx_,
18397 GRN_LOG_DEBUG,
18398 "[ii][builder][read-to-chunk] flush"
18399 "<%.*s>: "
18400 "<%.*s>(%u): "
18401 "n=<%u> "
18402 "df=<%u> "
18403 "threshold=<%.1f>",
18404 name_size,
18405 name,
18406 static_cast<int>(GRN_TEXT_LEN(&token)),
18407 GRN_TEXT_VALUE(&token),
18408 chunk_.tid,
18409 chunk_.n,
18410 df_,
18411 threshold);
18412 GRN_OBJ_FIN(ctx, &token);
18413 }
18414 rc = flush_chunk();
18415 if (rc != GRN_SUCCESS) {
18416 return rc;
18417 }
18418 }
18419 }
18420 last_sid = 0;
18421 }
18422 rid += gap;
18423 gap = rid - chunk_.rid; /* Global gap */
18424 chunk_.rid_buf[chunk_.offset] = (chunk_.offset > 0) ? gap : rid;
18425 chunk_.n++;
18426 chunk_.rid = rid;
18427 chunk_.rid_gap += gap;
18428 df_++;
18429
18430 /* Read section ID. */
18431 if (ii_flags & GRN_OBJ_WITH_SECTION) {
18432 auto sid = static_cast<uint32_t>((value & sid_mask_) + 1);
18433 chunk_.sid_buf[chunk_.offset] = sid - last_sid - 1;
18434 chunk_.n++;
18435 last_sid = sid;
18436 }
18437
18438 /* Read weight. */
18439 if (ii_flags & GRN_OBJ_WITH_WEIGHT) {
18440 uint32_t weight;
18441 rc = read_from_block(block_id, &value);
18442 if (rc != GRN_SUCCESS) {
18443 return rc;
18444 }
18445 weight = static_cast<uint32_t>(value);
18446 chunk_.weight_buf[chunk_.offset] = weight;
18447 chunk_.n++;
18448 }
18449
18450 /* Read positions or a frequency. */
18451 if (ii_flags & GRN_OBJ_WITH_POSITION) {
18452 uint32_t pos = -1;
18453 freq = 0;
18454 for (;;) {
18455 rc = read_from_block(block_id, &value);
18456 if (rc != GRN_SUCCESS) {
18457 return rc;
18458 }
18459 if (!value) {
18460 break;
18461 }
18462 if (chunk_.pos_offset == chunk_.pos_size) {
18463 rc = grn_ii_builder_chunk_extend_pos_buf(ctx_, &chunk_);
18464 if (rc != GRN_SUCCESS) {
18465 return rc;
18466 }
18467 }
18468 if (pos == static_cast<uint32_t>(-1)) {
18469 chunk_.pos_buf[chunk_.pos_offset] =
18470 static_cast<uint32_t>(value - 1);
18471 chunk_.pos_sum += value - 1;
18472 } else {
18473 chunk_.pos_buf[chunk_.pos_offset] = static_cast<uint32_t>(value);
18474 chunk_.pos_sum += value;
18475 }
18476 chunk_.n++;
18477 pos += static_cast<uint32_t>(value);
18478 chunk_.pos_offset++;
18479 freq++;
18480 }
18481 } else {
18482 rc = read_from_block(block_id, &value);
18483 if (rc != GRN_SUCCESS) {
18484 return rc;
18485 }
18486 freq = static_cast<uint32_t>(value);
18487 }
18488 chunk_.freq_buf[chunk_.offset] = freq - 1;
18489 chunk_.n++;
18490 chunk_.offset++;
18491 }
18492
18493 uint64_t value;
18494 auto rc = read_from_block(block_id, &value);
18495 if (rc == GRN_SUCCESS) {
18496 blocks_[block_id].tid = static_cast<grn_id>(value);
18497 } else if (rc == GRN_END_OF_DATA) {
18498 blocks_[block_id].tid = GRN_ID_NIL;
18499 } else {
18500 return rc;
18501 }
18502 return GRN_SUCCESS;
18503 }
18504
18505 // Registers chunks.
18506 grn_rc
18507 register_chunks()
18508 {
18509 auto rc = grn_ii_builder_chunk_encode(ctx_, &chunk_, cinfos_, n_cinfos_);
18510 if (rc != GRN_SUCCESS) {
18511 return rc;
18512 }
18513
18514 if (!grn_ii_builder_buffer_is_assigned(ctx_, &buf_)) {
18515 rc = grn_ii_builder_buffer_assign(ctx_, &buf_, chunk_.enc_offset);
18516 if (rc != GRN_SUCCESS) {
18517 return rc;
18518 }
18519 }
18520 uint32_t buf_tid = buf_.buf->header.nterms;
18521 if (buf_tid >= options_.buffer_max_n_terms ||
18522 buf_.chunk_size - buf_.chunk_offset < chunk_.enc_offset) {
18523 rc = grn_ii_builder_buffer_flush(ctx_, &buf_);
18524 if (rc != GRN_SUCCESS) {
18525 return rc;
18526 }
18527 rc = grn_ii_builder_buffer_assign(ctx_, &buf_, chunk_.enc_offset);
18528 if (rc != GRN_SUCCESS) {
18529 return rc;
18530 }
18531 buf_tid = 0;
18532 }
18533 buffer_term *buf_term = &(buf_.buf->terms[buf_tid]);
18534 buf_term->tid = chunk_.tid;
18535 if (n_cinfos_ > 0) {
18536 buf_term->tid |= CHUNK_SPLIT;
18537 }
18538 buf_term->size_in_buffer = 0;
18539 buf_term->pos_in_buffer = 0;
18540 buf_term->size_in_chunk = chunk_.enc_offset;
18541 buf_term->pos_in_chunk = buf_.chunk_offset;
18542
18543 if (grn_logger_pass(ctx_, GRN_LOG_DEBUG)) {
18544 auto ctx = ctx_;
18545 GRN_DEFINE_NAME(ii_);
18546 grn_obj token;
18547 GRN_TEXT_INIT(&token, 0);
18548 grn_ii_get_term(ctx, ii_, chunk_.tid, &token);
18549 GRN_LOG(ctx,
18550 GRN_LOG_DEBUG,
18551 "[ii][builder][register][chunks] "
18552 "<%.*s>: "
18553 "<%.*s>(%u): "
18554 "n_chunks=<%u> "
18555 "chunk=<%u>/<%u>(%u)/(%u) "
18556 "encoded_chunk_size=<%" GRN_FMT_SIZE ">",
18557 name_size,
18558 name,
18559 static_cast<int>(GRN_TEXT_LEN(&token)),
18560 GRN_TEXT_VALUE(&token),
18561 chunk_.tid,
18562 n_cinfos_,
18563 buf_.chunk_offset,
18564 buf_.chunk_size,
18565 buf_.chunk_size - buf_.chunk_offset,
18566 buf_.ii->chunk->header->segment_size,
18567 chunk_.enc_offset);
18568 GRN_OBJ_FIN(ctx, &token);
18569 }
18570 grn_memcpy(buf_.chunk + buf_.chunk_offset,
18571 chunk_.enc_buf,
18572 chunk_.enc_offset);
18573 buf_.chunk_offset += chunk_.enc_offset;
18574
18575 uint32_t *a = array_get(ctx_, ii_, chunk_.tid);
18576 if (!a) {
18577 auto ctx = ctx_;
18578 GRN_DEFINE_NAME(ii_);
18579 grn_obj token;
18580 GRN_TEXT_INIT(&token, 0);
18581 grn_ii_get_term(ctx_, ii_, chunk_.tid, &token);
18582 MERR("[ii][builder][register][chunks] "
18583 "failed to allocate an array in segment: "
18584 "<%.*s>: "
18585 "<%.*s>(%u): "
18586 "max_n_segments=<%u>",
18587 name_size,
18588 name,
18589 static_cast<int>(GRN_TEXT_LEN(&token)),
18590 GRN_TEXT_VALUE(&token),
18591 chunk_.tid,
18592 ii_->seg->header->max_segment);
18593 GRN_OBJ_FIN(ctx, &token);
18594 return ctx->rc;
18595 }
18596 a[0] = grn_ii_pos_pack(ii_,
18597 buf_.buf_id,
18598 POS_LOFFSET_HEADER + POS_LOFFSET_TERM * buf_tid);
18599 a[1] = df_;
18600 array_unref(ctx_, ii_, chunk_.tid);
18601
18602 buf_.buf->header.nterms++;
18603 n_cinfos_ = 0;
18604 grn_ii_builder_chunk_clear(ctx_, &chunk_);
18605 return GRN_SUCCESS;
18606 }
18607
18608 grn_rc
18609 commit()
18610 {
18611 if (progress_needed_) {
18612 progress_.value.index.phase = GRN_PROGRESS_INDEX_COMMIT;
18613 progress_.value.index.n_target_terms =
18614 grn_table_size(ctx_, ii_->lexicon);
18615 grn_ctx_call_progress_callback(ctx_, &progress_);
18616 }
18617
18618 for (uint32_t i = 0; i < n_blocks_; i++) {
18619 uint64_t value;
18620 auto rc = read_from_block(i, &value);
18621 if (rc != GRN_SUCCESS) {
18622 return rc;
18623 }
18624 blocks_[i].tid = static_cast<grn_id>(value);
18625 }
18626
18627 // See also the comment in BlockBuilder::flush().
18628 auto rc = table_each_by_key(ctx_, ii_->lexicon, [&](grn_id tid) {
18629 chunk_.tid = tid;
18630 chunk_.rid = GRN_ID_NIL;
18631 df_ = 0;
18632 for (uint32_t i = 0; i < n_blocks_; i++) {
18633 if (tid == blocks_[i].tid) {
18634 auto rc = read_to_chunk(i);
18635 if (rc != GRN_SUCCESS) {
18636 return rc;
18637 }
18638 }
18639 }
18640 if (chunk_.n == 0) {
18641 /* This term does not appear. */
18642 return GRN_SUCCESS;
18643 }
18644 if (n_cinfos_ == 0) {
18645 bool packed;
18646 auto rc = pack_chunk(&packed);
18647 if (rc != GRN_SUCCESS) {
18648 return rc;
18649 }
18650 if (packed) {
18651 return GRN_SUCCESS;
18652 }
18653 }
18654 auto rc = register_chunks();
18655 if (rc != GRN_SUCCESS) {
18656 return rc;
18657 }
18658 if (progress_needed_) {
18659 progress_.value.index.n_processed_terms++;
18660 grn_ctx_call_progress_callback(ctx_, &progress_);
18661 }
18662 return GRN_SUCCESS;
18663 });
18664 if (rc != GRN_SUCCESS) {
18665 return rc;
18666 }
18667 if (grn_ii_builder_buffer_is_assigned(ctx_, &buf_)) {
18668 rc = grn_ii_builder_buffer_flush(ctx_, &buf_);
18669 if (rc != GRN_SUCCESS) {
18670 return rc;
18671 }
18672 }
18673 return GRN_SUCCESS;
18674 }
18675
18676 grn_ctx *ctx_;
18677 bool progress_needed_; /* Whether progress callback is needed for
18678 performance */
18679 grn_progress progress_; /* Progress information */
18680
18681 grn_ii *ii_; /* Building inverted index */
18682 grn_ii_builder_options options_; /* Options */
18683
18684 grn_obj *src_table_; /* Source table */
18685 unsigned int n_records_; /* Number of records in source table */
18686 grn_obj srcs_; /* Source columns (to be freed) */
18687 grn_obj **src_token_columns_; /* Source token columns (to be freed) */
18688 uint8_t sid_bits_; /* Number of bits for section ID */
18689 uint64_t sid_mask_; /* Mask bits for section ID */
18690
18691 /* A temporary file to save blocks. */
18692 char path_[PATH_MAX]; /* File path */
18693 int fd_; /* File descriptor (to be closed) */
18694 uint8_t *file_buf_; /* File buffer for buffered output (to be freed) */
18695 uint32_t file_buf_offset_; /* File buffer write offset */
18696
18697 grn_ii_builder_block *blocks_; /* Blocks (to be freed) */
18698 uint32_t n_blocks_; /* Number of blocks */
18699 uint32_t blocks_size_; /* Buffer size of blocks */
18700
18701 grn_ii_builder_buffer buf_; /* Buffer (to be finalized) */
18702 grn_ii_builder_chunk chunk_; /* Chunk (to be finalized) */
18703
18704 uint32_t df_; /* Document frequency (number of sections) */
18705 chunk_info *cinfos_; /* Chunk headers (to be freed) */
18706 uint32_t n_cinfos_; /* Number of chunks */
18707 uint32_t cinfos_size_; /* Size of cinfos */
18708 };
18709 } // namespace grn::ii
18710
18711 extern "C" grn_rc
18712 grn_ii_build(grn_ctx *ctx, grn_ii *ii, const grn_ii_builder_options *options)
18713 {
18714 grn_rc rc = GRN_SUCCESS;
18715 {
18716 grn::ii::Builder builder(ctx, ii, options);
18717 rc = builder.append_source();
18718 if (rc == GRN_SUCCESS) {
18719 rc = builder.commit();
18720 }
18721 }
18722 if (rc != GRN_SUCCESS) {
18723 grn_obj_flush(ctx, reinterpret_cast<grn_obj *>(ii));
18724 }
18725 return rc;
18726 }
18727
18728 extern "C" grn_rc
18729 grn_ii_wal_recover(grn_ctx *ctx, grn_ii *ii)
18730 {
18731 if (GRN_CTX_GET_WAL_ROLE(ctx) != GRN_WAL_ROLE_PRIMARY) {
18732 return GRN_SUCCESS;
18733 }
18734
18735 if (!grn_wal_exist(ctx, (grn_obj *)ii)) {
18736 if (grn_io_is_locked(ii->seg)) {
18737 grn_io_clear_lock(ii->seg);
18738 grn_obj_touch(ctx, (grn_obj *)ii, NULL);
18739 grn_obj_flush(ctx, (grn_obj *)ii);
18740 }
18741 return GRN_SUCCESS;
18742 }
18743
18744 grn_obj_set_error(ctx,
18745 (grn_obj *)ii,
18746 GRN_FUNCTION_NOT_IMPLEMENTED,
18747 GRN_ID_NIL,
18748 "[ii][wal][recover]",
18749 "not implemented");
18750 return ctx->rc;
18751 }
18752
18753 extern "C" grn_rc
18754 grn_ii_warm(grn_ctx *ctx, grn_ii *ii)
18755 {
18756 grn_rc rc = grn_io_warm(ctx, ii->seg);
18757 if (rc == GRN_SUCCESS) {
18758 rc = grn_io_warm(ctx, ii->chunk);
18759 }
18760 return rc;
18761 }