robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 716835c2d51fa783d7

master
73.4 KiB2598 linesraw
1// Tree data structure for storing marks at (row, col) positions and updating
2// them to arbitrary text changes. Derivative work of kbtree in klib, whose
3// copyright notice is reproduced below. Also inspired by the design of the
4// marker tree data structure of the Atom editor, regarding efficient updates
5// to text changes.
6//
7// Marks are inserted using marktree_put. Text changes are processed using
8// marktree_splice. All read and delete operations use the iterator.
9// use marktree_itr_get to put an iterator at a given position or
10// marktree_lookup to lookup a mark by its id (iterator optional in this case).
11// Use marktree_itr_current and marktree_itr_next/prev to read marks in a loop.
12// marktree_del_itr deletes the current mark of the iterator and implicitly
13// moves the iterator to the next mark.
14
15// Copyright notice for kbtree (included in heavily modified form):
16//
17// Copyright 1997-1999, 2001, John-Mark Gurney.
18//           2008-2009, Attractive Chaos <attractor@live.co.uk>
19//
20// Redistribution and use in source and binary forms, with or without
21// modification, are permitted provided that the following conditions
22// are met:
23//
24// 1. Redistributions of source code must retain the above copyright
25//    notice, this list of conditions and the following disclaimer.
26// 2. Redistributions in binary form must reproduce the above copyright
27//    notice, this list of conditions and the following disclaimer in the
28//    documentation and/or other materials provided with the distribution.
29//
30// THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
31// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33// ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
34// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
36// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
39// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40// SUCH DAMAGE.
41//
42// Changes done by the neovim project follow the Apache v2 license available
43// at the repo root.
44
45#include <assert.h>
46#include <inttypes.h>
47#include <stdio.h>
48#include <stdlib.h>
49#include <string.h>
50#include <uv.h>
51
52#include "klib/kvec.h"
53#include "nvim/macros_defs.h"
54#include "nvim/map_defs.h"
55#include "nvim/marktree.h"
56#include "nvim/memory.h"
57#include "nvim/pos_defs.h"
58// only for debug functions
59#include "nvim/api/private/defs.h"
60#include "nvim/api/private/helpers.h"
61#include "nvim/garray.h"
62#include "nvim/garray_defs.h"
63
64#define T MT_BRANCH_FACTOR
65#define ILEN (sizeof(MTNode) + sizeof(struct mtnode_inner_s))
66
67#define ID_INCR (((uint64_t)1) << 2)
68
69#define rawkey(itr) ((itr)->x->key[(itr)->i])
70
71static bool pos_leq(MTPos a, MTPos b)
72{
73  return a.row < b.row || (a.row == b.row && a.col <= b.col);
74}
75
76static bool pos_less(MTPos a, MTPos b)
77{
78  return !pos_leq(b, a);
79}
80
81static void relative(MTPos base, MTPos *val)
82{
83  assert(pos_leq(base, *val));
84  if (val->row == base.row) {
85    val->row = 0;
86    val->col -= base.col;
87  } else {
88    val->row -= base.row;
89  }
90}
91
92static void unrelative(MTPos base, MTPos *val)
93{
94  if (val->row == 0) {
95    val->row = base.row;
96    val->col += base.col;
97  } else {
98    val->row += base.row;
99  }
100}
101
102static void compose(MTPos *base, MTPos val)
103{
104  if (val.row == 0) {
105    base->col += val.col;
106  } else {
107    base->row += val.row;
108    base->col = val.col;
109  }
110}
111
112typedef Map(uint64_t, MTDamagePair) MTDamageMap;
113
114#include "marktree.c.generated.h"
115
116#define mt_generic_cmp(a, b) (((b) < (a)) - ((a) < (b)))
117static int key_cmp(MTKey a, MTKey b)
118{
119  int cmp = mt_generic_cmp(a.pos.row, b.pos.row);
120  if (cmp != 0) {
121    return cmp;
122  }
123  cmp = mt_generic_cmp(a.pos.col, b.pos.col);
124  if (cmp != 0) {
125    return cmp;
126  }
127
128  // TODO(bfredl): MT_FLAG_REAL could go away if we fix marktree_getp_aux for real
129  const uint16_t cmp_mask = MT_FLAG_RIGHT_GRAVITY | MT_FLAG_END | MT_FLAG_REAL | MT_FLAG_LAST;
130  return mt_generic_cmp(a.flags & cmp_mask, b.flags & cmp_mask);
131}
132
133/// @return position of k if it exists in the node, otherwise the position
134/// it should be inserted, which ranges from 0 to x->n _inclusively_
135/// @param match (optional) set to TRUE if match (pos, gravity) was found
136static inline int marktree_getp_aux(const MTNode *x, MTKey k, bool *match)
137{
138  bool dummy_match;
139  bool *m = match ? match : &dummy_match;
140
141  int begin = 0;
142  int end = x->n;
143  if (x->n == 0) {
144    *m = false;
145    return -1;
146  }
147  while (begin < end) {
148    int mid = (begin + end) >> 1;
149    if (key_cmp(x->key[mid], k) < 0) {
150      begin = mid + 1;
151    } else {
152      end = mid;
153    }
154  }
155  if (begin == x->n) {
156    *m = false;
157    return x->n - 1;
158  }
159  if (!(*m = (key_cmp(k, x->key[begin]) == 0))) {
160    begin--;
161  }
162  return begin;
163}
164
165static inline void refkey(MarkTree *b, MTNode *x, int i)
166{
167  pmap_put(uint64_t)(b->id2node, mt_lookup_key(x->key[i]), x);
168}
169
170static MTNode *id2node(MarkTree *b, uint64_t id)
171{
172  return pmap_get(uint64_t)(b->id2node, id);
173}
174
175#define ptr s->i_ptr
176#define meta s->i_meta
177// put functions
178
179// x must be an internal node, which is not full
180// x->ptr[i] should be a full node, i e x->ptr[i]->n == 2*T-1
181static inline void split_node(MarkTree *b, MTNode *x, const int i, MTKey next)
182{
183  MTNode *y = x->ptr[i];
184  MTNode *z = marktree_alloc_node(b, y->level);
185  z->level = y->level;
186  z->n = T - 1;
187
188  // tricky: we might split a node in between inserting the start node and the end
189  // node of the same pair. Then we must not intersect this id yet (done later
190  // in marktree_intersect_pair).
191  uint64_t last_start = mt_end(next) ? mt_lookup_id(next.ns, next.id, false) : MARKTREE_END_FLAG;
192
193  // no alloc in the common case (less than 4 intersects)
194  kvi_copy(z->intersect, y->intersect);
195
196  if (!y->level) {
197    uint64_t pi = pseudo_index(y, 0);  // note: sloppy pseudo-index
198    for (int j = 0; j < T; j++) {
199      MTKey k = y->key[j];
200      uint64_t pi_end = pseudo_index_for_id(b, mt_lookup_id(k.ns, k.id, true), true);
201      if (mt_start(k) && pi_end > pi && mt_lookup_key(k) != last_start) {
202        intersect_node(b, z, mt_lookup_id(k.ns, k.id, false));
203      }
204    }
205
206    // note: y->key[T-1] is moved up and thus checked for both
207    for (int j = T - 1; j < (T * 2) - 1; j++) {
208      MTKey k = y->key[j];
209      uint64_t pi_start = pseudo_index_for_id(b, mt_lookup_id(k.ns, k.id, false), true);
210      if (mt_end(k) && pi_start > 0 && pi_start < pi) {
211        intersect_node(b, y, mt_lookup_id(k.ns, k.id, false));
212      }
213    }
214  }
215
216  memcpy(z->key, &y->key[T], sizeof(MTKey) * (T - 1));
217  for (int j = 0; j < T - 1; j++) {
218    refkey(b, z, j);
219  }
220  if (y->level) {
221    memcpy(z->ptr, &y->ptr[T], sizeof(MTNode *) * T);
222    memcpy(z->meta, &y->meta[T], sizeof(z->meta[0]) * T);
223    for (int j = 0; j < T; j++) {
224      z->ptr[j]->parent = z;
225      z->ptr[j]->p_idx = (int16_t)j;
226    }
227  }
228  y->n = T - 1;
229  memmove(&x->ptr[i + 2], &x->ptr[i + 1], sizeof(MTNode *) * (size_t)(x->n - i));
230  memmove(&x->meta[i + 2], &x->meta[i + 1], sizeof(x->meta[0]) * (size_t)(x->n - i));
231  x->ptr[i + 1] = z;
232  meta_describe_node(x->meta[i + 1], z);
233  z->parent = x;  // == y->parent
234  for (int j = i + 1; j < x->n + 2; j++) {
235    x->ptr[j]->p_idx = (int16_t)j;
236  }
237  memmove(&x->key[i + 1], &x->key[i], sizeof(MTKey) * (size_t)(x->n - i));
238
239  // move key to internal layer:
240  x->key[i] = y->key[T - 1];
241  refkey(b, x, i);
242  x->n++;
243
244  uint32_t meta_inc[kMTMetaCount];
245  meta_describe_key(meta_inc, x->key[i]);
246  for (int m = 0; m < kMTMetaCount; m++) {
247    // y used contain all of z and x->key[i], discount those
248    x->meta[i][m] -= (x->meta[i + 1][m] + meta_inc[m]);
249  }
250
251  for (int j = 0; j < T - 1; j++) {
252    relative(x->key[i].pos, &z->key[j].pos);
253  }
254  if (i > 0) {
255    unrelative(x->key[i - 1].pos, &x->key[i].pos);
256  }
257
258  if (y->level) {
259    bubble_up(y);
260    bubble_up(z);
261  } else {
262    // code above goose here
263  }
264}
265
266// x must not be a full node (even if there might be internal space)
267static inline void marktree_putp_aux(MarkTree *b, MTNode *x, MTKey k, uint32_t *meta_inc)
268{
269  // TODO(bfredl): ugh, make sure this is the _last_ valid (pos, gravity) position,
270  // to minimize movement
271  int i = marktree_getp_aux(x, k, NULL) + 1;
272  if (x->level == 0) {
273    if (i != x->n) {
274      memmove(&x->key[i + 1], &x->key[i],
275              (size_t)(x->n - i) * sizeof(MTKey));
276    }
277    x->key[i] = k;
278    refkey(b, x, i);
279    x->n++;
280  } else {
281    if (x->ptr[i]->n == 2 * T - 1) {
282      split_node(b, x, i, k);
283      if (key_cmp(k, x->key[i]) > 0) {
284        i++;
285      }
286    }
287    if (i > 0) {
288      relative(x->key[i - 1].pos, &k.pos);
289    }
290    marktree_putp_aux(b, x->ptr[i], k, meta_inc);
291    for (int m = 0; m < kMTMetaCount; m++) {
292      x->meta[i][m] += meta_inc[m];
293    }
294  }
295}
296
297void marktree_put(MarkTree *b, MTKey key, int end_row, int end_col, bool end_right)
298{
299  assert(!(key.flags & ~(MT_FLAG_EXTERNAL_MASK | MT_FLAG_RIGHT_GRAVITY)));
300  if (end_row >= 0) {
301    key.flags |= MT_FLAG_PAIRED;
302  }
303
304  marktree_put_key(b, key);
305
306  if (end_row >= 0) {
307    MTKey end_key = key;
308    end_key.flags = (uint16_t)((uint16_t)(key.flags & ~MT_FLAG_RIGHT_GRAVITY)
309                               |(uint16_t)MT_FLAG_END
310                               |(uint16_t)(end_right ? MT_FLAG_RIGHT_GRAVITY : 0));
311    end_key.pos = (MTPos){ end_row, end_col };
312    marktree_put_key(b, end_key);
313    MarkTreeIter itr[1] = { 0 };
314    MarkTreeIter end_itr[1] = { 0 };
315    marktree_lookup(b, mt_lookup_key(key), itr);
316    marktree_lookup(b, mt_lookup_key(end_key), end_itr);
317
318    marktree_intersect_pair(b, mt_lookup_key(key), itr, end_itr, false);
319  }
320}
321
322// this is currently not used very often, but if it was it should use binary search
323static bool intersection_has(Intersection *x, uint64_t id)
324{
325  for (size_t i = 0; i < kv_size(*x); i++) {
326    if (kv_A(*x, i) == id) {
327      return true;
328    } else if (kv_A(*x, i) >= id) {
329      return false;
330    }
331  }
332  return false;
333}
334
335/// Finds the one position `id` can occupy in the ascending "intersect" array of `x`.
336///
337/// @return Index of `id`, or the index it would be inserted at if absent.
338static size_t intersect_item_pos(MTNode *x, uint64_t id)
339{
340  size_t lo = 0;
341  size_t hi = kv_size(x->intersect);
342  while (lo < hi) {
343    size_t mid = lo + (hi - lo) / 2;
344    if (kv_A(x->intersect, mid) < id) {
345      lo = mid + 1;
346    } else {
347      hi = mid;
348    }
349  }
350  return lo;
351}
352
353static void intersect_node(MarkTree *b, MTNode *x, uint64_t id)
354{
355  assert(!(id & MARKTREE_END_FLAG));
356  // Common case: ids arrive in ascending order, so the new key belongs at the end.
357  if (kv_size(x->intersect) == 0 || kv_A(x->intersect, kv_size(x->intersect) - 1) < id) {
358    kvi_push(x->intersect, id);
359    return;
360  }
361  size_t i = intersect_item_pos(x, id);
362  kvi_pushp(x->intersect);
363  memmove(&kv_A(x->intersect, i + 1), &kv_A(x->intersect, i),
364          (kv_size(x->intersect) - i - 1) * sizeof(kv_A(x->intersect, 0)));
365  kv_A(x->intersect, i) = id;
366}
367
368static void unintersect_node(MarkTree *b, MTNode *x, uint64_t id, bool strict)
369{
370  assert(!(id & MARKTREE_END_FLAG));
371  size_t i = intersect_item_pos(x, id);
372  bool seen = i < kv_size(x->intersect) && kv_A(x->intersect, i) == id;
373  if (strict) {
374#ifndef RELDEBUG
375    // TODO(bfredl): This assert has been seen to fail for end users
376    // using RelWithDebInfo builds. While indicating an invalid state for
377    // the marktree, this error doesn't need to be fatal. The assert still
378    // needs to present in Debug builds to be able to detect regressions in tests.
379    assert(seen);
380#endif
381  }
382
383  if (seen) {
384    if (i < kv_size(x->intersect) - 1) {
385      memmove(&kv_A(x->intersect, i), &kv_A(x->intersect, i + 1), (kv_size(x->intersect) - i - 1) *
386              sizeof(kv_A(x->intersect, i)));
387    }
388    kv_size(x->intersect)--;
389  }
390}
391
392/// @param itr mutated
393/// @param end_itr not mutated
394void marktree_intersect_pair(MarkTree *b, uint64_t id, MarkTreeIter *itr, MarkTreeIter *end_itr,
395                             bool delete)
396{
397  int lvl = 0, maxlvl = MIN(itr->lvl, end_itr->lvl);
398#define iat(itr, l, q) ((l == itr->lvl) ? itr->i + q : itr->s[l].i)
399  for (; lvl < maxlvl; lvl++) {
400    if (itr->s[lvl].i > end_itr->s[lvl].i) {
401      return;  // empty range
402    } else if (itr->s[lvl].i < end_itr->s[lvl].i) {
403      break;  // work to do
404    }
405  }
406  if (lvl == maxlvl && iat(itr, lvl, 1) > iat(end_itr, lvl, 0)) {
407    return;  // empty range
408  }
409
410  while (itr->x) {
411    bool skip = false;
412    if (itr->x == end_itr->x) {
413      if (itr->x->level == 0 || itr->i >= end_itr->i) {
414        break;
415      } else {
416        skip = true;
417      }
418    } else if (itr->lvl > lvl) {
419      skip = true;
420    } else {
421      if (iat(itr, lvl, 1) < iat(end_itr, lvl, 1)) {
422        skip = true;
423      } else {
424        lvl++;
425      }
426    }
427
428    if (skip) {
429      if (itr->x->level) {
430        MTNode *x = itr->x->ptr[itr->i + 1];
431        if (delete) {
432          unintersect_node(b, x, id, true);
433        } else {
434          intersect_node(b, x, id);
435        }
436      }
437    }
438    marktree_itr_next_skip(b, itr, skip, true, NULL, NULL);
439  }
440#undef iat
441}
442
443static MTNode *marktree_alloc_node(MarkTree *b, bool internal)
444{
445  MTNode *x = xcalloc(1, internal ? ILEN : sizeof(MTNode));
446  kvi_init(x->intersect);
447  b->n_nodes++;
448  return x;
449}
450
451// really meta_inc[kMTMetaCount]
452static void meta_describe_key_inc(uint32_t *meta_inc, MTKey *k)
453{
454  if (!mt_end(*k) && !mt_invalid(*k)) {
455    meta_inc[kMTMetaInline] += (k->flags & MT_FLAG_DECOR_VIRT_TEXT_INLINE) ? 1 : 0;
456    meta_inc[kMTMetaLines] += (k->flags & MT_FLAG_DECOR_VIRT_LINES) ? 1 : 0;
457    meta_inc[kMTMetaSignHL] += (k->flags & MT_FLAG_DECOR_SIGNHL) ? 1 : 0;
458    meta_inc[kMTMetaSignText] += (k->flags & MT_FLAG_DECOR_SIGNTEXT) ? 1 : 0;
459    meta_inc[kMTMetaConcealLines] += (k->flags & MT_FLAG_DECOR_CONCEAL_LINES) ? 1 : 0;
460  }
461}
462
463static void meta_describe_key(uint32_t *meta_inc, MTKey k)
464{
465  memset(meta_inc, 0, kMTMetaCount * sizeof(*meta_inc));
466  meta_describe_key_inc(meta_inc, &k);
467}
468
469// if x is internal, assumes x->meta[..] of children are correct
470static void meta_describe_node(uint32_t *meta_node, MTNode *x)
471{
472  memset(meta_node, 0, kMTMetaCount * sizeof(meta_node[0]));
473  for (int i = 0; i < x->n; i++) {
474    meta_describe_key_inc(meta_node, &x->key[i]);
475  }
476  if (x->level) {
477    for (int i = 0; i < x->n + 1; i++) {
478      for (int m = 0; m < kMTMetaCount; m++) {
479        meta_node[m] += x->meta[i][m];
480      }
481    }
482  }
483}
484
485static bool meta_has(const uint32_t *meta_count, MetaFilter meta_filter)
486{
487  uint32_t count = 0;
488  for (int m = 0; m < kMTMetaCount; m++) {
489    count += meta_count[m] & meta_filter[m];
490  }
491  return count > 0;
492}
493
494void marktree_put_key(MarkTree *b, MTKey k)
495{
496  k.flags |= MT_FLAG_REAL;  // let's be real.
497  if (!b->root) {
498    b->root = marktree_alloc_node(b, true);
499  }
500  MTNode *r = b->root;
501  if (r->n == 2 * T - 1) {
502    MTNode *s = marktree_alloc_node(b, true);
503    b->root = s; s->level = r->level + 1; s->n = 0;
504    s->ptr[0] = r;
505    for (int m = 0; m < kMTMetaCount; m++) {
506      s->meta[0][m] = b->meta_root[m];
507    }
508    r->parent = s;
509    r->p_idx = 0;
510    split_node(b, s, 0, k);
511    r = s;
512  }
513
514  uint32_t meta_inc[kMTMetaCount];
515  meta_describe_key(meta_inc, k);
516  marktree_putp_aux(b, r, k, meta_inc);
517  for (int m = 0; m < kMTMetaCount; m++) {
518    b->meta_root[m] += meta_inc[m];
519  }
520  b->n_keys++;
521}
522
523/// INITIATING DELETION PROTOCOL:
524///
525/// 1. Construct a valid iterator to the node to delete (argument)
526/// 2. If an "internal" key. Iterate one step to the left or right,
527///     which gives an internal key "auxiliary key".
528/// 3. Now delete this internal key (intended or auxiliary).
529///    The leaf node X might become undersized.
530/// 4. If step two was done: now replace the key that _should_ be
531///    deleted with the auxiliary key. Adjust relative
532/// 5. Now "repair" the tree as needed. We always start at a leaf node X.
533///     - if the node is big enough, terminate
534///     - if we can steal from the left, steal
535///     - if we can steal from the right, steal
536///     - otherwise merge this node with a neighbour. This might make our
537///       parent undersized. So repeat 5 for the parent.
538/// 6. If 4 went all the way to the root node. The root node
539///    might have ended up with size 0. Delete it then.
540///
541/// The iterator remains valid, and now points at the key _after_ the deleted
542/// one.
543///
544/// @param rev should be true if we plan to iterate _backwards_ and delete
545///            stuff before this key. Most of the time this is false (the
546///            recommended strategy is to always iterate forward)
547uint64_t marktree_del_itr(MarkTree *b, MarkTreeIter *itr, bool rev)
548{
549  int adjustment = 0;
550
551  MTNode *cur = itr->x;
552  int curi = itr->i;
553  uint64_t id = mt_lookup_key(cur->key[curi]);
554
555  MTKey raw = rawkey(itr);
556  uint64_t other = 0;
557  if (mt_paired(raw) && !(raw.flags & MT_FLAG_ORPHANED)) {
558    other = mt_lookup_key_side(raw, !mt_end(raw));
559
560    MarkTreeIter other_itr[1];
561    marktree_lookup(b, other, other_itr);
562    rawkey(other_itr).flags |= MT_FLAG_ORPHANED;
563    // Remove intersect markers. NB: must match exactly!
564    if (mt_start(raw)) {
565      MarkTreeIter this_itr[1] = { *itr };  // mutated copy
566      marktree_intersect_pair(b, id, this_itr, other_itr, true);
567    } else {
568      marktree_intersect_pair(b, other, other_itr, itr, true);
569    }
570  }
571
572  // 2.
573  if (itr->x->level) {
574    if (rev) {
575      abort();
576    } else {
577      // steal previous node
578      marktree_itr_prev(b, itr);
579      adjustment = -1;
580    }
581  }
582
583  // 3.
584  MTNode *x = itr->x;
585  assert(x->level == 0);
586  MTKey intkey = x->key[itr->i];
587
588  uint32_t meta_inc[kMTMetaCount];
589  meta_describe_key(meta_inc, intkey);
590  if (x->n > itr->i + 1) {
591    memmove(&x->key[itr->i], &x->key[itr->i + 1],
592            sizeof(MTKey) * (size_t)(x->n - itr->i - 1));
593  }
594  x->n--;
595
596  b->n_keys--;
597  pmap_del(uint64_t)(b->id2node, id, NULL);
598
599  // 4.
600  // if (adjustment == 1) {
601  //   abort();
602  // }
603  if (adjustment == -1) {
604    int ilvl = itr->lvl - 1;
605    MTNode *lnode = x;
606    uint64_t start_id = 0;
607    bool did_bubble = false;
608    if (mt_end(intkey)) {
609      start_id = mt_lookup_key_side(intkey, false);
610    }
611    do {
612      MTNode *p = lnode->parent;
613      if (ilvl < 0) {
614        abort();
615      }
616      int i = itr->s[ilvl].i;
617      assert(p->ptr[i] == lnode);
618      if (i > 0) {
619        unrelative(p->key[i - 1].pos, &intkey.pos);
620      }
621
622      if (p != cur && start_id) {
623        if (intersection_has(&p->ptr[0]->intersect, start_id)) {
624          // if not the first time, we need to undo the addition in the
625          // previous step (`intersect_node` just below)
626          int last = (lnode != x) ? 1 : 0;
627          for (int k = 0; k < p->n + last; k++) {  // one less as p->ptr[n] is the last
628            unintersect_node(b, p->ptr[k], start_id, true);
629          }
630          intersect_node(b, p, start_id);
631          did_bubble = true;
632        }
633      }
634
635      for (int m = 0; m < kMTMetaCount; m++) {
636        p->meta[lnode->p_idx][m] -= meta_inc[m];
637      }
638
639      lnode = p;
640      ilvl--;
641    } while (lnode != cur);
642
643    MTKey deleted = cur->key[curi];
644    meta_describe_key(meta_inc, deleted);
645    cur->key[curi] = intkey;
646    refkey(b, cur, curi);
647    // if `did_bubble` then we already added `start_id` to some parent
648    if (mt_end(cur->key[curi]) && !did_bubble) {
649      uint64_t pi = pseudo_index(x, 0);  // note: sloppy pseudo-index
650      uint64_t pi_start = pseudo_index_for_id(b, start_id, true);
651      if (pi_start > 0 && pi_start < pi) {
652        intersect_node(b, x, start_id);
653      }
654    }
655
656    relative(intkey.pos, &deleted.pos);
657    MTNode *y = cur->ptr[curi + 1];
658    if (deleted.pos.row || deleted.pos.col) {
659      while (y) {
660        for (int k = 0; k < y->n; k++) {
661          unrelative(deleted.pos, &y->key[k].pos);
662        }
663        y = y->level ? y->ptr[0] : NULL;
664      }
665    }
666    itr->i--;
667  }
668
669  MTNode *lnode = cur;
670  while (lnode->parent) {
671    uint32_t *meta_p = lnode->parent->meta[lnode->p_idx];
672    for (int m = 0; m < kMTMetaCount; m++) {
673      meta_p[m] -= meta_inc[m];
674    }
675
676    lnode = lnode->parent;
677  }
678  for (int m = 0; m < kMTMetaCount; m++) {
679    assert(b->meta_root[m] >= meta_inc[m]);
680    b->meta_root[m] -= meta_inc[m];
681  }
682
683  // 5.
684  bool itr_dirty = false;
685  int rlvl = itr->lvl - 1;
686  int *lasti = &itr->i;
687  MTPos ppos = itr->pos;
688  while (x != b->root) {
689    assert(rlvl >= 0);
690    MTNode *p = x->parent;
691    if (x->n >= T - 1) {
692      // we are done, if this node is fine the rest of the tree will be
693      break;
694    }
695    int pi = itr->s[rlvl].i;
696    assert(p->ptr[pi] == x);
697    if (pi > 0) {
698      ppos.row -= p->key[pi - 1].pos.row;
699      ppos.col = itr->s[rlvl].oldcol;
700    }
701    // ppos is now the pos of p
702
703    if (pi > 0 && p->ptr[pi - 1]->n > T - 1) {
704      *lasti += 1;
705      itr_dirty = true;
706      // steal one key from the left neighbour
707      pivot_right(b, ppos, p, pi - 1);
708      break;
709    } else if (pi < p->n && p->ptr[pi + 1]->n > T - 1) {
710      // steal one key from right neighbour
711      pivot_left(b, ppos, p, pi);
712      break;
713    } else if (pi > 0) {
714      assert(p->ptr[pi - 1]->n == T - 1);
715      // merge with left neighbour
716      *lasti += T;
717      x = merge_node(b, p, pi - 1);
718      if (lasti == &itr->i) {
719        // TRICKY: we merged the node the iterator was on
720        itr->x = x;
721      }
722      itr->s[rlvl].i--;
723      itr_dirty = true;
724    } else {
725      assert(pi < p->n && p->ptr[pi + 1]->n == T - 1);
726      merge_node(b, p, pi);
727      // no iter adjustment needed
728    }
729    lasti = &itr->s[rlvl].i;
730    rlvl--;
731    x = p;
732  }
733
734  // 6.
735  if (b->root->n == 0) {
736    if (itr->lvl > 0) {
737      memmove(itr->s, itr->s + 1, (size_t)(itr->lvl - 1) * sizeof(*itr->s));
738      itr->lvl--;
739    }
740    if (b->root->level) {
741      MTNode *oldroot = b->root;
742      b->root = b->root->ptr[0];
743      for (int m = 0; m < kMTMetaCount; m++) {
744        assert(b->meta_root[m] == oldroot->meta[0][m]);
745      }
746
747      b->root->parent = NULL;
748      marktree_free_node(b, oldroot);
749    } else {
750      // no items, nothing for iterator to point to
751      // not strictly needed, should handle delete right-most mark anyway
752      itr->x = NULL;
753    }
754  }
755
756  if (itr->x && itr_dirty) {
757    marktree_itr_fix_pos(b, itr);
758  }
759
760  // BONUS STEP: fix the iterator, so that it points to the key afterwards
761  // TODO(bfredl): with "rev" should point before
762  // if (adjustment == 1) {
763  //   abort();
764  // }
765  if (adjustment == -1) {
766    // tricky: we stand at the deleted space in the previous leaf node.
767    // But the inner key is now the previous key we stole, so we need
768    // to skip that one as well.
769    marktree_itr_next(b, itr);
770    marktree_itr_next(b, itr);
771  } else {
772    if (itr->x && itr->i >= itr->x->n) {
773      // we deleted the last key of a leaf node
774      // go to the inner key after that.
775      assert(itr->x->level == 0);
776      marktree_itr_next(b, itr);
777    }
778  }
779
780  return other;
781}
782
783void marktree_revise_meta(MarkTree *b, MarkTreeIter *itr, MTKey old_key)
784{
785  uint32_t meta_old[kMTMetaCount], meta_new[kMTMetaCount];
786  meta_describe_key(meta_old, old_key);
787  meta_describe_key(meta_new, rawkey(itr));
788
789  if (!memcmp(meta_old, meta_new, sizeof(meta_old))) {
790    return;
791  }
792
793  MTNode *lnode = itr->x;
794  while (lnode->parent) {
795    uint32_t *meta_p = lnode->parent->meta[lnode->p_idx];
796    for (int m = 0; m < kMTMetaCount; m++) {
797      meta_p[m] += meta_new[m] - meta_old[m];
798    }
799
800    lnode = lnode->parent;
801  }
802
803  for (int m = 0; m < kMTMetaCount; m++) {
804    b->meta_root[m] += meta_new[m] - meta_old[m];
805  }
806}
807
808/// similar to intersect_common but modify x and y in place to retain
809/// only the items which are NOT in common
810static void intersect_merge(Intersection *restrict m, Intersection *restrict x,
811                            Intersection *restrict y)
812{
813  size_t xi = 0;
814  size_t yi = 0;
815  size_t xn = 0;
816  size_t yn = 0;
817  while (xi < kv_size(*x) && yi < kv_size(*y)) {
818    if (kv_A(*x, xi) == kv_A(*y, yi)) {
819      // TODO(bfredl): kvi_pushp is actually quite complex, break out kvi_resize() to a function?
820      kvi_push(*m, kv_A(*x, xi));
821      xi++;
822      yi++;
823    } else if (kv_A(*x, xi) < kv_A(*y, yi)) {
824      kv_A(*x, xn++) = kv_A(*x, xi++);
825    } else {
826      kv_A(*y, yn++) = kv_A(*y, yi++);
827    }
828  }
829
830  if (xi < kv_size(*x)) {
831    memmove(&kv_A(*x, xn), &kv_A(*x, xi), sizeof(kv_A(*x, xn)) * (kv_size(*x) - xi));
832    xn += kv_size(*x) - xi;
833  }
834  if (yi < kv_size(*y)) {
835    memmove(&kv_A(*y, yn), &kv_A(*y, yi), sizeof(kv_A(*y, yn)) * (kv_size(*y) - yi));
836    yn += kv_size(*y) - yi;
837  }
838
839  kv_size(*x) = xn;
840  kv_size(*y) = yn;
841}
842
843// w used to be a child of x but it is now a child of y, adjust intersections accordingly
844// @param[out] d are intersections which should be added to the old children of y
845static void intersect_mov(Intersection *restrict x, Intersection *restrict y,
846                          Intersection *restrict w, Intersection *restrict d)
847{
848  size_t wi = 0;
849  size_t yi = 0;
850  size_t wn = 0;
851  size_t yn = 0;
852  size_t xi = 0;
853  while (wi < kv_size(*w) || xi < kv_size(*x)) {
854    if (wi < kv_size(*w) && (xi >= kv_size(*x) || kv_A(*x, xi) >= kv_A(*w, wi))) {
855      if (xi < kv_size(*x) && kv_A(*x, xi) == kv_A(*w, wi)) {
856        xi++;
857      }
858      // now w < x strictly
859      while (yi < kv_size(*y) && kv_A(*y, yi) < kv_A(*w, wi)) {
860        kvi_push(*d, kv_A(*y, yi));
861        yi++;
862      }
863      if (yi < kv_size(*y) && kv_A(*y, yi) == kv_A(*w, wi)) {
864        kv_A(*y, yn++) = kv_A(*y, yi++);
865        wi++;
866      } else {
867        kv_A(*w, wn++) = kv_A(*w, wi++);
868      }
869    } else {
870      // x < w strictly
871      while (yi < kv_size(*y) && kv_A(*y, yi) < kv_A(*x, xi)) {
872        kvi_push(*d, kv_A(*y, yi));
873        yi++;
874      }
875      if (yi < kv_size(*y) && kv_A(*y, yi) == kv_A(*x, xi)) {
876        kv_A(*y, yn++) = kv_A(*y, yi++);
877        xi++;
878      } else {
879        // add kv_A(x, xi) at kv_A(w, wn), pushing up wi if wi == wn
880        if (wi == wn) {
881          size_t n = kv_size(*w) - wn;
882          kvi_pushp(*w);
883          if (n > 0) {
884            memmove(&kv_A(*w, wn + 1), &kv_A(*w, wn), n * sizeof(kv_A(*w, 0)));
885          }
886          kv_A(*w, wi) = kv_A(*x, xi);
887          wn++;
888          wi++;  // no need to consider the added element again
889        } else {
890          assert(wn < wi);
891          kv_A(*w, wn++) = kv_A(*x, xi);
892        }
893        xi++;
894      }
895    }
896  }
897  if (yi < kv_size(*y)) {
898    // move remaining items to d
899    size_t n = kv_size(*y) - yi;  // at least one
900    kvi_ensure_more_space(*d, n);
901    memcpy(&kv_A(*d, kv_size(*d)), &kv_A(*y, yi), n * sizeof(kv_A(*d, 0)));
902    kv_size(*d) += n;
903  }
904  kv_size(*w) = wn;
905  kv_size(*y) = yn;
906}
907
908bool intersect_mov_test(const uint64_t *x, size_t nx, const uint64_t *y, size_t ny,
909                        const uint64_t *win, size_t nwin, uint64_t *wout, size_t *nwout,
910                        uint64_t *dout, size_t *ndout)
911{
912  // x is immutable in the context of intersect_mov. y might shrink, but we
913  // don't care about it (we get it the deleted ones in d)
914  Intersection xi = { .items = (uint64_t *)x, .size = nx };
915  Intersection yi = { .items = (uint64_t *)y, .size = ny };
916
917  Intersection w;
918  kvi_init(w);
919  for (size_t i = 0; i < nwin; i++) {
920    kvi_push(w, win[i]);
921  }
922  Intersection d;
923  kvi_init(d);
924
925  intersect_mov(&xi, &yi, &w, &d);
926
927  if (w.size > *nwout || d.size > *ndout) {
928    return false;
929  }
930
931  memcpy(wout, w.items, sizeof(w.items[0]) * w.size);
932  *nwout = w.size;
933
934  memcpy(dout, d.items, sizeof(d.items[0]) * d.size);
935  *ndout = d.size;
936
937  return true;
938}
939
940/// intersection: i = x & y
941static void intersect_common(Intersection *i, Intersection *x, Intersection *y)
942{
943  size_t xi = 0;
944  size_t yi = 0;
945  while (xi < kv_size(*x) && yi < kv_size(*y)) {
946    if (kv_A(*x, xi) == kv_A(*y, yi)) {
947      kvi_push(*i, kv_A(*x, xi));
948      xi++;
949      yi++;
950    } else if (kv_A(*x, xi) < kv_A(*y, yi)) {
951      xi++;
952    } else {
953      yi++;
954    }
955  }
956}
957
958// inplace union: x |= y
959static void intersect_add(Intersection *x, Intersection *y)
960{
961  size_t xi = 0;
962  size_t yi = 0;
963  while (xi < kv_size(*x) && yi < kv_size(*y)) {
964    if (kv_A(*x, xi) == kv_A(*y, yi)) {
965      xi++;
966      yi++;
967    } else if (kv_A(*y, yi) < kv_A(*x, xi)) {
968      size_t n = kv_size(*x) - xi;  // at least one
969      kvi_pushp(*x);
970      memmove(&kv_A(*x, xi + 1), &kv_A(*x, xi), n * sizeof(kv_A(*x, 0)));
971      kv_A(*x, xi) = kv_A(*y, yi);
972      xi++;  // newly added element
973      yi++;
974    } else {
975      xi++;
976    }
977  }
978  if (yi < kv_size(*y)) {
979    size_t n = kv_size(*y) - yi;  // at least one
980    kvi_ensure_more_space(*x, n);
981    memcpy(&kv_A(*x, kv_size(*x)), &kv_A(*y, yi), n * sizeof(kv_A(*x, 0)));
982    kv_size(*x) += n;
983  }
984}
985
986// inplace asymmetric difference: x &= ~y
987static void intersect_sub(Intersection *restrict x, Intersection *restrict y)
988{
989  size_t xi = 0;
990  size_t yi = 0;
991  size_t xn = 0;
992  while (xi < kv_size(*x) && yi < kv_size(*y)) {
993    if (kv_A(*x, xi) == kv_A(*y, yi)) {
994      xi++;
995      yi++;
996    } else if (kv_A(*x, xi) < kv_A(*y, yi)) {
997      kv_A(*x, xn++) = kv_A(*x, xi++);
998    } else {
999      yi++;
1000    }
1001  }
1002  if (xi < kv_size(*x)) {
1003    size_t n = kv_size(*x) - xi;
1004    if (xn < xi) {  // otherwise xn == xi
1005      memmove(&kv_A(*x, xn), &kv_A(*x, xi), n * sizeof(kv_A(*x, 0)));
1006    }
1007    xn += n;
1008  }
1009  kv_size(*x) = xn;
1010}
1011
1012/// x is a node which shrunk, or the half of a split
1013///
1014/// this means that intervals which previously intersected all the (current)
1015/// child nodes, now instead intersects `x` itself.
1016static void bubble_up(MTNode *x)
1017{
1018  Intersection xi;
1019  kvi_init(xi);
1020  // due to invariants, the largest subset of _all_ subnodes is the intersection
1021  // between the first and the last
1022  intersect_common(&xi, &x->ptr[0]->intersect, &x->ptr[x->n]->intersect);
1023  if (kv_size(xi)) {
1024    for (int i = 0; i < x->n + 1; i++) {
1025      intersect_sub(&x->ptr[i]->intersect, &xi);
1026    }
1027    intersect_add(&x->intersect, &xi);
1028  }
1029  kvi_destroy(xi);
1030}
1031
1032static MTNode *merge_node(MarkTree *b, MTNode *p, int i)
1033{
1034  MTNode *x = p->ptr[i];
1035  MTNode *y = p->ptr[i + 1];
1036  Intersection mi;
1037  kvi_init(mi);
1038
1039  intersect_merge(&mi, &x->intersect, &y->intersect);
1040
1041  x->key[x->n] = p->key[i];
1042  refkey(b, x, x->n);
1043  if (i > 0) {
1044    relative(p->key[i - 1].pos, &x->key[x->n].pos);
1045  }
1046
1047  uint32_t meta_inc[kMTMetaCount];
1048  meta_describe_key(meta_inc, x->key[x->n]);
1049
1050  memmove(&x->key[x->n + 1], y->key, (size_t)y->n * sizeof(MTKey));
1051  for (int k = 0; k < y->n; k++) {
1052    refkey(b, x, x->n + 1 + k);
1053    unrelative(x->key[x->n].pos, &x->key[x->n + 1 + k].pos);
1054  }
1055  if (x->level) {
1056    // bubble down: ranges that intersected old-x but not old-y or vice versa
1057    // must be moved to their respective children
1058    memmove(&x->ptr[x->n + 1], y->ptr, ((size_t)y->n + 1) * sizeof(MTNode *));
1059    memmove(&x->meta[x->n + 1], y->meta, ((size_t)y->n + 1) * sizeof(y->meta[0]));
1060    for (int k = 0; k < x->n + 1; k++) {
1061      // TODO(bfredl): dedicated impl for "Z |= Y"
1062      for (size_t idx = 0; idx < kv_size(x->intersect); idx++) {
1063        intersect_node(b, x->ptr[k], kv_A(x->intersect, idx));
1064      }
1065    }
1066    for (int ky = 0; ky < y->n + 1; ky++) {
1067      int k = x->n + ky + 1;
1068      // nodes that used to be in y, now the second half of x
1069      x->ptr[k]->parent = x;
1070      x->ptr[k]->p_idx = (int16_t)k;
1071      // TODO(bfredl): dedicated impl for "Z |= X"
1072      for (size_t idx = 0; idx < kv_size(y->intersect); idx++) {
1073        intersect_node(b, x->ptr[k], kv_A(y->intersect, idx));
1074      }
1075    }
1076  }
1077  x->n += y->n + 1;
1078  for (int m = 0; m < kMTMetaCount; m++) {
1079    // x now contains everything of y plus old p->key[i]
1080    p->meta[i][m] += (p->meta[i + 1][m] + meta_inc[m]);
1081  }
1082
1083  memmove(&p->key[i], &p->key[i + 1], (size_t)(p->n - i - 1) * sizeof(MTKey));
1084  memmove(&p->ptr[i + 1], &p->ptr[i + 2], (size_t)(p->n - i - 1) * sizeof(MTKey *));
1085  memmove(&p->meta[i + 1], &p->meta[i + 2], (size_t)(p->n - i - 1) * sizeof(p->meta[0]));
1086  for (int j = i + 1; j < p->n; j++) {  // note: one has been deleted
1087    p->ptr[j]->p_idx = (int16_t)j;
1088  }
1089  p->n--;
1090  marktree_free_node(b, y);
1091
1092  kvi_destroy(x->intersect);
1093
1094  // move of a kvec_withinit_t, messy!
1095  // TODO(bfredl): special case version of intersect_merge(x_out, x_in_m_out, y) to avoid this
1096  kvi_move(&x->intersect, &mi);
1097
1098  return x;
1099}
1100
1101/// @param dest is overwritten (assumed to already been freed/moved)
1102/// @param src consumed (don't free or use)
1103void kvi_move(Intersection *dest, Intersection *src)
1104{
1105  dest->size = src->size;
1106  dest->capacity = src->capacity;
1107  if (src->items == src->init_array) {
1108    memcpy(dest->init_array, src->init_array, src->size * sizeof(*src->init_array));
1109    dest->items = dest->init_array;
1110  } else {
1111    dest->items = src->items;
1112  }
1113}
1114
1115// TODO(bfredl): as a potential "micro" optimization, pivoting should balance
1116// the two nodes instead of stealing just one key
1117// x_pos is the absolute position of the key just before x (or a dummy key strictly less than any
1118// key inside x, if x is the first leaf)
1119static void pivot_right(MarkTree *b, MTPos p_pos, MTNode *p, const int i)
1120{
1121  MTNode *x = p->ptr[i];
1122  MTNode *y = p->ptr[i + 1];
1123  memmove(&y->key[1], y->key, (size_t)y->n * sizeof(MTKey));
1124  if (y->level) {
1125    memmove(&y->ptr[1], y->ptr, ((size_t)y->n + 1) * sizeof(MTNode *));
1126    memmove(&y->meta[1], y->meta, ((size_t)y->n + 1) * sizeof(y->meta[0]));
1127    for (int j = 1; j < y->n + 2; j++) {
1128      y->ptr[j]->p_idx = (int16_t)j;
1129    }
1130  }
1131
1132  y->key[0] = p->key[i];
1133  refkey(b, y, 0);
1134  p->key[i] = x->key[x->n - 1];
1135  refkey(b, p, i);
1136
1137  uint32_t meta_inc_y[kMTMetaCount];
1138  meta_describe_key(meta_inc_y, y->key[0]);
1139  uint32_t meta_inc_x[kMTMetaCount];
1140  meta_describe_key(meta_inc_x, p->key[i]);
1141
1142  for (int m = 0; m < kMTMetaCount; m++) {
1143    p->meta[i + 1][m] += meta_inc_y[m];
1144    p->meta[i][m] -= meta_inc_x[m];
1145  }
1146
1147  if (x->level) {
1148    y->ptr[0] = x->ptr[x->n];
1149    memcpy(y->meta[0], x->meta[x->n], sizeof(y->meta[0]));
1150    for (int m = 0; m < kMTMetaCount; m++) {
1151      p->meta[i + 1][m] += y->meta[0][m];
1152      p->meta[i][m] -= y->meta[0][m];
1153    }
1154    y->ptr[0]->parent = y;
1155    y->ptr[0]->p_idx = 0;
1156  }
1157  x->n--;
1158  y->n++;
1159  if (i > 0) {
1160    unrelative(p->key[i - 1].pos, &p->key[i].pos);
1161  }
1162  relative(p->key[i].pos, &y->key[0].pos);
1163  for (int k = 1; k < y->n; k++) {
1164    unrelative(y->key[0].pos, &y->key[k].pos);
1165  }
1166
1167  // repair intersections of x
1168  if (x->level) {
1169    // handle y and first new y->ptr[0]
1170    Intersection d;
1171    kvi_init(d);
1172    // y->ptr[0] was moved from x to y
1173    // adjust y->ptr[0] for a difference between the parents
1174    // in addition, this might cause some intersection of the old y
1175    // to bubble down to the old children of y (if y->ptr[0] wasn't intersected)
1176    intersect_mov(&x->intersect, &y->intersect, &y->ptr[0]->intersect, &d);
1177    if (kv_size(d)) {
1178      for (int yi = 1; yi < y->n + 1; yi++) {
1179        intersect_add(&y->ptr[yi]->intersect, &d);
1180      }
1181    }
1182    kvi_destroy(d);
1183
1184    bubble_up(x);
1185  } else {
1186    // if the last element of x used to be an end node, check if it now covers all of x
1187    if (mt_end(p->key[i])) {
1188      uint64_t pi = pseudo_index(x, 0);  // note: sloppy pseudo-index
1189      uint64_t start_id = mt_lookup_key_side(p->key[i], false);
1190      uint64_t pi_start = pseudo_index_for_id(b, start_id, true);
1191      if (pi_start > 0 && pi_start < pi) {
1192        intersect_node(b, x, start_id);
1193      }
1194    }
1195
1196    if (mt_start(y->key[0])) {
1197      // no need for a check, just delet it if it was there
1198      unintersect_node(b, y, mt_lookup_key(y->key[0]), false);
1199    }
1200  }
1201}
1202
1203static void pivot_left(MarkTree *b, MTPos p_pos, MTNode *p, int i)
1204{
1205  MTNode *x = p->ptr[i];
1206  MTNode *y = p->ptr[i + 1];
1207
1208  // reverse from how we "always" do it. but pivot_left
1209  // is just the inverse of pivot_right, so reverse it literally.
1210  for (int k = 1; k < y->n; k++) {
1211    relative(y->key[0].pos, &y->key[k].pos);
1212  }
1213  unrelative(p->key[i].pos, &y->key[0].pos);
1214  if (i > 0) {
1215    relative(p->key[i - 1].pos, &p->key[i].pos);
1216  }
1217
1218  x->key[x->n] = p->key[i];
1219  refkey(b, x, x->n);
1220  p->key[i] = y->key[0];
1221  refkey(b, p, i);
1222
1223  uint32_t meta_inc_x[kMTMetaCount];
1224  meta_describe_key(meta_inc_x, x->key[x->n]);
1225  uint32_t meta_inc_y[kMTMetaCount];
1226  meta_describe_key(meta_inc_y, p->key[i]);
1227  for (int m = 0; m < kMTMetaCount; m++) {
1228    p->meta[i][m] += meta_inc_x[m];
1229    p->meta[i + 1][m] -= meta_inc_y[m];
1230  }
1231
1232  if (x->level) {
1233    x->ptr[x->n + 1] = y->ptr[0];
1234    memcpy(x->meta[x->n + 1], y->meta[0], sizeof(y->meta[0]));
1235    for (int m = 0; m < kMTMetaCount; m++) {
1236      p->meta[i + 1][m] -= y->meta[0][m];
1237      p->meta[i][m] += y->meta[0][m];
1238    }
1239    x->ptr[x->n + 1]->parent = x;
1240    x->ptr[x->n + 1]->p_idx = (int16_t)(x->n + 1);
1241  }
1242  memmove(y->key, &y->key[1], (size_t)(y->n - 1) * sizeof(MTKey));
1243  if (y->level) {
1244    memmove(y->ptr, &y->ptr[1], (size_t)y->n * sizeof(MTNode *));
1245    memmove(y->meta, &y->meta[1], (size_t)y->n * sizeof(y->meta[0]));
1246    for (int j = 0; j < y->n; j++) {  // note: last item deleted
1247      y->ptr[j]->p_idx = (int16_t)j;
1248    }
1249  }
1250  x->n++;
1251  y->n--;
1252
1253  // repair intersections of x,y
1254  if (x->level) {
1255    // handle y and first new y->ptr[0]
1256    Intersection d;
1257    kvi_init(d);
1258    // x->ptr[x->n] was moved from y to x
1259    // adjust x->ptr[x->n] for a difference between the parents
1260    // in addition, this might cause some intersection of the old x
1261    // to bubble down to the old children of x (if x->ptr[n] wasn't intersected)
1262    intersect_mov(&y->intersect, &x->intersect, &x->ptr[x->n]->intersect, &d);
1263    if (kv_size(d)) {
1264      for (int xi = 0; xi < x->n; xi++) {  // ptr[x->n| deliberately skipped
1265        intersect_add(&x->ptr[xi]->intersect, &d);
1266      }
1267    }
1268    kvi_destroy(d);
1269
1270    bubble_up(y);
1271  } else {
1272    // if the first element of y used to be an start node, check if it now covers all of y
1273    if (mt_start(p->key[i])) {
1274      uint64_t pi = pseudo_index(y, 0);  // note: sloppy pseudo-index
1275
1276      uint64_t end_id = mt_lookup_key_side(p->key[i], true);
1277      uint64_t pi_end = pseudo_index_for_id(b, end_id, true);
1278
1279      if (pi_end > pi) {
1280        intersect_node(b, y, mt_lookup_key(p->key[i]));
1281      }
1282    }
1283
1284    if (mt_end(x->key[x->n - 1])) {
1285      // no need for a check, just delet it if it was there
1286      unintersect_node(b, x, mt_lookup_key_side(x->key[x->n - 1], false), false);
1287    }
1288  }
1289}
1290
1291/// frees all mem, resets tree to valid empty state
1292void marktree_clear(MarkTree *b)
1293{
1294  if (b->root) {
1295    marktree_free_subtree(b, b->root);
1296    b->root = NULL;
1297  }
1298  map_destroy(uint64_t, b->id2node);
1299  b->n_keys = 0;
1300  memset(b->meta_root, 0, kMTMetaCount * sizeof(b->meta_root[0]));
1301  assert(b->n_nodes == 0);
1302}
1303
1304void marktree_free_subtree(MarkTree *b, MTNode *x)
1305{
1306  if (x->level) {
1307    for (int i = 0; i < x->n + 1; i++) {
1308      marktree_free_subtree(b, x->ptr[i]);
1309    }
1310  }
1311  marktree_free_node(b, x);
1312}
1313
1314static void marktree_free_node(MarkTree *b, MTNode *x)
1315{
1316  kvi_destroy(x->intersect);
1317  xfree(x);
1318  b->n_nodes--;
1319}
1320
1321/// @param itr iterator is invalid after call
1322void marktree_move(MarkTree *b, MarkTreeIter *itr, int row, int col)
1323{
1324  MTKey key = rawkey(itr);
1325  MTNode *x = itr->x;
1326  if (!x->level) {
1327    bool internal = false;
1328    MTPos newpos = MTPos(row, col);
1329    if (x->parent != NULL) {
1330      // strictly _after_ key before `x`
1331      // (not optimal when x is very first leaf of the entire tree, but that's fine)
1332      if (pos_less(itr->pos, newpos)) {
1333        relative(itr->pos, &newpos);
1334
1335        // strictly before the end of x. (this could be made sharper by
1336        // finding the internal key just after x, but meh)
1337        if (pos_less(newpos, x->key[x->n - 1].pos)) {
1338          internal = true;
1339        }
1340      }
1341    } else {
1342      // tree is one node. newpos thus is already "relative" itr->pos
1343      internal = true;
1344    }
1345
1346    if (internal) {
1347      if (key.pos.row == newpos.row && key.pos.col == newpos.col) {
1348        return;
1349      }
1350      key.pos = newpos;
1351      bool match;
1352      // tricky: could minimize movement in either direction better
1353      int new_i = marktree_getp_aux(x, key, &match);
1354      if (!match) {
1355        new_i++;
1356      }
1357      if (new_i == itr->i) {
1358        x->key[itr->i].pos = newpos;
1359      } else if (new_i < itr->i) {
1360        memmove(&x->key[new_i + 1], &x->key[new_i], sizeof(MTKey) * (size_t)(itr->i - new_i));
1361        x->key[new_i] = key;
1362      } else if (new_i > itr->i) {
1363        memmove(&x->key[itr->i], &x->key[itr->i + 1], sizeof(MTKey) * (size_t)(new_i - itr->i - 1));
1364        x->key[new_i - 1] = key;
1365      }
1366      return;
1367    }
1368  }
1369  uint64_t other = marktree_del_itr(b, itr, false);
1370  key.pos = (MTPos){ row, col };
1371
1372  marktree_put_key(b, key);
1373
1374  if (other) {
1375    marktree_restore_pair(b, key);
1376  }
1377  itr->x = NULL;  // itr might become invalid by put
1378}
1379
1380void marktree_restore_pair(MarkTree *b, MTKey key)
1381{
1382  MarkTreeIter itr[1];
1383  MarkTreeIter end_itr[1];
1384  marktree_lookup(b, mt_lookup_key_side(key, false), itr);
1385  marktree_lookup(b, mt_lookup_key_side(key, true), end_itr);
1386  if (!itr->x || !end_itr->x) {
1387    // this could happen if the other end is waiting to be restored later
1388    // this function will be called again for the other end.
1389    return;
1390  }
1391  rawkey(itr).flags &= (uint16_t) ~MT_FLAG_ORPHANED;
1392  rawkey(end_itr).flags &= (uint16_t) ~MT_FLAG_ORPHANED;
1393
1394  marktree_intersect_pair(b, mt_lookup_key_side(key, false), itr, end_itr, false);
1395}
1396
1397// itr functions
1398
1399bool marktree_itr_get(MarkTree *b, int32_t row, int col, MarkTreeIter *itr)
1400{
1401  return marktree_itr_get_ext(b, MTPos(row, col), itr, false, false, NULL, NULL);
1402}
1403
1404bool marktree_itr_get_ext(MarkTree *b, MTPos p, MarkTreeIter *itr, bool last, bool gravity,
1405                          MTPos *oldbase, MetaFilter meta_filter)
1406{
1407  if (b->n_keys == 0) {
1408    itr->x = NULL;
1409    return false;
1410  }
1411
1412  MTKey k = { .pos = p, .flags = gravity ? MT_FLAG_RIGHT_GRAVITY : 0 };
1413  if (last && !gravity) {
1414    k.flags = MT_FLAG_LAST;
1415  }
1416  itr->pos = (MTPos){ 0, 0 };
1417  itr->x = b->root;
1418  itr->lvl = 0;
1419  if (oldbase) {
1420    oldbase[itr->lvl] = itr->pos;
1421  }
1422  while (true) {
1423    itr->i = marktree_getp_aux(itr->x, k, 0) + 1;
1424
1425    if (itr->x->level == 0) {
1426      break;
1427    }
1428    if (meta_filter) {
1429      if (!meta_has(itr->x->meta[itr->i], meta_filter)) {
1430        // this takes us to the internal position after the first rejected node
1431        break;
1432      }
1433    }
1434
1435    itr->s[itr->lvl].i = itr->i;
1436    itr->s[itr->lvl].oldcol = itr->pos.col;
1437
1438    if (itr->i > 0) {
1439      compose(&itr->pos, itr->x->key[itr->i - 1].pos);
1440      relative(itr->x->key[itr->i - 1].pos, &k.pos);
1441    }
1442    itr->x = itr->x->ptr[itr->i];
1443    itr->lvl++;
1444    if (oldbase) {
1445      oldbase[itr->lvl] = itr->pos;
1446    }
1447  }
1448
1449  if (last) {
1450    return marktree_itr_prev(b, itr);
1451  } else if (itr->i >= itr->x->n) {
1452    // no need for "meta_filter" here, this just goes up one step
1453    return marktree_itr_next_skip(b, itr, true, false, NULL, NULL);
1454  }
1455  return true;
1456}
1457
1458bool marktree_itr_first(MarkTree *b, MarkTreeIter *itr)
1459{
1460  if (b->n_keys == 0) {
1461    itr->x = NULL;
1462    return false;
1463  }
1464
1465  itr->x = b->root;
1466  itr->i = 0;
1467  itr->lvl = 0;
1468  itr->pos = MTPos(0, 0);
1469  while (itr->x->level > 0) {
1470    itr->s[itr->lvl].i = 0;
1471    itr->s[itr->lvl].oldcol = 0;
1472    itr->lvl++;
1473    itr->x = itr->x->ptr[0];
1474  }
1475  return true;
1476}
1477
1478// gives the first key that is greater or equal to p
1479int marktree_itr_last(MarkTree *b, MarkTreeIter *itr)
1480{
1481  if (b->n_keys == 0) {
1482    itr->x = NULL;
1483    return false;
1484  }
1485  itr->pos = MTPos(0, 0);
1486  itr->x = b->root;
1487  itr->lvl = 0;
1488  while (true) {
1489    itr->i = itr->x->n;
1490
1491    if (itr->x->level == 0) {
1492      break;
1493    }
1494
1495    itr->s[itr->lvl].i = itr->i;
1496    itr->s[itr->lvl].oldcol = itr->pos.col;
1497
1498    assert(itr->i > 0);
1499    compose(&itr->pos, itr->x->key[itr->i - 1].pos);
1500
1501    itr->x = itr->x->ptr[itr->i];
1502    itr->lvl++;
1503  }
1504  itr->i--;
1505  return true;
1506}
1507
1508bool marktree_itr_next(MarkTree *b, MarkTreeIter *itr)
1509{
1510  return marktree_itr_next_skip(b, itr, false, false, NULL, NULL);
1511}
1512
1513static bool marktree_itr_next_skip(MarkTree *b, MarkTreeIter *itr, bool skip, bool preload,
1514                                   MTPos oldbase[], MetaFilter meta_filter)
1515{
1516  if (!itr->x) {
1517    return false;
1518  }
1519  itr->i++;
1520  if (meta_filter && itr->x->level > 0) {
1521    if (!meta_has(itr->x->meta[itr->i], meta_filter)) {
1522      skip = true;
1523    }
1524  }
1525  if (itr->x->level == 0 || skip) {
1526    if (preload && itr->x->level == 0 && skip) {
1527      // skip rest of this leaf node
1528      itr->i = itr->x->n;
1529    } else if (itr->i < itr->x->n) {
1530      // TODO(bfredl): this is the common case,
1531      // and could be handled by inline wrapper
1532      return true;
1533    }
1534    // we ran out of non-internal keys. Go up until we find an internal key
1535    while (itr->i >= itr->x->n) {
1536      itr->x = itr->x->parent;
1537      if (itr->x == NULL) {
1538        return false;
1539      }
1540      itr->lvl--;
1541      itr->i = itr->s[itr->lvl].i;
1542      if (itr->i > 0) {
1543        itr->pos.row -= itr->x->key[itr->i - 1].pos.row;
1544        itr->pos.col = itr->s[itr->lvl].oldcol;
1545      }
1546    }
1547  } else {
1548    // we stood at an "internal" key. Go down to the first non-internal
1549    // key after it.
1550    while (itr->x->level > 0) {
1551      // internal key, there is always a child after
1552      if (itr->i > 0) {
1553        itr->s[itr->lvl].oldcol = itr->pos.col;
1554        compose(&itr->pos, itr->x->key[itr->i - 1].pos);
1555      }
1556      if (oldbase && itr->i == 0) {
1557        oldbase[itr->lvl + 1] = oldbase[itr->lvl];
1558      }
1559      itr->s[itr->lvl].i = itr->i;
1560      assert(itr->x->ptr[itr->i]->parent == itr->x);
1561      itr->lvl++;
1562      itr->x = itr->x->ptr[itr->i];
1563      if (preload && itr->x->level) {
1564        itr->i = -1;
1565        break;
1566      }
1567      itr->i = 0;
1568      if (meta_filter && itr->x->level) {
1569        if (!meta_has(itr->x->meta[0], meta_filter)) {
1570          // itr->x has filtered keys but x->ptr[0] does not, don't enter the latter
1571          break;
1572        }
1573      }
1574    }
1575  }
1576  return true;
1577}
1578
1579bool marktree_itr_get_filter(MarkTree *b, int32_t row, int col, int stop_row, int stop_col,
1580                             MetaFilter meta_filter, MarkTreeIter *itr)
1581{
1582  if (!meta_has(b->meta_root, meta_filter)) {
1583    return false;
1584  }
1585  if (!marktree_itr_get_ext(b, MTPos(row, col), itr, false, false, NULL, meta_filter)) {
1586    return false;
1587  }
1588
1589  return marktree_itr_check_filter(b, itr, stop_row, stop_col, meta_filter);
1590}
1591
1592/// use after marktree_itr_get_overlap() to continue in a filtered fashion
1593///
1594/// not strictly needed but steps out to the right parent node where there
1595/// might be "start" keys matching the filter ("end" keys are properly handled
1596/// by marktree_itr_step_overlap() already)
1597bool marktree_itr_step_out_filter(MarkTree *b, MarkTreeIter *itr, MetaFilter meta_filter)
1598{
1599  if (!meta_has(b->meta_root, meta_filter)) {
1600    itr->x = NULL;
1601    return false;
1602  }
1603
1604  while (itr->x && itr->x->parent) {
1605    if (meta_has(itr->x->parent->meta[itr->x->p_idx], meta_filter)) {
1606      return true;
1607    }
1608
1609    itr->i = itr->x->n;
1610
1611    // no filter needed, just reuse the code path for step to parent
1612    marktree_itr_next_skip(b, itr, true, false, NULL, NULL);
1613  }
1614
1615  return itr->x;
1616}
1617
1618bool marktree_itr_next_filter(MarkTree *b, MarkTreeIter *itr, int stop_row, int stop_col,
1619                              MetaFilter meta_filter)
1620{
1621  if (!marktree_itr_next_skip(b, itr, false, false, NULL, meta_filter)) {
1622    return false;
1623  }
1624
1625  return marktree_itr_check_filter(b, itr, stop_row, stop_col, meta_filter);
1626}
1627
1628static const uint32_t meta_map[kMTMetaCount] = {
1629  MT_FLAG_DECOR_VIRT_TEXT_INLINE,
1630  MT_FLAG_DECOR_VIRT_LINES,
1631  MT_FLAG_DECOR_SIGNHL,
1632  MT_FLAG_DECOR_SIGNTEXT,
1633  MT_FLAG_DECOR_CONCEAL_LINES
1634};
1635static bool marktree_itr_check_filter(MarkTree *b, MarkTreeIter *itr, int stop_row, int stop_col,
1636                                      MetaFilter meta_filter)
1637{
1638  MTPos stop_pos = MTPos(stop_row, stop_col);
1639
1640  uint32_t key_filter = 0;
1641  for (int m = 0; m < kMTMetaCount; m++) {
1642    key_filter |= meta_map[m]&meta_filter[m];
1643  }
1644
1645  while (true) {
1646    if (pos_leq(stop_pos, marktree_itr_pos(itr))) {
1647      itr->x = NULL;
1648      return false;
1649    }
1650
1651    MTKey k = rawkey(itr);
1652    if (!mt_end(k) && (k.flags & key_filter)) {
1653      return true;
1654    }
1655
1656    // this skips subtrees, but not keys, thus the outer loop
1657    if (!marktree_itr_next_skip(b, itr, false, false, NULL, meta_filter)) {
1658      return false;
1659    }
1660  }
1661}
1662
1663bool marktree_itr_prev(MarkTree *b, MarkTreeIter *itr)
1664{
1665  if (!itr->x) {
1666    return false;
1667  }
1668  if (itr->x->level == 0) {
1669    itr->i--;
1670    if (itr->i >= 0) {
1671      // TODO(bfredl): this is the common case,
1672      // and could be handled by inline wrapper
1673      return true;
1674    }
1675    // we ran out of non-internal keys. Go up until we find a non-internal key
1676    while (itr->i < 0) {
1677      itr->x = itr->x->parent;
1678      if (itr->x == NULL) {
1679        return false;
1680      }
1681      itr->lvl--;
1682      itr->i = itr->s[itr->lvl].i - 1;
1683      if (itr->i >= 0) {
1684        itr->pos.row -= itr->x->key[itr->i].pos.row;
1685        itr->pos.col = itr->s[itr->lvl].oldcol;
1686      }
1687    }
1688  } else {
1689    // we stood at an "internal" key. Go down to the last non-internal
1690    // key before it.
1691    while (itr->x->level > 0) {
1692      // internal key, there is always a child before
1693      if (itr->i > 0) {
1694        itr->s[itr->lvl].oldcol = itr->pos.col;
1695        compose(&itr->pos, itr->x->key[itr->i - 1].pos);
1696      }
1697      itr->s[itr->lvl].i = itr->i;
1698      assert(itr->x->ptr[itr->i]->parent == itr->x);
1699      itr->x = itr->x->ptr[itr->i];
1700      itr->i = itr->x->n;
1701      itr->lvl++;
1702    }
1703    itr->i--;
1704  }
1705  return true;
1706}
1707
1708bool marktree_itr_node_done(MarkTreeIter *itr)
1709{
1710  return !itr->x || itr->i == itr->x->n - 1;
1711}
1712
1713MTPos marktree_itr_pos(MarkTreeIter *itr)
1714{
1715  MTPos pos = rawkey(itr).pos;
1716  unrelative(itr->pos, &pos);
1717  return pos;
1718}
1719
1720MTKey marktree_itr_current(MarkTreeIter *itr)
1721{
1722  if (itr->x) {
1723    MTKey key = rawkey(itr);
1724    key.pos = marktree_itr_pos(itr);
1725    return key;
1726  }
1727  return MT_INVALID_KEY;
1728}
1729
1730static bool itr_eq(MarkTreeIter *itr1, MarkTreeIter *itr2)
1731{
1732  return (&rawkey(itr1) == &rawkey(itr2));
1733}
1734
1735/// Get all marks which overlaps the position (row,col)
1736///
1737/// After calling this function, use marktree_itr_step_overlap to step through
1738/// one overlapping mark at a time, until it returns false
1739///
1740/// NOTE: It's possible to get all marks which overlaps a region (row,col) to (row_end,col_end)
1741/// To do this, first call marktree_itr_get_overlap with the start position and
1742/// keep calling marktree_itr_step_overlap until it returns false.
1743/// After this, as a second loop, keep calling the marktree_itr_next() until
1744/// the iterator is invalid or reaches past (row_end, col_end). In this loop,
1745/// consider all "start" marks (and unpaired marks if relevant), but skip over
1746/// all "end" marks, using mt_end(mark).
1747///
1748/// @return false if we already know no marks can be found
1749///               even if "true" the first call to marktree_itr_step_overlap
1750///               could return false
1751bool marktree_itr_get_overlap(MarkTree *b, int row, int col, MarkTreeIter *itr)
1752{
1753  if (b->n_keys == 0) {
1754    itr->x = NULL;
1755    return false;
1756  }
1757
1758  itr->x = b->root;
1759  itr->i = -1;
1760  itr->lvl = 0;
1761  itr->pos = MTPos(0, 0);
1762  itr->intersect_pos = MTPos(row, col);
1763  // intersect_pos but will be adjusted relative itr->x
1764  itr->intersect_pos_x = MTPos(row, col);
1765  itr->intersect_idx = 0;
1766  return true;
1767}
1768
1769/// Step through all overlapping pairs at a position.
1770///
1771/// This function must only be used with an iterator from |marktree_itr_step_overlap|
1772///
1773/// @return true if a valid pair was found (returned as `pair`)
1774/// When all overlapping mark pairs have been found, false will be returned. `itr`
1775/// is then valid as an ordinary iterator at the (row, col) position specified in
1776/// marktree_itr_step_overlap
1777bool marktree_itr_step_overlap(MarkTree *b, MarkTreeIter *itr, MTPair *pair)
1778{
1779  // phase one: we start at the root node and step inwards towards itr->intersect_pos
1780  // (the position queried in marktree_itr_get_overlap)
1781  //
1782  // For each node (ancestor node to the node containing the sought position)
1783  // we return all intersecting intervals, one at a time
1784  while (itr->i == -1) {
1785    if (itr->intersect_idx < kv_size(itr->x->intersect)) {
1786      uint64_t id = kv_A(itr->x->intersect, itr->intersect_idx++);
1787      *pair = mtpair_from(marktree_lookup(b, id, NULL),
1788                          marktree_lookup(b, id|MARKTREE_END_FLAG, NULL));
1789      return true;
1790    }
1791
1792    if (itr->x->level == 0) {
1793      itr->s[itr->lvl].i = itr->i = 0;
1794      break;
1795    }
1796
1797    MTKey k = { .pos = itr->intersect_pos_x, .flags = 0 };
1798    itr->i = marktree_getp_aux(itr->x, k, 0) + 1;
1799
1800    itr->s[itr->lvl].i = itr->i;
1801    itr->s[itr->lvl].oldcol = itr->pos.col;
1802
1803    if (itr->i > 0) {
1804      compose(&itr->pos, itr->x->key[itr->i - 1].pos);
1805      relative(itr->x->key[itr->i - 1].pos, &itr->intersect_pos_x);
1806    }
1807    itr->x = itr->x->ptr[itr->i];
1808    itr->lvl++;
1809    itr->i = -1;
1810    itr->intersect_idx = 0;
1811  }
1812
1813  // phase two: we now need to handle the node found at itr->intersect_pos
1814  // first consider all start nodes in the node before this position.
1815  while (itr->i < itr->x->n && pos_less(rawkey(itr).pos, itr->intersect_pos_x)) {
1816    MTKey k = itr->x->key[itr->i++];
1817    itr->s[itr->lvl].i = itr->i;
1818    if (mt_start(k)) {
1819      MTKey end = marktree_lookup(b, mt_lookup_id(k.ns, k.id, true), NULL);
1820      if (pos_less(end.pos, itr->intersect_pos)) {
1821        continue;
1822      }
1823
1824      unrelative(itr->pos, &k.pos);
1825      *pair = mtpair_from(k, end);
1826      return true;  // it's a start!
1827    }
1828  }
1829
1830  // phase 2B: We also need to step to the end of this node and consider all end marks, which
1831  // might end an interval overlapping itr->intersect_pos
1832  while (itr->i < itr->x->n) {
1833    MTKey k = itr->x->key[itr->i++];
1834    if (mt_end(k)) {
1835      uint64_t id = mt_lookup_id(k.ns, k.id, false);
1836      if (id2node(b, id) == itr->x) {
1837        continue;
1838      }
1839      unrelative(itr->pos, &k.pos);
1840      MTKey start = marktree_lookup(b, id, NULL);
1841      if (pos_leq(itr->intersect_pos, start.pos)) {
1842        continue;
1843      }
1844      *pair = mtpair_from(start, k);
1845      return true;  // end of a range which began before us!
1846    }
1847  }
1848
1849  // when returning false, get back to the queried position, to ensure the caller
1850  // can keep using it as an ordinary iterator at the queried position. The docstring
1851  // for marktree_itr_get_overlap explains how this is useful.
1852  itr->i = itr->s[itr->lvl].i;
1853  assert(itr->i >= 0);
1854  if (itr->i >= itr->x->n) {
1855    marktree_itr_next(b, itr);
1856  }
1857
1858  // either on or after the intersected position, bail out
1859  return false;
1860}
1861
1862static void check_damage(MarkTree *b, MTDamageMap *damage, MarkTreeIter *itr1, MarkTreeIter *itr2)
1863{
1864  const uint64_t start_id = mt_lookup_key_side(rawkey(itr1), false);
1865  MTDamagePair *p = map_put_ref(uint64_t, MTDamagePair)(damage, start_id, NULL, NULL);
1866  MTDamage *me = mt_end(rawkey(itr1)) ? &p->end : &p->start;
1867  assert(me->new == NULL);
1868  *me = (MTDamage){ .old = itr1->x, .new = itr2->x, .old_i = itr1->i, .new_i = itr2->i  };
1869}
1870
1871static void swap_keys(MarkTree *b, MarkTreeIter *itr1, MarkTreeIter *itr2, MTDamageMap *damage)
1872{
1873  if (itr1->x->level || itr1->x != itr2->x) {
1874    if (mt_paired(rawkey(itr1))) {
1875      check_damage(b, damage, itr1, itr2);
1876    }
1877    if (mt_paired(rawkey(itr2))) {
1878      check_damage(b, damage, itr2, itr1);
1879    }
1880  }
1881
1882  if (itr1->x != itr2->x) {
1883    uint32_t meta_inc_1[kMTMetaCount];
1884    meta_describe_key(meta_inc_1, rawkey(itr1));
1885    uint32_t meta_inc_2[kMTMetaCount];
1886    meta_describe_key(meta_inc_2, rawkey(itr2));
1887
1888    if (memcmp(meta_inc_1, meta_inc_2, sizeof(meta_inc_1)) != 0) {
1889      MTNode *x1 = itr1->x;
1890      MTNode *x2 = itr2->x;
1891      while (x1 != x2) {
1892        if (x1->level <= x2->level) {
1893          // as the root node uniquely has the highest level, x1 cannot be it
1894          uint32_t *meta_node = x1->parent->meta[x1->p_idx];
1895          for (int m = 0; m < kMTMetaCount; m++) {
1896            meta_node[m] += meta_inc_2[m] - meta_inc_1[m];
1897          }
1898          x1 = x1->parent;
1899        }
1900        if (x2->level < x1->level) {
1901          uint32_t *meta_node = x2->parent->meta[x2->p_idx];
1902          for (int m = 0; m < kMTMetaCount; m++) {
1903            meta_node[m] += meta_inc_1[m] - meta_inc_2[m];
1904          }
1905          x2 = x2->parent;
1906        }
1907      }
1908    }
1909  }
1910
1911  MTKey key1 = rawkey(itr1);
1912  MTKey key2 = rawkey(itr2);
1913  rawkey(itr1) = key2;
1914  rawkey(itr1).pos = key1.pos;
1915  rawkey(itr2) = key1;
1916  rawkey(itr2).pos = key2.pos;
1917  refkey(b, itr1->x, itr1->i);
1918  refkey(b, itr2->x, itr2->i);
1919}
1920
1921bool marktree_splice(MarkTree *b, int32_t start_line, int start_col, int old_extent_line,
1922                     int old_extent_col, int new_extent_line, int new_extent_col)
1923{
1924  MTPos start = { start_line, start_col };
1925  MTPos old_extent = { old_extent_line, old_extent_col };
1926  MTPos new_extent = { new_extent_line, new_extent_col };
1927
1928  bool may_delete = (old_extent.row != 0 || old_extent.col != 0);
1929  bool same_line = old_extent.row == 0 && new_extent.row == 0;
1930  unrelative(start, &old_extent);
1931  unrelative(start, &new_extent);
1932  MarkTreeIter itr[1] = { 0 };
1933  MarkTreeIter enditr[1] = { 0 };
1934
1935  MTPos oldbase[MT_MAX_DEPTH] = { 0 };
1936
1937  marktree_itr_get_ext(b, start, itr, false, true, oldbase, NULL);
1938  if (!itr->x) {
1939    // den e FÄRDIG
1940    return false;
1941  }
1942  MTPos delta = { new_extent.row - old_extent.row,
1943                  new_extent.col - old_extent.col };
1944
1945  if (may_delete) {
1946    MTPos ipos = marktree_itr_pos(itr);
1947    if (!pos_leq(old_extent, ipos)
1948        || (old_extent.row == ipos.row && old_extent.col == ipos.col
1949            && !mt_right(rawkey(itr)))) {
1950      marktree_itr_get_ext(b, old_extent, enditr, true, true, NULL, NULL);
1951      assert(enditr->x);
1952      // "assert" (itr <= enditr)
1953    } else {
1954      may_delete = false;
1955    }
1956  }
1957
1958  bool past_right = false;
1959  bool moved = false;
1960  MTDamageMap damage = MAP_INIT;
1961
1962  // Follow the general strategy of messing things up and fix them later
1963  // "oldbase" carries the information needed to calculate old position of
1964  // children.
1965  if (may_delete) {
1966    while (itr->x && !past_right) {
1967      MTPos loc_start = start;
1968      MTPos loc_old = old_extent;
1969      relative(itr->pos, &loc_start);
1970
1971      relative(oldbase[itr->lvl], &loc_old);
1972
1973continue_same_node:
1974      // NB: strictly should be less than the right gravity of loc_old, but
1975      // the iter comparison below will already break on that.
1976      if (!pos_leq(rawkey(itr).pos, loc_old)) {
1977        break;
1978      }
1979
1980      if (mt_right(rawkey(itr))) {
1981        while (!itr_eq(itr, enditr)
1982               && mt_right(rawkey(enditr))) {
1983          marktree_itr_prev(b, enditr);
1984        }
1985        if (!mt_right(rawkey(enditr))) {
1986          swap_keys(b, itr, enditr, &damage);
1987        } else {
1988          past_right = true;  // NOLINT
1989          (void)past_right;
1990          break;
1991        }
1992      }
1993
1994      if (itr_eq(itr, enditr)) {
1995        // actually, will be past_right after this key
1996        past_right = true;
1997      }
1998
1999      moved = true;
2000      if (itr->x->level) {
2001        oldbase[itr->lvl + 1] = rawkey(itr).pos;
2002        unrelative(oldbase[itr->lvl], &oldbase[itr->lvl + 1]);
2003        rawkey(itr).pos = loc_start;
2004        marktree_itr_next_skip(b, itr, false, false, oldbase, NULL);
2005      } else {
2006        rawkey(itr).pos = loc_start;
2007        if (itr->i < itr->x->n - 1) {
2008          itr->i++;
2009          if (!past_right) {
2010            goto continue_same_node;
2011          }
2012        } else {
2013          marktree_itr_next(b, itr);
2014        }
2015      }
2016    }
2017    while (itr->x) {
2018      MTPos loc_new = new_extent;
2019      relative(itr->pos, &loc_new);
2020      MTPos limit = old_extent;
2021
2022      relative(oldbase[itr->lvl], &limit);
2023
2024past_continue_same_node:
2025
2026      if (pos_leq(limit, rawkey(itr).pos)) {
2027        break;
2028      }
2029
2030      MTPos oldpos = rawkey(itr).pos;
2031      rawkey(itr).pos = loc_new;
2032      moved = true;
2033      if (itr->x->level) {
2034        oldbase[itr->lvl + 1] = oldpos;
2035        unrelative(oldbase[itr->lvl], &oldbase[itr->lvl + 1]);
2036
2037        marktree_itr_next_skip(b, itr, false, false, oldbase, NULL);
2038      } else {
2039        if (itr->i < itr->x->n - 1) {
2040          itr->i++;
2041          goto past_continue_same_node;
2042        } else {
2043          marktree_itr_next(b, itr);
2044        }
2045      }
2046    }
2047  }
2048
2049  while (itr->x) {
2050    unrelative(oldbase[itr->lvl], &rawkey(itr).pos);
2051    int realrow = rawkey(itr).pos.row;
2052    assert(realrow >= old_extent.row);
2053    bool done = false;
2054    if (realrow == old_extent.row) {
2055      if (delta.col) {
2056        rawkey(itr).pos.col += delta.col;
2057      }
2058    } else {
2059      if (same_line) {
2060        // optimization: column only adjustment can skip remaining rows
2061        done = true;
2062      }
2063    }
2064    if (delta.row) {
2065      rawkey(itr).pos.row += delta.row;
2066      moved = true;
2067    }
2068    relative(itr->pos, &rawkey(itr).pos);
2069    if (done) {
2070      break;
2071    }
2072    marktree_itr_next_skip(b, itr, true, false, NULL, NULL);
2073  }
2074
2075  uint64_t start_id;
2076  MTDamagePair d;
2077  map_foreach(&damage, start_id, d, {
2078    if (d.start.old && d.end.old) {
2079      // both ends of pair did move
2080      marktree_itr_set_node(b, itr, d.start.old, d.start.old_i);
2081      marktree_itr_set_node(b, enditr, d.end.old, d.end.old_i);
2082      marktree_intersect_pair(b, start_id, itr, enditr, true);
2083      marktree_itr_set_node(b, itr, d.start.new, d.start.new_i);
2084      marktree_itr_set_node(b, enditr, d.end.new, d.end.new_i);
2085      marktree_intersect_pair(b, start_id, itr, enditr, false);
2086    } else if (d.start.old) {
2087      // only start did move
2088      MarkTreeIter endpos[1];
2089      marktree_lookup(b, start_id | MARKTREE_END_FLAG, endpos);
2090      if (endpos->x) {
2091        marktree_itr_set_node(b, itr, d.start.old, d.start.old_i);
2092        *enditr = *endpos;
2093        marktree_intersect_pair(b, start_id, itr, enditr, true);
2094        marktree_itr_set_node(b, itr, d.start.new, d.start.new_i);
2095        *enditr = *endpos;
2096        marktree_intersect_pair(b, start_id, itr, enditr, false);
2097      }
2098    } else if (d.end.old) {
2099      // only end did move
2100      MarkTreeIter startpos[1];
2101      marktree_lookup(b, start_id, startpos);
2102      if (startpos->x) {
2103        *itr = *startpos;
2104        marktree_itr_set_node(b, enditr, d.end.old, d.end.old_i);
2105        marktree_intersect_pair(b, start_id, itr, enditr, true);
2106        *itr = *startpos;
2107        marktree_itr_set_node(b, enditr, d.end.new, d.end.new_i);
2108        marktree_intersect_pair(b, start_id, itr, enditr, false);
2109      }
2110    }
2111  });
2112  map_destroy(uint64_t, &damage);
2113
2114  return moved;
2115}
2116
2117void marktree_move_region(MarkTree *b, int start_row, colnr_T start_col, int extent_row,
2118                          colnr_T extent_col, int new_row, colnr_T new_col)
2119{
2120  MTPos start = { start_row, start_col };
2121  MTPos size = { extent_row, extent_col };
2122  MTPos end = size;
2123  unrelative(start, &end);
2124  MarkTreeIter itr[1] = { 0 };
2125  marktree_itr_get_ext(b, start, itr, false, true, NULL, NULL);
2126  kvec_t(MTKey) saved = KV_INITIAL_VALUE;
2127  while (itr->x) {
2128    MTKey k = marktree_itr_current(itr);
2129    if (!pos_leq(k.pos, end) || (k.pos.row == end.row && k.pos.col == end.col
2130                                 && mt_right(k))) {
2131      break;
2132    }
2133    relative(start, &k.pos);
2134    kv_push(saved, k);
2135    marktree_del_itr(b, itr, false);
2136  }
2137
2138  marktree_splice(b, start.row, start.col, size.row, size.col, 0, 0);
2139  MTPos new = { new_row, new_col };
2140  marktree_splice(b, new.row, new.col,
2141                  0, 0, size.row, size.col);
2142
2143  for (size_t i = 0; i < kv_size(saved); i++) {
2144    MTKey item = kv_A(saved, i);
2145    unrelative(new, &item.pos);
2146    marktree_put_key(b, item);
2147    if (mt_paired(item)) {
2148      // other end might be later in `saved`, this will safely bail out then
2149      marktree_restore_pair(b, item);
2150    }
2151  }
2152  kv_destroy(saved);
2153}
2154
2155/// @param itr OPTIONAL. set itr to pos.
2156MTKey marktree_lookup_ns(MarkTree *b, uint32_t ns, uint32_t id, bool end, MarkTreeIter *itr)
2157{
2158  return marktree_lookup(b, mt_lookup_id(ns, id, end), itr);
2159}
2160
2161static uint64_t pseudo_index(MTNode *x, int i)
2162{
2163  int off = MT_LOG2_BRANCH * x->level;
2164  uint64_t index = 0;
2165
2166  while (x) {
2167    index |= (uint64_t)(i + 1) << off;
2168    off += MT_LOG2_BRANCH;
2169    i = x->p_idx;
2170    x = x->parent;
2171  }
2172
2173  return index;
2174}
2175
2176/// @param itr OPTIONAL. set itr to pos.
2177/// if sloppy, two keys at the same _leaf_ node has the same index
2178static uint64_t pseudo_index_for_id(MarkTree *b, uint64_t id, bool sloppy)
2179{
2180  MTNode *n = id2node(b, id);
2181  if (n == NULL) {
2182    return 0;  // a valid pseudo-index is never zero!
2183  }
2184
2185  int i = 0;
2186  if (n->level || !sloppy) {
2187    for (i = 0; i < n->n; i++) {
2188      if (mt_lookup_key(n->key[i]) == id) {
2189        break;
2190      }
2191    }
2192    assert(i < n->n);
2193    if (n->level) {
2194      i += 1;  // internal key i comes after ptr[i]
2195    }
2196  }
2197
2198  return pseudo_index(n, i);
2199}
2200
2201/// @param itr OPTIONAL. set itr to pos.
2202MTKey marktree_lookup(MarkTree *b, uint64_t id, MarkTreeIter *itr)
2203{
2204  MTNode *n = id2node(b, id);
2205  if (n == NULL) {
2206    if (itr) {
2207      itr->x = NULL;
2208    }
2209    return MT_INVALID_KEY;
2210  }
2211  int i = 0;
2212  for (i = 0; i < n->n; i++) {
2213    if (mt_lookup_key(n->key[i]) == id) {
2214      return marktree_itr_set_node(b, itr, n, i);
2215    }
2216  }
2217
2218  abort();
2219}
2220
2221MTKey marktree_itr_set_node(MarkTree *b, MarkTreeIter *itr, MTNode *n, int i)
2222{
2223  MTKey key = n->key[i];
2224  if (itr) {
2225    itr->i = i;
2226    itr->x = n;
2227    itr->lvl = b->root->level - n->level;
2228  }
2229  while (n->parent != NULL) {
2230    MTNode *p = n->parent;
2231    i = n->p_idx;
2232    assert(p->ptr[i] == n);
2233
2234    if (itr) {
2235      itr->s[b->root->level - p->level].i = i;
2236    }
2237    if (i > 0) {
2238      unrelative(p->key[i - 1].pos, &key.pos);
2239    }
2240    n = p;
2241  }
2242  if (itr) {
2243    marktree_itr_fix_pos(b, itr);
2244  }
2245  return key;
2246}
2247
2248MTPos marktree_get_altpos(MarkTree *b, MTKey mark, MarkTreeIter *itr)
2249{
2250  return marktree_get_alt(b, mark, itr).pos;
2251}
2252
2253/// @return alt mark for a paired mark or mark itself for unpaired mark
2254MTKey marktree_get_alt(MarkTree *b, MTKey mark, MarkTreeIter *itr)
2255{
2256  return mt_paired(mark) ? marktree_lookup_ns(b, mark.ns, mark.id, !mt_end(mark), itr) : mark;
2257}
2258
2259static void marktree_itr_fix_pos(MarkTree *b, MarkTreeIter *itr)
2260{
2261  itr->pos = (MTPos){ 0, 0 };
2262  MTNode *x = b->root;
2263  for (int lvl = 0; lvl < itr->lvl; lvl++) {
2264    itr->s[lvl].oldcol = itr->pos.col;
2265    int i = itr->s[lvl].i;
2266    if (i > 0) {
2267      compose(&itr->pos, x->key[i - 1].pos);
2268    }
2269    assert(x->level);
2270    x = x->ptr[i];
2271  }
2272  assert(x == itr->x);
2273}
2274
2275// for unit test
2276void marktree_put_test(MarkTree *b, uint32_t ns, uint32_t id, int row, int col, bool right_gravity,
2277                       int end_row, int end_col, bool end_right, bool meta_inline)
2278{
2279  uint16_t flags = mt_flags(right_gravity, false, false, false);
2280  // The specific choice is irrelevant here, we pick one counted decor
2281  // type to test the counting and filtering logic.
2282  flags |= meta_inline ? MT_FLAG_DECOR_VIRT_TEXT_INLINE : 0;
2283  MTKey key = { { row, col }, ns, id, flags, { .hl = DECOR_HIGHLIGHT_INLINE_INIT } };
2284  marktree_put(b, key, end_row, end_col, end_right);
2285}
2286
2287// for unit test
2288bool mt_right_test(MTKey key)
2289{
2290  return mt_right(key);
2291}
2292
2293// for unit test
2294void marktree_del_pair_test(MarkTree *b, uint32_t ns, uint32_t id)
2295{
2296  MarkTreeIter itr[1];
2297  marktree_lookup_ns(b, ns, id, false, itr);
2298
2299  uint64_t other = marktree_del_itr(b, itr, false);
2300  assert(other);
2301  marktree_lookup(b, other, itr);
2302  marktree_del_itr(b, itr, false);
2303}
2304
2305void marktree_check(MarkTree *b)
2306{
2307#ifndef NDEBUG
2308  if (b->root == NULL) {
2309    assert(b->n_keys == 0);
2310    assert(b->n_nodes == 0);
2311    assert(b->id2node == NULL || map_size(b->id2node) == 0);
2312    return;
2313  }
2314
2315  MTPos dummy;
2316  bool last_right = false;
2317
2318  size_t nkeys = marktree_check_node(b, b->root, &dummy, &last_right, b->meta_root);
2319  assert(b->n_keys == nkeys);
2320  assert(b->n_keys == map_size(b->id2node));
2321#else
2322  // Do nothing, as assertions are required
2323  (void)b;
2324#endif
2325}
2326
2327size_t marktree_check_node(MarkTree *b, MTNode *x, MTPos *last, bool *last_right,
2328                           const uint32_t *meta_node_ref)
2329{
2330  assert(x->n <= 2 * T - 1);
2331  // TODO(bfredl): too strict if checking "in repair" post-delete tree.
2332  assert(x->n >= (x != b->root ? T - 1 : 0));
2333  size_t n_keys = (size_t)x->n;
2334
2335  for (int i = 0; i < x->n; i++) {
2336    if (x->level) {
2337      n_keys += marktree_check_node(b, x->ptr[i], last, last_right, x->meta[i]);
2338    } else {
2339      *last = (MTPos) { 0, 0 };
2340    }
2341    if (i > 0) {
2342      unrelative(x->key[i - 1].pos, last);
2343    }
2344    assert(pos_leq(*last, x->key[i].pos));
2345    if (last->row == x->key[i].pos.row && last->col == x->key[i].pos.col) {
2346      assert(!*last_right || mt_right(x->key[i]));
2347    }
2348    *last_right = mt_right(x->key[i]);
2349    assert(x->key[i].pos.col >= 0);
2350    assert(pmap_get(uint64_t)(b->id2node, mt_lookup_key(x->key[i])) == x);
2351  }
2352
2353  if (x->level) {
2354    n_keys += marktree_check_node(b, x->ptr[x->n], last, last_right, x->meta[x->n]);
2355    unrelative(x->key[x->n - 1].pos, last);
2356
2357    for (int i = 0; i < x->n + 1; i++) {
2358      assert(x->ptr[i]->parent == x);
2359      assert(x->ptr[i]->p_idx == i);
2360      assert(x->ptr[i]->level == x->level - 1);
2361      // PARANOIA: check no double node ref
2362      for (int j = 0; j < i; j++) {
2363        assert(x->ptr[i] != x->ptr[j]);
2364      }
2365    }
2366  } else if (x->n > 0) {
2367    *last = x->key[x->n - 1].pos;
2368  }
2369
2370  uint32_t meta_node[kMTMetaCount];
2371  meta_describe_node(meta_node, x);
2372  for (int m = 0; m < kMTMetaCount; m++) {
2373    assert(meta_node_ref[m] == meta_node[m]);
2374  }
2375
2376  return n_keys;
2377}
2378
2379bool marktree_check_intersections(MarkTree *b)
2380{
2381  if (!b->root) {
2382    return true;
2383  }
2384  PMap(ptr_t) checked = MAP_INIT;
2385
2386  // 1. move x->intersect to checked[x] and reinit x->intersect
2387  mt_recurse_nodes(b->root, &checked);
2388
2389  // 2. iterate over all marks. for each START mark of a pair,
2390  // intersect the nodes between the pair
2391  MarkTreeIter itr[1];
2392  marktree_itr_first(b, itr);
2393  while (true) {
2394    MTKey mark = marktree_itr_current(itr);
2395    if (mark.pos.row < 0) {
2396      break;
2397    }
2398
2399    if (mt_start(mark)) {
2400      MarkTreeIter start_itr[1];
2401      MarkTreeIter end_itr[1];
2402      uint64_t end_id = mt_lookup_id(mark.ns, mark.id, true);
2403      MTKey k = marktree_lookup(b, end_id, end_itr);
2404      if (k.pos.row >= 0) {
2405        *start_itr = *itr;
2406        marktree_intersect_pair(b, mt_lookup_key(mark), start_itr, end_itr, false);
2407      }
2408    }
2409
2410    marktree_itr_next(b, itr);
2411  }
2412
2413  // 3. for each node check if the recreated intersection
2414  // matches the old checked[x] intersection.
2415  bool status = mt_recurse_nodes_compare(b->root, &checked);
2416
2417  uint64_t *val;
2418  map_foreach_value(&checked, val, {
2419    xfree(val);
2420  });
2421  map_destroy(ptr_t, &checked);
2422
2423  return status;
2424}
2425
2426void mt_recurse_nodes(MTNode *x, PMap(ptr_t) *checked)
2427{
2428  if (kv_size(x->intersect)) {
2429    kvi_push(x->intersect, (uint64_t)-1);  // sentinel
2430    uint64_t *val;
2431    if (x->intersect.items == x->intersect.init_array) {
2432      val = xmemdup(x->intersect.items, x->intersect.size * sizeof(*x->intersect.items));
2433    } else {
2434      val = x->intersect.items;
2435    }
2436    pmap_put(ptr_t)(checked, x, val);
2437    kvi_init(x->intersect);
2438  }
2439
2440  if (x->level) {
2441    for (int i = 0; i < x->n + 1; i++) {
2442      mt_recurse_nodes(x->ptr[i], checked);
2443    }
2444  }
2445}
2446
2447bool mt_recurse_nodes_compare(MTNode *x, PMap(ptr_t) *checked)
2448{
2449  uint64_t *ref = pmap_get(ptr_t)(checked, x);
2450  if (ref != NULL) {
2451    for (size_t i = 0;; i++) {
2452      if (ref[i] == (uint64_t)-1) {
2453        if (i != kv_size(x->intersect)) {
2454          return false;
2455        }
2456
2457        break;
2458      } else {
2459        if (kv_size(x->intersect) <= i || ref[i] != kv_A(x->intersect, i)) {
2460          return false;
2461        }
2462      }
2463    }
2464  } else {
2465    if (kv_size(x->intersect)) {
2466      return false;
2467    }
2468  }
2469
2470  if (x->level) {
2471    for (int i = 0; i < x->n + 1; i++) {
2472      if (!mt_recurse_nodes_compare(x->ptr[i], checked)) {
2473        return false;
2474      }
2475    }
2476  }
2477
2478  return true;
2479}
2480
2481// TODO(bfredl): kv_print
2482#define GA_PUT(x) ga_concat(ga, (char *)(x))
2483#define GA_PRINT(fmt, ...) snprintf(buf, sizeof(buf), fmt, __VA_ARGS__); \
2484  GA_PUT(buf);
2485
2486String mt_inspect(MarkTree *b, bool keys, bool dot)
2487{
2488  garray_T ga[1];
2489  ga_init(ga, (int)sizeof(char), 80);
2490  MTPos p = { 0, 0 };
2491  if (b->root) {
2492    if (dot) {
2493      GA_PUT("digraph D {\n\n");
2494      mt_inspect_dotfile_node(b, ga, b->root, p, NULL);
2495      GA_PUT("\n}");
2496    } else {
2497      mt_inspect_node(b, ga, keys, b->root, p);
2498    }
2499  }
2500  return ga_take_string(ga);
2501}
2502
2503static inline uint64_t mt_dbg_id(uint64_t id)
2504{
2505  return (id >> 1) & 0xffffffff;
2506}
2507
2508static void mt_inspect_node(MarkTree *b, garray_T *ga, bool keys, MTNode *n, MTPos off)
2509{
2510  static char buf[1024];
2511  GA_PUT("[");
2512  if (keys && kv_size(n->intersect)) {
2513    for (size_t i = 0; i < kv_size(n->intersect); i++) {
2514      GA_PUT(i == 0 ? "{" : ";");
2515      // GA_PRINT("%"PRIu64, kv_A(n->intersect, i));
2516      GA_PRINT("%" PRIu64, mt_dbg_id(kv_A(n->intersect, i)));
2517    }
2518    GA_PUT("},");
2519  }
2520  if (n->level) {
2521    mt_inspect_node(b, ga, keys, n->ptr[0], off);
2522  }
2523  for (int i = 0; i < n->n; i++) {
2524    MTPos p = n->key[i].pos;
2525    unrelative(off, &p);
2526    GA_PRINT("%d/%d", p.row, p.col);
2527    if (keys) {
2528      MTKey key = n->key[i];
2529      GA_PUT(":");
2530      if (mt_start(key)) {
2531        GA_PUT("<");
2532      }
2533      // GA_PRINT("%"PRIu64, mt_lookup_id(key.ns, key.id, false));
2534      GA_PRINT("%" PRIu32, key.id);
2535      if (mt_end(key)) {
2536        GA_PUT(">");
2537      }
2538    }
2539    if (n->level) {
2540      mt_inspect_node(b, ga, keys, n->ptr[i + 1], p);
2541    } else {
2542      ga_concat(ga, ",");
2543    }
2544  }
2545  ga_concat(ga, "]");
2546}
2547
2548static void mt_inspect_dotfile_node(MarkTree *b, garray_T *ga, MTNode *n, MTPos off, char *parent)
2549{
2550  static char buf[1024];
2551  char namebuf[64];
2552  if (parent != NULL) {
2553    snprintf(namebuf, sizeof namebuf, "%s_%c%d", parent, 'a' + n->level, n->p_idx);
2554  } else {
2555    snprintf(namebuf, sizeof namebuf, "MTNode");
2556  }
2557
2558  GA_PRINT("  %s[shape=plaintext, label=<\n", namebuf);
2559  GA_PUT("    <table border='0' cellborder='1' cellspacing='0'>\n");
2560  if (kv_size(n->intersect)) {
2561    GA_PUT("    <tr><td>");
2562    for (size_t i = 0; i < kv_size(n->intersect); i++) {
2563      if (i > 0) {
2564        GA_PUT(", ");
2565      }
2566      GA_PRINT("%" PRIu64, mt_dbg_id(kv_A(n->intersect, i)));
2567    }
2568    GA_PUT("</td></tr>\n");
2569  }
2570
2571  GA_PUT("    <tr><td>");
2572  for (int i = 0; i < n->n; i++) {
2573    MTKey k = n->key[i];
2574    if (i > 0) {
2575      GA_PUT(", ");
2576    }
2577    GA_PRINT("%d", k.id);
2578    if (mt_paired(k)) {
2579      GA_PUT(mt_end(k) ? "e" : "s");
2580    }
2581  }
2582  GA_PUT("</td></tr>\n");
2583  GA_PUT("    </table>\n");
2584  GA_PUT(">];\n");
2585  if (parent) {
2586    GA_PRINT("  %s -> %s\n", parent, namebuf);
2587  }
2588  if (n->level) {
2589    mt_inspect_dotfile_node(b, ga, n->ptr[0], off, namebuf);
2590  }
2591  for (int i = 0; i < n->n; i++) {
2592    MTPos p = n->key[i].pos;
2593    unrelative(off, &p);
2594    if (n->level) {
2595      mt_inspect_dotfile_node(b, ga, n->ptr[i + 1], p, namebuf);
2596    }
2597  }
2598}