robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
d51fa783d7
master
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{ 73return a .row < b .row || (a .row == b .row && a .col <=b .col ); 74} 75 76static bool pos_less (MTPos a ,MTPos b ) 77{ 78return !pos_leq (b ,a ); 79} 80 81static void relative (MTPos base ,MTPos * val ) 82{ 83assert (pos_leq (base ,* val )); 84if (val -> row == base .row ) { 85val -> row = 0 ; 86val -> col -= base .col ; 87 }else { 88val -> row -= base .row ; 89 } 90} 91 92static void unrelative (MTPos base ,MTPos * val ) 93{ 94if (val -> row == 0 ) { 95val -> row = base .row ; 96val -> col += base .col ; 97 }else { 98val -> row += base .row ; 99 } 100} 101 102static void compose (MTPos * base ,MTPos val ) 103{ 104if (val .row == 0 ) { 105base -> col += val .col ; 106 }else { 107base -> row += val .row ; 108base -> 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{ 119int cmp = mt_generic_cmp (a .pos .row ,b .pos .row ); 120if (cmp != 0 ) { 121return cmp ; 122 } 123cmp = mt_generic_cmp (a .pos .col ,b .pos .col ); 124if (cmp != 0 ) { 125return cmp ; 126 } 127 128// TODO(bfredl): MT_FLAG_REAL could go away if we fix marktree_getp_aux for real 129const uint16_t cmp_mask = MT_FLAG_RIGHT_GRAVITY |MT_FLAG_END |MT_FLAG_REAL |MT_FLAG_LAST ; 130return 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{ 138bool dummy_match ; 139bool * m = match ?match :& dummy_match ; 140 141int begin = 0 ; 142int end = x -> n ; 143if (x -> n == 0 ) { 144* m = false; 145return -1 ; 146 } 147while (begin < end ) { 148int mid = (begin + end ) >>1 ; 149if (key_cmp (x -> key [mid ],k )< 0 ) { 150begin = mid + 1 ; 151 }else { 152end = mid ; 153 } 154 } 155if (begin == x -> n ) { 156* m = false; 157return x -> n - 1 ; 158 } 159if (!(* m = (key_cmp (k ,x -> key [begin ])== 0 ))) { 160begin -- ; 161 } 162return begin ; 163} 164 165static inline void refkey (MarkTree * b ,MTNode * x ,int i ) 166{ 167pmap_put (uint64_t )(b -> id2node ,mt_lookup_key (x -> key [i ]),x ); 168} 169 170static MTNode * id2node (MarkTree * b ,uint64_t id ) 171{ 172return 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{ 183MTNode * y = x -> ptr [i ]; 184MTNode * z = marktree_alloc_node (b ,y -> level ); 185z -> level = y -> level ; 186z -> 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). 191uint64_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) 194kvi_copy (z -> intersect ,y -> intersect ); 195 196if (!y -> level ) { 197uint64_t pi = pseudo_index (y ,0 );// note: sloppy pseudo-index 198for (int j = 0 ;j < T ;j ++ ) { 199MTKey k = y -> key [j ]; 200uint64_t pi_end = pseudo_index_for_id (b ,mt_lookup_id (k .ns ,k .id , true), true); 201if (mt_start (k )&& pi_end > pi && mt_lookup_key (k )!= last_start ) { 202intersect_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 207for (int j = T - 1 ;j < (T * 2 )- 1 ;j ++ ) { 208MTKey k = y -> key [j ]; 209uint64_t pi_start = pseudo_index_for_id (b ,mt_lookup_id (k .ns ,k .id , false), true); 210if (mt_end (k )&& pi_start > 0 && pi_start < pi ) { 211intersect_node (b ,y ,mt_lookup_id (k .ns ,k .id , false)); 212 } 213 } 214 } 215 216memcpy (z -> key ,& y -> key [T ],sizeof (MTKey )* (T - 1 )); 217for (int j = 0 ;j < T - 1 ;j ++ ) { 218refkey (b ,z ,j ); 219 } 220if (y -> level ) { 221memcpy (z -> ptr ,& y -> ptr [T ],sizeof (MTNode * )* T ); 222memcpy (z -> meta ,& y -> meta [T ],sizeof (z -> meta [0 ])* T ); 223for (int j = 0 ;j < T ;j ++ ) { 224z -> ptr [j ]-> parent = z ; 225z -> ptr [j ]-> p_idx = (int16_t )j ; 226 } 227 } 228y -> n = T - 1 ; 229memmove (& x -> ptr [i + 2 ],& x -> ptr [i + 1 ],sizeof (MTNode * )* (size_t )(x -> n - i )); 230memmove (& x -> meta [i + 2 ],& x -> meta [i + 1 ],sizeof (x -> meta [0 ])* (size_t )(x -> n - i )); 231x -> ptr [i + 1 ]= z ; 232meta_describe_node (x -> meta [i + 1 ],z ); 233z -> parent = x ;// == y->parent 234for (int j = i + 1 ;j < x -> n + 2 ;j ++ ) { 235x -> ptr [j ]-> p_idx = (int16_t )j ; 236 } 237memmove (& x -> key [i + 1 ],& x -> key [i ],sizeof (MTKey )* (size_t )(x -> n - i )); 238 239// move key to internal layer: 240x -> key [i ]= y -> key [T - 1 ]; 241refkey (b ,x ,i ); 242x -> n ++ ; 243 244uint32_t meta_inc [kMTMetaCount ]; 245meta_describe_key (meta_inc ,x -> key [i ]); 246for (int m = 0 ;m < kMTMetaCount ;m ++ ) { 247// y used contain all of z and x->key[i], discount those 248x -> meta [i ][m ]-= (x -> meta [i + 1 ][m ]+ meta_inc [m ]); 249 } 250 251for (int j = 0 ;j < T - 1 ;j ++ ) { 252relative (x -> key [i ].pos ,& z -> key [j ].pos ); 253 } 254if (i > 0 ) { 255unrelative (x -> key [i - 1 ].pos ,& x -> key [i ].pos ); 256 } 257 258if (y -> level ) { 259bubble_up (y ); 260bubble_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 271int i = marktree_getp_aux (x ,k ,NULL )+ 1 ; 272if (x -> level == 0 ) { 273if (i != x -> n ) { 274memmove (& x -> key [i + 1 ],& x -> key [i ], 275 (size_t )(x -> n - i )* sizeof (MTKey )); 276 } 277x -> key [i ]= k ; 278refkey (b ,x ,i ); 279x -> n ++ ; 280 }else { 281if (x -> ptr [i ]-> n == 2 * T - 1 ) { 282split_node (b ,x ,i ,k ); 283if (key_cmp (k ,x -> key [i ])> 0 ) { 284i ++ ; 285 } 286 } 287if (i > 0 ) { 288relative (x -> key [i - 1 ].pos ,& k .pos ); 289 } 290marktree_putp_aux (b ,x -> ptr [i ],k ,meta_inc ); 291for (int m = 0 ;m < kMTMetaCount ;m ++ ) { 292x -> 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{ 299assert (!(key .flags & ~(MT_FLAG_EXTERNAL_MASK |MT_FLAG_RIGHT_GRAVITY ))); 300if (end_row >=0 ) { 301key .flags |=MT_FLAG_PAIRED ; 302 } 303 304marktree_put_key (b ,key ); 305 306if (end_row >=0 ) { 307MTKey end_key = key ; 308end_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 )); 311end_key .pos = (MTPos ){end_row ,end_col }; 312marktree_put_key (b ,end_key ); 313MarkTreeIter itr [1 ]= {0 }; 314MarkTreeIter end_itr [1 ]= {0 }; 315marktree_lookup (b ,mt_lookup_key (key ),itr ); 316marktree_lookup (b ,mt_lookup_key (end_key ),end_itr ); 317 318marktree_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{ 325for (size_t i = 0 ;i < kv_size (* x );i ++ ) { 326if (kv_A (* x ,i )== id ) { 327return true; 328 }else if (kv_A (* x ,i ) >=id ) { 329return false; 330 } 331 } 332return 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{ 340size_t lo = 0 ; 341size_t hi = kv_size (x -> intersect ); 342while (lo < hi ) { 343size_t mid = lo + (hi - lo ) /2 ; 344if (kv_A (x -> intersect ,mid )< id ) { 345lo = mid + 1 ; 346 }else { 347hi = mid ; 348 } 349 } 350return lo ; 351} 352 353static void intersect_node (MarkTree * b ,MTNode * x ,uint64_t id ) 354{ 355assert (!(id & MARKTREE_END_FLAG )); 356// Common case: ids arrive in ascending order, so the new key belongs at the end. 357if (kv_size (x -> intersect )== 0 || kv_A (x -> intersect ,kv_size (x -> intersect )- 1 )< id ) { 358kvi_push (x -> intersect ,id ); 359return ; 360 } 361size_t i = intersect_item_pos (x ,id ); 362kvi_pushp (x -> intersect ); 363memmove (& kv_A (x -> intersect ,i + 1 ),& kv_A (x -> intersect ,i ), 364 (kv_size (x -> intersect )- i - 1 )* sizeof (kv_A (x -> intersect ,0 ))); 365kv_A (x -> intersect ,i )= id ; 366} 367 368static void unintersect_node (MarkTree * b ,MTNode * x ,uint64_t id ,bool strict ) 369{ 370assert (!(id & MARKTREE_END_FLAG )); 371size_t i = intersect_item_pos (x ,id ); 372bool seen = i < kv_size (x -> intersect )&& kv_A (x -> intersect ,i )== id ; 373if (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. 379assert (seen ); 380#endif 381 } 382 383if (seen ) { 384if (i < kv_size (x -> intersect )- 1 ) { 385memmove (& kv_A (x -> intersect ,i ),& kv_A (x -> intersect ,i + 1 ), (kv_size (x -> intersect )- i - 1 )* 386sizeof (kv_A (x -> intersect ,i ))); 387 } 388kv_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 , 395bool delete ) 396{ 397int 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) 399for (;lvl < maxlvl ;lvl ++ ) { 400if (itr -> s [lvl ].i > end_itr -> s [lvl ].i ) { 401return ;// empty range 402 }else if (itr -> s [lvl ].i < end_itr -> s [lvl ].i ) { 403break ;// work to do 404 } 405 } 406if (lvl == maxlvl && iat (itr ,lvl ,1 )> iat (end_itr ,lvl ,0 )) { 407return ;// empty range 408 } 409 410while (itr -> x ) { 411bool skip = false; 412if (itr -> x == end_itr -> x ) { 413if (itr -> x -> level == 0 || itr -> i >=end_itr -> i ) { 414break ; 415 }else { 416skip = true; 417 } 418 }else if (itr -> lvl > lvl ) { 419skip = true; 420 }else { 421if (iat (itr ,lvl ,1 )< iat (end_itr ,lvl ,1 )) { 422skip = true; 423 }else { 424lvl ++ ; 425 } 426 } 427 428if (skip ) { 429if (itr -> x -> level ) { 430MTNode * x = itr -> x -> ptr [itr -> i + 1 ]; 431if (delete ) { 432unintersect_node (b ,x ,id , true); 433 }else { 434intersect_node (b ,x ,id ); 435 } 436 } 437 } 438marktree_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{ 445MTNode * x = xcalloc (1 ,internal ?ILEN :sizeof (MTNode )); 446kvi_init (x -> intersect ); 447b -> n_nodes ++ ; 448return x ; 449} 450 451// really meta_inc[kMTMetaCount] 452static void meta_describe_key_inc (uint32_t * meta_inc ,MTKey * k ) 453{ 454if (!mt_end (* k )&& !mt_invalid (* k )) { 455meta_inc [kMTMetaInline ]+= (k -> flags & MT_FLAG_DECOR_VIRT_TEXT_INLINE ) ?1 :0 ; 456meta_inc [kMTMetaLines ]+= (k -> flags & MT_FLAG_DECOR_VIRT_LINES ) ?1 :0 ; 457meta_inc [kMTMetaSignHL ]+= (k -> flags & MT_FLAG_DECOR_SIGNHL ) ?1 :0 ; 458meta_inc [kMTMetaSignText ]+= (k -> flags & MT_FLAG_DECOR_SIGNTEXT ) ?1 :0 ; 459meta_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{ 465memset (meta_inc ,0 ,kMTMetaCount * sizeof (* meta_inc )); 466meta_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{ 472memset (meta_node ,0 ,kMTMetaCount * sizeof (meta_node [0 ])); 473for (int i = 0 ;i < x -> n ;i ++ ) { 474meta_describe_key_inc (meta_node ,& x -> key [i ]); 475 } 476if (x -> level ) { 477for (int i = 0 ;i < x -> n + 1 ;i ++ ) { 478for (int m = 0 ;m < kMTMetaCount ;m ++ ) { 479meta_node [m ]+= x -> meta [i ][m ]; 480 } 481 } 482 } 483} 484 485static bool meta_has (const uint32_t * meta_count ,MetaFilter meta_filter ) 486{ 487uint32_t count = 0 ; 488for (int m = 0 ;m < kMTMetaCount ;m ++ ) { 489count += meta_count [m ]& meta_filter [m ]; 490 } 491return count > 0 ; 492} 493 494void marktree_put_key (MarkTree * b ,MTKey k ) 495{ 496k .flags |=MT_FLAG_REAL ;// let's be real. 497if (!b -> root ) { 498b -> root = marktree_alloc_node (b , true); 499 } 500MTNode * r = b -> root ; 501if (r -> n == 2 * T - 1 ) { 502MTNode * s = marktree_alloc_node (b , true); 503b -> root = s ;s -> level = r -> level + 1 ;s -> n = 0 ; 504s -> ptr [0 ]= r ; 505for (int m = 0 ;m < kMTMetaCount ;m ++ ) { 506s -> meta [0 ][m ]= b -> meta_root [m ]; 507 } 508r -> parent = s ; 509r -> p_idx = 0 ; 510split_node (b ,s ,0 ,k ); 511r = s ; 512 } 513 514uint32_t meta_inc [kMTMetaCount ]; 515meta_describe_key (meta_inc ,k ); 516marktree_putp_aux (b ,r ,k ,meta_inc ); 517for (int m = 0 ;m < kMTMetaCount ;m ++ ) { 518b -> meta_root [m ]+= meta_inc [m ]; 519 } 520b -> 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{ 549int adjustment = 0 ; 550 551MTNode * cur = itr -> x ; 552int curi = itr -> i ; 553uint64_t id = mt_lookup_key (cur -> key [curi ]); 554 555MTKey raw = rawkey (itr ); 556uint64_t other = 0 ; 557if (mt_paired (raw )&& !(raw .flags & MT_FLAG_ORPHANED )) { 558other = mt_lookup_key_side (raw , !mt_end (raw )); 559 560MarkTreeIter other_itr [1 ]; 561marktree_lookup (b ,other ,other_itr ); 562rawkey (other_itr ).flags |=MT_FLAG_ORPHANED ; 563// Remove intersect markers. NB: must match exactly! 564if (mt_start (raw )) { 565MarkTreeIter this_itr [1 ]= {* itr };// mutated copy 566marktree_intersect_pair (b ,id ,this_itr ,other_itr , true); 567 }else { 568marktree_intersect_pair (b ,other ,other_itr ,itr , true); 569 } 570 } 571 572// 2. 573if (itr -> x -> level ) { 574if (rev ) { 575abort (); 576 }else { 577// steal previous node 578marktree_itr_prev (b ,itr ); 579adjustment = -1 ; 580 } 581 } 582 583// 3. 584MTNode * x = itr -> x ; 585assert (x -> level == 0 ); 586MTKey intkey = x -> key [itr -> i ]; 587 588uint32_t meta_inc [kMTMetaCount ]; 589meta_describe_key (meta_inc ,intkey ); 590if (x -> n > itr -> i + 1 ) { 591memmove (& x -> key [itr -> i ],& x -> key [itr -> i + 1 ], 592sizeof (MTKey )* (size_t )(x -> n - itr -> i - 1 )); 593 } 594x -> n -- ; 595 596b -> n_keys -- ; 597pmap_del (uint64_t )(b -> id2node ,id ,NULL ); 598 599// 4. 600// if (adjustment == 1) { 601// abort(); 602// } 603if (adjustment == -1 ) { 604int ilvl = itr -> lvl - 1 ; 605MTNode * lnode = x ; 606uint64_t start_id = 0 ; 607bool did_bubble = false; 608if (mt_end (intkey )) { 609start_id = mt_lookup_key_side (intkey , false); 610 } 611do { 612MTNode * p = lnode -> parent ; 613if (ilvl < 0 ) { 614abort (); 615 } 616int i = itr -> s [ilvl ].i ; 617assert (p -> ptr [i ]== lnode ); 618if (i > 0 ) { 619unrelative (p -> key [i - 1 ].pos ,& intkey .pos ); 620 } 621 622if (p != cur && start_id ) { 623if (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) 626int last = (lnode != x ) ?1 :0 ; 627for (int k = 0 ;k < p -> n + last ;k ++ ) {// one less as p->ptr[n] is the last 628unintersect_node (b ,p -> ptr [k ],start_id , true); 629 } 630intersect_node (b ,p ,start_id ); 631did_bubble = true; 632 } 633 } 634 635for (int m = 0 ;m < kMTMetaCount ;m ++ ) { 636p -> meta [lnode -> p_idx ][m ]-= meta_inc [m ]; 637 } 638 639lnode = p ; 640ilvl -- ; 641 }while (lnode != cur ); 642 643MTKey deleted = cur -> key [curi ]; 644meta_describe_key (meta_inc ,deleted ); 645cur -> key [curi ]= intkey ; 646refkey (b ,cur ,curi ); 647// if `did_bubble` then we already added `start_id` to some parent 648if (mt_end (cur -> key [curi ])&& !did_bubble ) { 649uint64_t pi = pseudo_index (x ,0 );// note: sloppy pseudo-index 650uint64_t pi_start = pseudo_index_for_id (b ,start_id , true); 651if (pi_start > 0 && pi_start < pi ) { 652intersect_node (b ,x ,start_id ); 653 } 654 } 655 656relative (intkey .pos ,& deleted .pos ); 657MTNode * y = cur -> ptr [curi + 1 ]; 658if (deleted .pos .row || deleted .pos .col ) { 659while (y ) { 660for (int k = 0 ;k < y -> n ;k ++ ) { 661unrelative (deleted .pos ,& y -> key [k ].pos ); 662 } 663y = y -> level ?y -> ptr [0 ] :NULL ; 664 } 665 } 666itr -> i -- ; 667 } 668 669MTNode * lnode = cur ; 670while (lnode -> parent ) { 671uint32_t * meta_p = lnode -> parent -> meta [lnode -> p_idx ]; 672for (int m = 0 ;m < kMTMetaCount ;m ++ ) { 673meta_p [m ]-= meta_inc [m ]; 674 } 675 676lnode = lnode -> parent ; 677 } 678for (int m = 0 ;m < kMTMetaCount ;m ++ ) { 679assert (b -> meta_root [m ] >=meta_inc [m ]); 680b -> meta_root [m ]-= meta_inc [m ]; 681 } 682 683// 5. 684bool itr_dirty = false; 685int rlvl = itr -> lvl - 1 ; 686int * lasti = & itr -> i ; 687MTPos ppos = itr -> pos ; 688while (x != b -> root ) { 689assert (rlvl >=0 ); 690MTNode * p = x -> parent ; 691if (x -> n >=T - 1 ) { 692// we are done, if this node is fine the rest of the tree will be 693break ; 694 } 695int pi = itr -> s [rlvl ].i ; 696assert (p -> ptr [pi ]== x ); 697if (pi > 0 ) { 698ppos .row -= p -> key [pi - 1 ].pos .row ; 699ppos .col = itr -> s [rlvl ].oldcol ; 700 } 701// ppos is now the pos of p 702 703if (pi > 0 && p -> ptr [pi - 1 ]-> n > T - 1 ) { 704* lasti += 1 ; 705itr_dirty = true; 706// steal one key from the left neighbour 707pivot_right (b ,ppos ,p ,pi - 1 ); 708break ; 709 }else if (pi < p -> n && p -> ptr [pi + 1 ]-> n > T - 1 ) { 710// steal one key from right neighbour 711pivot_left (b ,ppos ,p ,pi ); 712break ; 713 }else if (pi > 0 ) { 714assert (p -> ptr [pi - 1 ]-> n == T - 1 ); 715// merge with left neighbour 716* lasti += T ; 717x = merge_node (b ,p ,pi - 1 ); 718if (lasti == & itr -> i ) { 719// TRICKY: we merged the node the iterator was on 720itr -> x = x ; 721 } 722itr -> s [rlvl ].i -- ; 723itr_dirty = true; 724 }else { 725assert (pi < p -> n && p -> ptr [pi + 1 ]-> n == T - 1 ); 726merge_node (b ,p ,pi ); 727// no iter adjustment needed 728 } 729lasti = & itr -> s [rlvl ].i ; 730rlvl -- ; 731x = p ; 732 } 733 734// 6. 735if (b -> root -> n == 0 ) { 736if (itr -> lvl > 0 ) { 737memmove (itr -> s ,itr -> s + 1 , (size_t )(itr -> lvl - 1 )* sizeof (* itr -> s )); 738itr -> lvl -- ; 739 } 740if (b -> root -> level ) { 741MTNode * oldroot = b -> root ; 742b -> root = b -> root -> ptr [0 ]; 743for (int m = 0 ;m < kMTMetaCount ;m ++ ) { 744assert (b -> meta_root [m ]== oldroot -> meta [0 ][m ]); 745 } 746 747b -> root -> parent = NULL ; 748marktree_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 752itr -> x = NULL ; 753 } 754 } 755 756if (itr -> x && itr_dirty ) { 757marktree_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// } 765if (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. 769marktree_itr_next (b ,itr ); 770marktree_itr_next (b ,itr ); 771 }else { 772if (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. 775assert (itr -> x -> level == 0 ); 776marktree_itr_next (b ,itr ); 777 } 778 } 779 780return other ; 781} 782 783void marktree_revise_meta (MarkTree * b ,MarkTreeIter * itr ,MTKey old_key ) 784{ 785uint32_t meta_old [kMTMetaCount ],meta_new [kMTMetaCount ]; 786meta_describe_key (meta_old ,old_key ); 787meta_describe_key (meta_new ,rawkey (itr )); 788 789if (!memcmp (meta_old ,meta_new ,sizeof (meta_old ))) { 790return ; 791 } 792 793MTNode * lnode = itr -> x ; 794while (lnode -> parent ) { 795uint32_t * meta_p = lnode -> parent -> meta [lnode -> p_idx ]; 796for (int m = 0 ;m < kMTMetaCount ;m ++ ) { 797meta_p [m ]+= meta_new [m ]- meta_old [m ]; 798 } 799 800lnode = lnode -> parent ; 801 } 802 803for (int m = 0 ;m < kMTMetaCount ;m ++ ) { 804b -> 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 * restrictm ,Intersection * restrictx , 811Intersection * restricty ) 812{ 813size_t xi = 0 ; 814size_t yi = 0 ; 815size_t xn = 0 ; 816size_t yn = 0 ; 817while (xi < kv_size (* x )&& yi < kv_size (* y )) { 818if (kv_A (* x ,xi )== kv_A (* y ,yi )) { 819// TODO(bfredl): kvi_pushp is actually quite complex, break out kvi_resize() to a function? 820kvi_push (* m ,kv_A (* x ,xi )); 821xi ++ ; 822yi ++ ; 823 }else if (kv_A (* x ,xi )< kv_A (* y ,yi )) { 824kv_A (* x ,xn ++ )= kv_A (* x ,xi ++ ); 825 }else { 826kv_A (* y ,yn ++ )= kv_A (* y ,yi ++ ); 827 } 828 } 829 830if (xi < kv_size (* x )) { 831memmove (& kv_A (* x ,xn ),& kv_A (* x ,xi ),sizeof (kv_A (* x ,xn ))* (kv_size (* x )- xi )); 832xn += kv_size (* x )- xi ; 833 } 834if (yi < kv_size (* y )) { 835memmove (& kv_A (* y ,yn ),& kv_A (* y ,yi ),sizeof (kv_A (* y ,yn ))* (kv_size (* y )- yi )); 836yn += kv_size (* y )- yi ; 837 } 838 839kv_size (* x )= xn ; 840kv_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 * restrictx ,Intersection * restricty , 846Intersection * restrictw ,Intersection * restrictd ) 847{ 848size_t wi = 0 ; 849size_t yi = 0 ; 850size_t wn = 0 ; 851size_t yn = 0 ; 852size_t xi = 0 ; 853while (wi < kv_size (* w )|| xi < kv_size (* x )) { 854if (wi < kv_size (* w )&& (xi >=kv_size (* x )|| kv_A (* x ,xi ) >=kv_A (* w ,wi ))) { 855if (xi < kv_size (* x )&& kv_A (* x ,xi )== kv_A (* w ,wi )) { 856xi ++ ; 857 } 858// now w < x strictly 859while (yi < kv_size (* y )&& kv_A (* y ,yi )< kv_A (* w ,wi )) { 860kvi_push (* d ,kv_A (* y ,yi )); 861yi ++ ; 862 } 863if (yi < kv_size (* y )&& kv_A (* y ,yi )== kv_A (* w ,wi )) { 864kv_A (* y ,yn ++ )= kv_A (* y ,yi ++ ); 865wi ++ ; 866 }else { 867kv_A (* w ,wn ++ )= kv_A (* w ,wi ++ ); 868 } 869 }else { 870// x < w strictly 871while (yi < kv_size (* y )&& kv_A (* y ,yi )< kv_A (* x ,xi )) { 872kvi_push (* d ,kv_A (* y ,yi )); 873yi ++ ; 874 } 875if (yi < kv_size (* y )&& kv_A (* y ,yi )== kv_A (* x ,xi )) { 876kv_A (* y ,yn ++ )= kv_A (* y ,yi ++ ); 877xi ++ ; 878 }else { 879// add kv_A(x, xi) at kv_A(w, wn), pushing up wi if wi == wn 880if (wi == wn ) { 881size_t n = kv_size (* w )- wn ; 882kvi_pushp (* w ); 883if (n > 0 ) { 884memmove (& kv_A (* w ,wn + 1 ),& kv_A (* w ,wn ),n * sizeof (kv_A (* w ,0 ))); 885 } 886kv_A (* w ,wi )= kv_A (* x ,xi ); 887wn ++ ; 888wi ++ ;// no need to consider the added element again 889 }else { 890assert (wn < wi ); 891kv_A (* w ,wn ++ )= kv_A (* x ,xi ); 892 } 893xi ++ ; 894 } 895 } 896 } 897if (yi < kv_size (* y )) { 898// move remaining items to d 899size_t n = kv_size (* y )- yi ;// at least one 900kvi_ensure_more_space (* d ,n ); 901memcpy (& kv_A (* d ,kv_size (* d )),& kv_A (* y ,yi ),n * sizeof (kv_A (* d ,0 ))); 902kv_size (* d )+= n ; 903 } 904kv_size (* w )= wn ; 905kv_size (* y )= yn ; 906} 907 908bool intersect_mov_test (const uint64_t * x ,size_t nx ,const uint64_t * y ,size_t ny , 909const uint64_t * win ,size_t nwin ,uint64_t * wout ,size_t * nwout , 910uint64_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) 914Intersection xi = { .items = (uint64_t * )x , .size = nx }; 915Intersection yi = { .items = (uint64_t * )y , .size = ny }; 916 917Intersection w ; 918kvi_init (w ); 919for (size_t i = 0 ;i < nwin ;i ++ ) { 920kvi_push (w ,win [i ]); 921 } 922Intersection d ; 923kvi_init (d ); 924 925intersect_mov (& xi ,& yi ,& w ,& d ); 926 927if (w .size > * nwout || d .size > * ndout ) { 928return false; 929 } 930 931memcpy (wout ,w .items ,sizeof (w .items [0 ])* w .size ); 932* nwout = w .size ; 933 934memcpy (dout ,d .items ,sizeof (d .items [0 ])* d .size ); 935* ndout = d .size ; 936 937return true; 938} 939 940/// intersection: i = x & y 941static void intersect_common (Intersection * i ,Intersection * x ,Intersection * y ) 942{ 943size_t xi = 0 ; 944size_t yi = 0 ; 945while (xi < kv_size (* x )&& yi < kv_size (* y )) { 946if (kv_A (* x ,xi )== kv_A (* y ,yi )) { 947kvi_push (* i ,kv_A (* x ,xi )); 948xi ++ ; 949yi ++ ; 950 }else if (kv_A (* x ,xi )< kv_A (* y ,yi )) { 951xi ++ ; 952 }else { 953yi ++ ; 954 } 955 } 956} 957 958// inplace union: x |= y 959static void intersect_add (Intersection * x ,Intersection * y ) 960{ 961size_t xi = 0 ; 962size_t yi = 0 ; 963while (xi < kv_size (* x )&& yi < kv_size (* y )) { 964if (kv_A (* x ,xi )== kv_A (* y ,yi )) { 965xi ++ ; 966yi ++ ; 967 }else if (kv_A (* y ,yi )< kv_A (* x ,xi )) { 968size_t n = kv_size (* x )- xi ;// at least one 969kvi_pushp (* x ); 970memmove (& kv_A (* x ,xi + 1 ),& kv_A (* x ,xi ),n * sizeof (kv_A (* x ,0 ))); 971kv_A (* x ,xi )= kv_A (* y ,yi ); 972xi ++ ;// newly added element 973yi ++ ; 974 }else { 975xi ++ ; 976 } 977 } 978if (yi < kv_size (* y )) { 979size_t n = kv_size (* y )- yi ;// at least one 980kvi_ensure_more_space (* x ,n ); 981memcpy (& kv_A (* x ,kv_size (* x )),& kv_A (* y ,yi ),n * sizeof (kv_A (* x ,0 ))); 982kv_size (* x )+= n ; 983 } 984} 985 986// inplace asymmetric difference: x &= ~y 987static void intersect_sub (Intersection * restrictx ,Intersection * restricty ) 988{ 989size_t xi = 0 ; 990size_t yi = 0 ; 991size_t xn = 0 ; 992while (xi < kv_size (* x )&& yi < kv_size (* y )) { 993if (kv_A (* x ,xi )== kv_A (* y ,yi )) { 994xi ++ ; 995yi ++ ; 996 }else if (kv_A (* x ,xi )< kv_A (* y ,yi )) { 997kv_A (* x ,xn ++ )= kv_A (* x ,xi ++ ); 998 }else { 999yi ++ ; 1000 } 1001 } 1002if (xi < kv_size (* x )) { 1003size_t n = kv_size (* x )- xi ; 1004if (xn < xi ) {// otherwise xn == xi 1005memmove (& kv_A (* x ,xn ),& kv_A (* x ,xi ),n * sizeof (kv_A (* x ,0 ))); 1006 } 1007xn += n ; 1008 } 1009kv_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{ 1018Intersection xi ; 1019kvi_init (xi ); 1020// due to invariants, the largest subset of _all_ subnodes is the intersection 1021// between the first and the last 1022intersect_common (& xi ,& x -> ptr [0 ]-> intersect ,& x -> ptr [x -> n ]-> intersect ); 1023if (kv_size (xi )) { 1024for (int i = 0 ;i < x -> n + 1 ;i ++ ) { 1025intersect_sub (& x -> ptr [i ]-> intersect ,& xi ); 1026 } 1027intersect_add (& x -> intersect ,& xi ); 1028 } 1029kvi_destroy (xi ); 1030} 1031 1032static MTNode * merge_node (MarkTree * b ,MTNode * p ,int i ) 1033{ 1034MTNode * x = p -> ptr [i ]; 1035MTNode * y = p -> ptr [i + 1 ]; 1036Intersection mi ; 1037kvi_init (mi ); 1038 1039intersect_merge (& mi ,& x -> intersect ,& y -> intersect ); 1040 1041x -> key [x -> n ]= p -> key [i ]; 1042refkey (b ,x ,x -> n ); 1043if (i > 0 ) { 1044relative (p -> key [i - 1 ].pos ,& x -> key [x -> n ].pos ); 1045 } 1046 1047uint32_t meta_inc [kMTMetaCount ]; 1048meta_describe_key (meta_inc ,x -> key [x -> n ]); 1049 1050memmove (& x -> key [x -> n + 1 ],y -> key , (size_t )y -> n * sizeof (MTKey )); 1051for (int k = 0 ;k < y -> n ;k ++ ) { 1052refkey (b ,x ,x -> n + 1 + k ); 1053unrelative (x -> key [x -> n ].pos ,& x -> key [x -> n + 1 + k ].pos ); 1054 } 1055if (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 1058memmove (& x -> ptr [x -> n + 1 ],y -> ptr , ((size_t )y -> n + 1 )* sizeof (MTNode * )); 1059memmove (& x -> meta [x -> n + 1 ],y -> meta , ((size_t )y -> n + 1 )* sizeof (y -> meta [0 ])); 1060for (int k = 0 ;k < x -> n + 1 ;k ++ ) { 1061// TODO(bfredl): dedicated impl for "Z |= Y" 1062for (size_t idx = 0 ;idx < kv_size (x -> intersect );idx ++ ) { 1063intersect_node (b ,x -> ptr [k ],kv_A (x -> intersect ,idx )); 1064 } 1065 } 1066for (int ky = 0 ;ky < y -> n + 1 ;ky ++ ) { 1067int k = x -> n + ky + 1 ; 1068// nodes that used to be in y, now the second half of x 1069x -> ptr [k ]-> parent = x ; 1070x -> ptr [k ]-> p_idx = (int16_t )k ; 1071// TODO(bfredl): dedicated impl for "Z |= X" 1072for (size_t idx = 0 ;idx < kv_size (y -> intersect );idx ++ ) { 1073intersect_node (b ,x -> ptr [k ],kv_A (y -> intersect ,idx )); 1074 } 1075 } 1076 } 1077x -> n += y -> n + 1 ; 1078for (int m = 0 ;m < kMTMetaCount ;m ++ ) { 1079// x now contains everything of y plus old p->key[i] 1080p -> meta [i ][m ]+= (p -> meta [i + 1 ][m ]+ meta_inc [m ]); 1081 } 1082 1083memmove (& p -> key [i ],& p -> key [i + 1 ], (size_t )(p -> n - i - 1 )* sizeof (MTKey )); 1084memmove (& p -> ptr [i + 1 ],& p -> ptr [i + 2 ], (size_t )(p -> n - i - 1 )* sizeof (MTKey * )); 1085memmove (& p -> meta [i + 1 ],& p -> meta [i + 2 ], (size_t )(p -> n - i - 1 )* sizeof (p -> meta [0 ])); 1086for (int j = i + 1 ;j < p -> n ;j ++ ) {// note: one has been deleted 1087p -> ptr [j ]-> p_idx = (int16_t )j ; 1088 } 1089p -> n -- ; 1090marktree_free_node (b ,y ); 1091 1092kvi_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 1096kvi_move (& x -> intersect ,& mi ); 1097 1098return 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{ 1105dest -> size = src -> size ; 1106dest -> capacity = src -> capacity ; 1107if (src -> items == src -> init_array ) { 1108memcpy (dest -> init_array ,src -> init_array ,src -> size * sizeof (* src -> init_array )); 1109dest -> items = dest -> init_array ; 1110 }else { 1111dest -> 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{ 1121MTNode * x = p -> ptr [i ]; 1122MTNode * y = p -> ptr [i + 1 ]; 1123memmove (& y -> key [1 ],y -> key , (size_t )y -> n * sizeof (MTKey )); 1124if (y -> level ) { 1125memmove (& y -> ptr [1 ],y -> ptr , ((size_t )y -> n + 1 )* sizeof (MTNode * )); 1126memmove (& y -> meta [1 ],y -> meta , ((size_t )y -> n + 1 )* sizeof (y -> meta [0 ])); 1127for (int j = 1 ;j < y -> n + 2 ;j ++ ) { 1128y -> ptr [j ]-> p_idx = (int16_t )j ; 1129 } 1130 } 1131 1132y -> key [0 ]= p -> key [i ]; 1133refkey (b ,y ,0 ); 1134p -> key [i ]= x -> key [x -> n - 1 ]; 1135refkey (b ,p ,i ); 1136 1137uint32_t meta_inc_y [kMTMetaCount ]; 1138meta_describe_key (meta_inc_y ,y -> key [0 ]); 1139uint32_t meta_inc_x [kMTMetaCount ]; 1140meta_describe_key (meta_inc_x ,p -> key [i ]); 1141 1142for (int m = 0 ;m < kMTMetaCount ;m ++ ) { 1143p -> meta [i + 1 ][m ]+= meta_inc_y [m ]; 1144p -> meta [i ][m ]-= meta_inc_x [m ]; 1145 } 1146 1147if (x -> level ) { 1148y -> ptr [0 ]= x -> ptr [x -> n ]; 1149memcpy (y -> meta [0 ],x -> meta [x -> n ],sizeof (y -> meta [0 ])); 1150for (int m = 0 ;m < kMTMetaCount ;m ++ ) { 1151p -> meta [i + 1 ][m ]+= y -> meta [0 ][m ]; 1152p -> meta [i ][m ]-= y -> meta [0 ][m ]; 1153 } 1154y -> ptr [0 ]-> parent = y ; 1155y -> ptr [0 ]-> p_idx = 0 ; 1156 } 1157x -> n -- ; 1158y -> n ++ ; 1159if (i > 0 ) { 1160unrelative (p -> key [i - 1 ].pos ,& p -> key [i ].pos ); 1161 } 1162relative (p -> key [i ].pos ,& y -> key [0 ].pos ); 1163for (int k = 1 ;k < y -> n ;k ++ ) { 1164unrelative (y -> key [0 ].pos ,& y -> key [k ].pos ); 1165 } 1166 1167// repair intersections of x 1168if (x -> level ) { 1169// handle y and first new y->ptr[0] 1170Intersection d ; 1171kvi_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) 1176intersect_mov (& x -> intersect ,& y -> intersect ,& y -> ptr [0 ]-> intersect ,& d ); 1177if (kv_size (d )) { 1178for (int yi = 1 ;yi < y -> n + 1 ;yi ++ ) { 1179intersect_add (& y -> ptr [yi ]-> intersect ,& d ); 1180 } 1181 } 1182kvi_destroy (d ); 1183 1184bubble_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 1187if (mt_end (p -> key [i ])) { 1188uint64_t pi = pseudo_index (x ,0 );// note: sloppy pseudo-index 1189uint64_t start_id = mt_lookup_key_side (p -> key [i ], false); 1190uint64_t pi_start = pseudo_index_for_id (b ,start_id , true); 1191if (pi_start > 0 && pi_start < pi ) { 1192intersect_node (b ,x ,start_id ); 1193 } 1194 } 1195 1196if (mt_start (y -> key [0 ])) { 1197// no need for a check, just delet it if it was there 1198unintersect_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{ 1205MTNode * x = p -> ptr [i ]; 1206MTNode * 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. 1210for (int k = 1 ;k < y -> n ;k ++ ) { 1211relative (y -> key [0 ].pos ,& y -> key [k ].pos ); 1212 } 1213unrelative (p -> key [i ].pos ,& y -> key [0 ].pos ); 1214if (i > 0 ) { 1215relative (p -> key [i - 1 ].pos ,& p -> key [i ].pos ); 1216 } 1217 1218x -> key [x -> n ]= p -> key [i ]; 1219refkey (b ,x ,x -> n ); 1220p -> key [i ]= y -> key [0 ]; 1221refkey (b ,p ,i ); 1222 1223uint32_t meta_inc_x [kMTMetaCount ]; 1224meta_describe_key (meta_inc_x ,x -> key [x -> n ]); 1225uint32_t meta_inc_y [kMTMetaCount ]; 1226meta_describe_key (meta_inc_y ,p -> key [i ]); 1227for (int m = 0 ;m < kMTMetaCount ;m ++ ) { 1228p -> meta [i ][m ]+= meta_inc_x [m ]; 1229p -> meta [i + 1 ][m ]-= meta_inc_y [m ]; 1230 } 1231 1232if (x -> level ) { 1233x -> ptr [x -> n + 1 ]= y -> ptr [0 ]; 1234memcpy (x -> meta [x -> n + 1 ],y -> meta [0 ],sizeof (y -> meta [0 ])); 1235for (int m = 0 ;m < kMTMetaCount ;m ++ ) { 1236p -> meta [i + 1 ][m ]-= y -> meta [0 ][m ]; 1237p -> meta [i ][m ]+= y -> meta [0 ][m ]; 1238 } 1239x -> ptr [x -> n + 1 ]-> parent = x ; 1240x -> ptr [x -> n + 1 ]-> p_idx = (int16_t )(x -> n + 1 ); 1241 } 1242memmove (y -> key ,& y -> key [1 ], (size_t )(y -> n - 1 )* sizeof (MTKey )); 1243if (y -> level ) { 1244memmove (y -> ptr ,& y -> ptr [1 ], (size_t )y -> n * sizeof (MTNode * )); 1245memmove (y -> meta ,& y -> meta [1 ], (size_t )y -> n * sizeof (y -> meta [0 ])); 1246for (int j = 0 ;j < y -> n ;j ++ ) {// note: last item deleted 1247y -> ptr [j ]-> p_idx = (int16_t )j ; 1248 } 1249 } 1250x -> n ++ ; 1251y -> n -- ; 1252 1253// repair intersections of x,y 1254if (x -> level ) { 1255// handle y and first new y->ptr[0] 1256Intersection d ; 1257kvi_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) 1262intersect_mov (& y -> intersect ,& x -> intersect ,& x -> ptr [x -> n ]-> intersect ,& d ); 1263if (kv_size (d )) { 1264for (int xi = 0 ;xi < x -> n ;xi ++ ) {// ptr[x->n| deliberately skipped 1265intersect_add (& x -> ptr [xi ]-> intersect ,& d ); 1266 } 1267 } 1268kvi_destroy (d ); 1269 1270bubble_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 1273if (mt_start (p -> key [i ])) { 1274uint64_t pi = pseudo_index (y ,0 );// note: sloppy pseudo-index 1275 1276uint64_t end_id = mt_lookup_key_side (p -> key [i ], true); 1277uint64_t pi_end = pseudo_index_for_id (b ,end_id , true); 1278 1279if (pi_end > pi ) { 1280intersect_node (b ,y ,mt_lookup_key (p -> key [i ])); 1281 } 1282 } 1283 1284if (mt_end (x -> key [x -> n - 1 ])) { 1285// no need for a check, just delet it if it was there 1286unintersect_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{ 1294if (b -> root ) { 1295marktree_free_subtree (b ,b -> root ); 1296b -> root = NULL ; 1297 } 1298map_destroy (uint64_t ,b -> id2node ); 1299b -> n_keys = 0 ; 1300memset (b -> meta_root ,0 ,kMTMetaCount * sizeof (b -> meta_root [0 ])); 1301assert (b -> n_nodes == 0 ); 1302} 1303 1304void marktree_free_subtree (MarkTree * b ,MTNode * x ) 1305{ 1306if (x -> level ) { 1307for (int i = 0 ;i < x -> n + 1 ;i ++ ) { 1308marktree_free_subtree (b ,x -> ptr [i ]); 1309 } 1310 } 1311marktree_free_node (b ,x ); 1312} 1313 1314static void marktree_free_node (MarkTree * b ,MTNode * x ) 1315{ 1316kvi_destroy (x -> intersect ); 1317xfree (x ); 1318b -> n_nodes -- ; 1319} 1320 1321/// @param itr iterator is invalid after call 1322void marktree_move (MarkTree * b ,MarkTreeIter * itr ,int row ,int col ) 1323{ 1324MTKey key = rawkey (itr ); 1325MTNode * x = itr -> x ; 1326if (!x -> level ) { 1327bool internal = false; 1328MTPos newpos = MTPos (row ,col ); 1329if (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) 1332if (pos_less (itr -> pos ,newpos )) { 1333relative (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) 1337if (pos_less (newpos ,x -> key [x -> n - 1 ].pos )) { 1338internal = true; 1339 } 1340 } 1341 }else { 1342// tree is one node. newpos thus is already "relative" itr->pos 1343internal = true; 1344 } 1345 1346if (internal ) { 1347if (key .pos .row == newpos .row && key .pos .col == newpos .col ) { 1348return ; 1349 } 1350key .pos = newpos ; 1351bool match ; 1352// tricky: could minimize movement in either direction better 1353int new_i = marktree_getp_aux (x ,key ,& match ); 1354if (!match ) { 1355new_i ++ ; 1356 } 1357if (new_i == itr -> i ) { 1358x -> key [itr -> i ].pos = newpos ; 1359 }else if (new_i < itr -> i ) { 1360memmove (& x -> key [new_i + 1 ],& x -> key [new_i ],sizeof (MTKey )* (size_t )(itr -> i - new_i )); 1361x -> key [new_i ]= key ; 1362 }else if (new_i > itr -> i ) { 1363memmove (& x -> key [itr -> i ],& x -> key [itr -> i + 1 ],sizeof (MTKey )* (size_t )(new_i - itr -> i - 1 )); 1364x -> key [new_i - 1 ]= key ; 1365 } 1366return ; 1367 } 1368 } 1369uint64_t other = marktree_del_itr (b ,itr , false); 1370key .pos = (MTPos ){row ,col }; 1371 1372marktree_put_key (b ,key ); 1373 1374if (other ) { 1375marktree_restore_pair (b ,key ); 1376 } 1377itr -> x = NULL ;// itr might become invalid by put 1378} 1379 1380void marktree_restore_pair (MarkTree * b ,MTKey key ) 1381{ 1382MarkTreeIter itr [1 ]; 1383MarkTreeIter end_itr [1 ]; 1384marktree_lookup (b ,mt_lookup_key_side (key , false),itr ); 1385marktree_lookup (b ,mt_lookup_key_side (key , true),end_itr ); 1386if (!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. 1389return ; 1390 } 1391rawkey (itr ).flags &= (uint16_t ) ~MT_FLAG_ORPHANED ; 1392rawkey (end_itr ).flags &= (uint16_t ) ~MT_FLAG_ORPHANED ; 1393 1394marktree_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{ 1401return 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 , 1405MTPos * oldbase ,MetaFilter meta_filter ) 1406{ 1407if (b -> n_keys == 0 ) { 1408itr -> x = NULL ; 1409return false; 1410 } 1411 1412MTKey k = { .pos = p , .flags = gravity ?MT_FLAG_RIGHT_GRAVITY :0 }; 1413if (last && !gravity ) { 1414k .flags = MT_FLAG_LAST ; 1415 } 1416itr -> pos = (MTPos ){0 ,0 }; 1417itr -> x = b -> root ; 1418itr -> lvl = 0 ; 1419if (oldbase ) { 1420oldbase [itr -> lvl ]= itr -> pos ; 1421 } 1422while (true) { 1423itr -> i = marktree_getp_aux (itr -> x ,k ,0 )+ 1 ; 1424 1425if (itr -> x -> level == 0 ) { 1426break ; 1427 } 1428if (meta_filter ) { 1429if (!meta_has (itr -> x -> meta [itr -> i ],meta_filter )) { 1430// this takes us to the internal position after the first rejected node 1431break ; 1432 } 1433 } 1434 1435itr -> s [itr -> lvl ].i = itr -> i ; 1436itr -> s [itr -> lvl ].oldcol = itr -> pos .col ; 1437 1438if (itr -> i > 0 ) { 1439compose (& itr -> pos ,itr -> x -> key [itr -> i - 1 ].pos ); 1440relative (itr -> x -> key [itr -> i - 1 ].pos ,& k .pos ); 1441 } 1442itr -> x = itr -> x -> ptr [itr -> i ]; 1443itr -> lvl ++ ; 1444if (oldbase ) { 1445oldbase [itr -> lvl ]= itr -> pos ; 1446 } 1447 } 1448 1449if (last ) { 1450return 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 1453return marktree_itr_next_skip (b ,itr , true, false,NULL ,NULL ); 1454 } 1455return true; 1456} 1457 1458bool marktree_itr_first (MarkTree * b ,MarkTreeIter * itr ) 1459{ 1460if (b -> n_keys == 0 ) { 1461itr -> x = NULL ; 1462return false; 1463 } 1464 1465itr -> x = b -> root ; 1466itr -> i = 0 ; 1467itr -> lvl = 0 ; 1468itr -> pos = MTPos (0 ,0 ); 1469while (itr -> x -> level > 0 ) { 1470itr -> s [itr -> lvl ].i = 0 ; 1471itr -> s [itr -> lvl ].oldcol = 0 ; 1472itr -> lvl ++ ; 1473itr -> x = itr -> x -> ptr [0 ]; 1474 } 1475return true; 1476} 1477 1478// gives the first key that is greater or equal to p 1479int marktree_itr_last (MarkTree * b ,MarkTreeIter * itr ) 1480{ 1481if (b -> n_keys == 0 ) { 1482itr -> x = NULL ; 1483return false; 1484 } 1485itr -> pos = MTPos (0 ,0 ); 1486itr -> x = b -> root ; 1487itr -> lvl = 0 ; 1488while (true) { 1489itr -> i = itr -> x -> n ; 1490 1491if (itr -> x -> level == 0 ) { 1492break ; 1493 } 1494 1495itr -> s [itr -> lvl ].i = itr -> i ; 1496itr -> s [itr -> lvl ].oldcol = itr -> pos .col ; 1497 1498assert (itr -> i > 0 ); 1499compose (& itr -> pos ,itr -> x -> key [itr -> i - 1 ].pos ); 1500 1501itr -> x = itr -> x -> ptr [itr -> i ]; 1502itr -> lvl ++ ; 1503 } 1504itr -> i -- ; 1505return true; 1506} 1507 1508bool marktree_itr_next (MarkTree * b ,MarkTreeIter * itr ) 1509{ 1510return 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 , 1514MTPos oldbase [],MetaFilter meta_filter ) 1515{ 1516if (!itr -> x ) { 1517return false; 1518 } 1519itr -> i ++ ; 1520if (meta_filter && itr -> x -> level > 0 ) { 1521if (!meta_has (itr -> x -> meta [itr -> i ],meta_filter )) { 1522skip = true; 1523 } 1524 } 1525if (itr -> x -> level == 0 || skip ) { 1526if (preload && itr -> x -> level == 0 && skip ) { 1527// skip rest of this leaf node 1528itr -> 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 1532return true; 1533 } 1534// we ran out of non-internal keys. Go up until we find an internal key 1535while (itr -> i >=itr -> x -> n ) { 1536itr -> x = itr -> x -> parent ; 1537if (itr -> x == NULL ) { 1538return false; 1539 } 1540itr -> lvl -- ; 1541itr -> i = itr -> s [itr -> lvl ].i ; 1542if (itr -> i > 0 ) { 1543itr -> pos .row -= itr -> x -> key [itr -> i - 1 ].pos .row ; 1544itr -> 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. 1550while (itr -> x -> level > 0 ) { 1551// internal key, there is always a child after 1552if (itr -> i > 0 ) { 1553itr -> s [itr -> lvl ].oldcol = itr -> pos .col ; 1554compose (& itr -> pos ,itr -> x -> key [itr -> i - 1 ].pos ); 1555 } 1556if (oldbase && itr -> i == 0 ) { 1557oldbase [itr -> lvl + 1 ]= oldbase [itr -> lvl ]; 1558 } 1559itr -> s [itr -> lvl ].i = itr -> i ; 1560assert (itr -> x -> ptr [itr -> i ]-> parent == itr -> x ); 1561itr -> lvl ++ ; 1562itr -> x = itr -> x -> ptr [itr -> i ]; 1563if (preload && itr -> x -> level ) { 1564itr -> i = -1 ; 1565break ; 1566 } 1567itr -> i = 0 ; 1568if (meta_filter && itr -> x -> level ) { 1569if (!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 1571break ; 1572 } 1573 } 1574 } 1575 } 1576return true; 1577} 1578 1579bool marktree_itr_get_filter (MarkTree * b ,int32_t row ,int col ,int stop_row ,int stop_col , 1580MetaFilter meta_filter ,MarkTreeIter * itr ) 1581{ 1582if (!meta_has (b -> meta_root ,meta_filter )) { 1583return false; 1584 } 1585if (!marktree_itr_get_ext (b ,MTPos (row ,col ),itr , false, false,NULL ,meta_filter )) { 1586return false; 1587 } 1588 1589return 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{ 1599if (!meta_has (b -> meta_root ,meta_filter )) { 1600itr -> x = NULL ; 1601return false; 1602 } 1603 1604while (itr -> x && itr -> x -> parent ) { 1605if (meta_has (itr -> x -> parent -> meta [itr -> x -> p_idx ],meta_filter )) { 1606return true; 1607 } 1608 1609itr -> i = itr -> x -> n ; 1610 1611// no filter needed, just reuse the code path for step to parent 1612marktree_itr_next_skip (b ,itr , true, false,NULL ,NULL ); 1613 } 1614 1615return itr -> x ; 1616} 1617 1618bool marktree_itr_next_filter (MarkTree * b ,MarkTreeIter * itr ,int stop_row ,int stop_col , 1619MetaFilter meta_filter ) 1620{ 1621if (!marktree_itr_next_skip (b ,itr , false, false,NULL ,meta_filter )) { 1622return false; 1623 } 1624 1625return marktree_itr_check_filter (b ,itr ,stop_row ,stop_col ,meta_filter ); 1626} 1627 1628static const uint32_t meta_map [kMTMetaCount ]= { 1629MT_FLAG_DECOR_VIRT_TEXT_INLINE , 1630MT_FLAG_DECOR_VIRT_LINES , 1631MT_FLAG_DECOR_SIGNHL , 1632MT_FLAG_DECOR_SIGNTEXT , 1633MT_FLAG_DECOR_CONCEAL_LINES 1634}; 1635static bool marktree_itr_check_filter (MarkTree * b ,MarkTreeIter * itr ,int stop_row ,int stop_col , 1636MetaFilter meta_filter ) 1637{ 1638MTPos stop_pos = MTPos (stop_row ,stop_col ); 1639 1640uint32_t key_filter = 0 ; 1641for (int m = 0 ;m < kMTMetaCount ;m ++ ) { 1642key_filter |=meta_map [m ]& meta_filter [m ]; 1643 } 1644 1645while (true) { 1646if (pos_leq (stop_pos ,marktree_itr_pos (itr ))) { 1647itr -> x = NULL ; 1648return false; 1649 } 1650 1651MTKey k = rawkey (itr ); 1652if (!mt_end (k )&& (k .flags & key_filter )) { 1653return true; 1654 } 1655 1656// this skips subtrees, but not keys, thus the outer loop 1657if (!marktree_itr_next_skip (b ,itr , false, false,NULL ,meta_filter )) { 1658return false; 1659 } 1660 } 1661} 1662 1663bool marktree_itr_prev (MarkTree * b ,MarkTreeIter * itr ) 1664{ 1665if (!itr -> x ) { 1666return false; 1667 } 1668if (itr -> x -> level == 0 ) { 1669itr -> i -- ; 1670if (itr -> i >=0 ) { 1671// TODO(bfredl): this is the common case, 1672// and could be handled by inline wrapper 1673return true; 1674 } 1675// we ran out of non-internal keys. Go up until we find a non-internal key 1676while (itr -> i < 0 ) { 1677itr -> x = itr -> x -> parent ; 1678if (itr -> x == NULL ) { 1679return false; 1680 } 1681itr -> lvl -- ; 1682itr -> i = itr -> s [itr -> lvl ].i - 1 ; 1683if (itr -> i >=0 ) { 1684itr -> pos .row -= itr -> x -> key [itr -> i ].pos .row ; 1685itr -> 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. 1691while (itr -> x -> level > 0 ) { 1692// internal key, there is always a child before 1693if (itr -> i > 0 ) { 1694itr -> s [itr -> lvl ].oldcol = itr -> pos .col ; 1695compose (& itr -> pos ,itr -> x -> key [itr -> i - 1 ].pos ); 1696 } 1697itr -> s [itr -> lvl ].i = itr -> i ; 1698assert (itr -> x -> ptr [itr -> i ]-> parent == itr -> x ); 1699itr -> x = itr -> x -> ptr [itr -> i ]; 1700itr -> i = itr -> x -> n ; 1701itr -> lvl ++ ; 1702 } 1703itr -> i -- ; 1704 } 1705return true; 1706} 1707 1708bool marktree_itr_node_done (MarkTreeIter * itr ) 1709{ 1710return !itr -> x || itr -> i == itr -> x -> n - 1 ; 1711} 1712 1713MTPos marktree_itr_pos (MarkTreeIter * itr ) 1714{ 1715MTPos pos = rawkey (itr ).pos ; 1716unrelative (itr -> pos ,& pos ); 1717return pos ; 1718} 1719 1720MTKey marktree_itr_current (MarkTreeIter * itr ) 1721{ 1722if (itr -> x ) { 1723MTKey key = rawkey (itr ); 1724key .pos = marktree_itr_pos (itr ); 1725return key ; 1726 } 1727return MT_INVALID_KEY ; 1728} 1729 1730static bool itr_eq (MarkTreeIter * itr1 ,MarkTreeIter * itr2 ) 1731{ 1732return (& 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{ 1753if (b -> n_keys == 0 ) { 1754itr -> x = NULL ; 1755return false; 1756 } 1757 1758itr -> x = b -> root ; 1759itr -> i = -1 ; 1760itr -> lvl = 0 ; 1761itr -> pos = MTPos (0 ,0 ); 1762itr -> intersect_pos = MTPos (row ,col ); 1763// intersect_pos but will be adjusted relative itr->x 1764itr -> intersect_pos_x = MTPos (row ,col ); 1765itr -> intersect_idx = 0 ; 1766return 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 1784while (itr -> i == -1 ) { 1785if (itr -> intersect_idx < kv_size (itr -> x -> intersect )) { 1786uint64_t id = kv_A (itr -> x -> intersect ,itr -> intersect_idx ++ ); 1787* pair = mtpair_from (marktree_lookup (b ,id ,NULL ), 1788marktree_lookup (b ,id |MARKTREE_END_FLAG ,NULL )); 1789return true; 1790 } 1791 1792if (itr -> x -> level == 0 ) { 1793itr -> s [itr -> lvl ].i = itr -> i = 0 ; 1794break ; 1795 } 1796 1797MTKey k = { .pos = itr -> intersect_pos_x , .flags = 0 }; 1798itr -> i = marktree_getp_aux (itr -> x ,k ,0 )+ 1 ; 1799 1800itr -> s [itr -> lvl ].i = itr -> i ; 1801itr -> s [itr -> lvl ].oldcol = itr -> pos .col ; 1802 1803if (itr -> i > 0 ) { 1804compose (& itr -> pos ,itr -> x -> key [itr -> i - 1 ].pos ); 1805relative (itr -> x -> key [itr -> i - 1 ].pos ,& itr -> intersect_pos_x ); 1806 } 1807itr -> x = itr -> x -> ptr [itr -> i ]; 1808itr -> lvl ++ ; 1809itr -> i = -1 ; 1810itr -> 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. 1815while (itr -> i < itr -> x -> n && pos_less (rawkey (itr ).pos ,itr -> intersect_pos_x )) { 1816MTKey k = itr -> x -> key [itr -> i ++ ]; 1817itr -> s [itr -> lvl ].i = itr -> i ; 1818if (mt_start (k )) { 1819MTKey end = marktree_lookup (b ,mt_lookup_id (k .ns ,k .id , true),NULL ); 1820if (pos_less (end .pos ,itr -> intersect_pos )) { 1821continue ; 1822 } 1823 1824unrelative (itr -> pos ,& k .pos ); 1825* pair = mtpair_from (k ,end ); 1826return 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 1832while (itr -> i < itr -> x -> n ) { 1833MTKey k = itr -> x -> key [itr -> i ++ ]; 1834if (mt_end (k )) { 1835uint64_t id = mt_lookup_id (k .ns ,k .id , false); 1836if (id2node (b ,id )== itr -> x ) { 1837continue ; 1838 } 1839unrelative (itr -> pos ,& k .pos ); 1840MTKey start = marktree_lookup (b ,id ,NULL ); 1841if (pos_leq (itr -> intersect_pos ,start .pos )) { 1842continue ; 1843 } 1844* pair = mtpair_from (start ,k ); 1845return 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. 1852itr -> i = itr -> s [itr -> lvl ].i ; 1853assert (itr -> i >=0 ); 1854if (itr -> i >=itr -> x -> n ) { 1855marktree_itr_next (b ,itr ); 1856 } 1857 1858// either on or after the intersected position, bail out 1859return false; 1860} 1861 1862static void check_damage (MarkTree * b ,MTDamageMap * damage ,MarkTreeIter * itr1 ,MarkTreeIter * itr2 ) 1863{ 1864const uint64_t start_id = mt_lookup_key_side (rawkey (itr1 ), false); 1865MTDamagePair * p = map_put_ref (uint64_t ,MTDamagePair )(damage ,start_id ,NULL ,NULL ); 1866MTDamage * me = mt_end (rawkey (itr1 )) ?& p -> end :& p -> start ; 1867assert (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{ 1873if (itr1 -> x -> level || itr1 -> x != itr2 -> x ) { 1874if (mt_paired (rawkey (itr1 ))) { 1875check_damage (b ,damage ,itr1 ,itr2 ); 1876 } 1877if (mt_paired (rawkey (itr2 ))) { 1878check_damage (b ,damage ,itr2 ,itr1 ); 1879 } 1880 } 1881 1882if (itr1 -> x != itr2 -> x ) { 1883uint32_t meta_inc_1 [kMTMetaCount ]; 1884meta_describe_key (meta_inc_1 ,rawkey (itr1 )); 1885uint32_t meta_inc_2 [kMTMetaCount ]; 1886meta_describe_key (meta_inc_2 ,rawkey (itr2 )); 1887 1888if (memcmp (meta_inc_1 ,meta_inc_2 ,sizeof (meta_inc_1 ))!= 0 ) { 1889MTNode * x1 = itr1 -> x ; 1890MTNode * x2 = itr2 -> x ; 1891while (x1 != x2 ) { 1892if (x1 -> level <=x2 -> level ) { 1893// as the root node uniquely has the highest level, x1 cannot be it 1894uint32_t * meta_node = x1 -> parent -> meta [x1 -> p_idx ]; 1895for (int m = 0 ;m < kMTMetaCount ;m ++ ) { 1896meta_node [m ]+= meta_inc_2 [m ]- meta_inc_1 [m ]; 1897 } 1898x1 = x1 -> parent ; 1899 } 1900if (x2 -> level < x1 -> level ) { 1901uint32_t * meta_node = x2 -> parent -> meta [x2 -> p_idx ]; 1902for (int m = 0 ;m < kMTMetaCount ;m ++ ) { 1903meta_node [m ]+= meta_inc_1 [m ]- meta_inc_2 [m ]; 1904 } 1905x2 = x2 -> parent ; 1906 } 1907 } 1908 } 1909 } 1910 1911MTKey key1 = rawkey (itr1 ); 1912MTKey key2 = rawkey (itr2 ); 1913rawkey (itr1 )= key2 ; 1914rawkey (itr1 ).pos = key1 .pos ; 1915rawkey (itr2 )= key1 ; 1916rawkey (itr2 ).pos = key2 .pos ; 1917refkey (b ,itr1 -> x ,itr1 -> i ); 1918refkey (b ,itr2 -> x ,itr2 -> i ); 1919} 1920 1921bool marktree_splice (MarkTree * b ,int32_t start_line ,int start_col ,int old_extent_line , 1922int old_extent_col ,int new_extent_line ,int new_extent_col ) 1923{ 1924MTPos start = {start_line ,start_col }; 1925MTPos old_extent = {old_extent_line ,old_extent_col }; 1926MTPos new_extent = {new_extent_line ,new_extent_col }; 1927 1928bool may_delete = (old_extent .row != 0 || old_extent .col != 0 ); 1929bool same_line = old_extent .row == 0 && new_extent .row == 0 ; 1930unrelative (start ,& old_extent ); 1931unrelative (start ,& new_extent ); 1932MarkTreeIter itr [1 ]= {0 }; 1933MarkTreeIter enditr [1 ]= {0 }; 1934 1935MTPos oldbase [MT_MAX_DEPTH ]= {0 }; 1936 1937marktree_itr_get_ext (b ,start ,itr , false, true,oldbase ,NULL ); 1938if (!itr -> x ) { 1939// den e FÄRDIG 1940return false; 1941 } 1942MTPos delta = {new_extent .row - old_extent .row , 1943new_extent .col - old_extent .col }; 1944 1945if (may_delete ) { 1946MTPos ipos = marktree_itr_pos (itr ); 1947if (!pos_leq (old_extent ,ipos ) 1948|| (old_extent .row == ipos .row && old_extent .col == ipos .col 1949&& !mt_right (rawkey (itr )))) { 1950marktree_itr_get_ext (b ,old_extent ,enditr , true, true,NULL ,NULL ); 1951assert (enditr -> x ); 1952// "assert" (itr <= enditr) 1953 }else { 1954may_delete = false; 1955 } 1956 } 1957 1958bool past_right = false; 1959bool moved = false; 1960MTDamageMap 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. 1965if (may_delete ) { 1966while (itr -> x && !past_right ) { 1967MTPos loc_start = start ; 1968MTPos loc_old = old_extent ; 1969relative (itr -> pos ,& loc_start ); 1970 1971relative (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. 1976if (!pos_leq (rawkey (itr ).pos ,loc_old )) { 1977break ; 1978 } 1979 1980if (mt_right (rawkey (itr ))) { 1981while (!itr_eq (itr ,enditr ) 1982&& mt_right (rawkey (enditr ))) { 1983marktree_itr_prev (b ,enditr ); 1984 } 1985if (!mt_right (rawkey (enditr ))) { 1986swap_keys (b ,itr ,enditr ,& damage ); 1987 }else { 1988past_right = true;// NOLINT 1989 (void )past_right ; 1990break ; 1991 } 1992 } 1993 1994if (itr_eq (itr ,enditr )) { 1995// actually, will be past_right after this key 1996past_right = true; 1997 } 1998 1999moved = true; 2000if (itr -> x -> level ) { 2001oldbase [itr -> lvl + 1 ]= rawkey (itr ).pos ; 2002unrelative (oldbase [itr -> lvl ],& oldbase [itr -> lvl + 1 ]); 2003rawkey (itr ).pos = loc_start ; 2004marktree_itr_next_skip (b ,itr , false, false,oldbase ,NULL ); 2005 }else { 2006rawkey (itr ).pos = loc_start ; 2007if (itr -> i < itr -> x -> n - 1 ) { 2008itr -> i ++ ; 2009if (!past_right ) { 2010 gotocontinue_same_node ; 2011 } 2012 }else { 2013marktree_itr_next (b ,itr ); 2014 } 2015 } 2016 } 2017while (itr -> x ) { 2018MTPos loc_new = new_extent ; 2019relative (itr -> pos ,& loc_new ); 2020MTPos limit = old_extent ; 2021 2022relative (oldbase [itr -> lvl ],& limit ); 2023 2024past_continue_same_node : 2025 2026if (pos_leq (limit ,rawkey (itr ).pos )) { 2027break ; 2028 } 2029 2030MTPos oldpos = rawkey (itr ).pos ; 2031rawkey (itr ).pos = loc_new ; 2032moved = true; 2033if (itr -> x -> level ) { 2034oldbase [itr -> lvl + 1 ]= oldpos ; 2035unrelative (oldbase [itr -> lvl ],& oldbase [itr -> lvl + 1 ]); 2036 2037marktree_itr_next_skip (b ,itr , false, false,oldbase ,NULL ); 2038 }else { 2039if (itr -> i < itr -> x -> n - 1 ) { 2040itr -> i ++ ; 2041 gotopast_continue_same_node ; 2042 }else { 2043marktree_itr_next (b ,itr ); 2044 } 2045 } 2046 } 2047 } 2048 2049while (itr -> x ) { 2050unrelative (oldbase [itr -> lvl ],& rawkey (itr ).pos ); 2051int realrow = rawkey (itr ).pos .row ; 2052assert (realrow >=old_extent .row ); 2053bool done = false; 2054if (realrow == old_extent .row ) { 2055if (delta .col ) { 2056rawkey (itr ).pos .col += delta .col ; 2057 } 2058 }else { 2059if (same_line ) { 2060// optimization: column only adjustment can skip remaining rows 2061done = true; 2062 } 2063 } 2064if (delta .row ) { 2065rawkey (itr ).pos .row += delta .row ; 2066moved = true; 2067 } 2068relative (itr -> pos ,& rawkey (itr ).pos ); 2069if (done ) { 2070break ; 2071 } 2072marktree_itr_next_skip (b ,itr , true, false,NULL ,NULL ); 2073 } 2074 2075uint64_t start_id ; 2076MTDamagePair d ; 2077map_foreach (& damage ,start_id ,d , { 2078if (d .start .old && d .end .old ) { 2079// both ends of pair did move 2080marktree_itr_set_node (b ,itr ,d .start .old ,d .start .old_i ); 2081marktree_itr_set_node (b ,enditr ,d .end .old ,d .end .old_i ); 2082marktree_intersect_pair (b ,start_id ,itr ,enditr , true); 2083marktree_itr_set_node (b ,itr ,d .start .new ,d .start .new_i ); 2084marktree_itr_set_node (b ,enditr ,d .end .new ,d .end .new_i ); 2085marktree_intersect_pair (b ,start_id ,itr ,enditr , false); 2086 }else if (d .start .old ) { 2087// only start did move 2088MarkTreeIter endpos [1 ]; 2089marktree_lookup (b ,start_id |MARKTREE_END_FLAG ,endpos ); 2090if (endpos -> x ) { 2091marktree_itr_set_node (b ,itr ,d .start .old ,d .start .old_i ); 2092* enditr = * endpos ; 2093marktree_intersect_pair (b ,start_id ,itr ,enditr , true); 2094marktree_itr_set_node (b ,itr ,d .start .new ,d .start .new_i ); 2095* enditr = * endpos ; 2096marktree_intersect_pair (b ,start_id ,itr ,enditr , false); 2097 } 2098 }else if (d .end .old ) { 2099// only end did move 2100MarkTreeIter startpos [1 ]; 2101marktree_lookup (b ,start_id ,startpos ); 2102if (startpos -> x ) { 2103* itr = * startpos ; 2104marktree_itr_set_node (b ,enditr ,d .end .old ,d .end .old_i ); 2105marktree_intersect_pair (b ,start_id ,itr ,enditr , true); 2106* itr = * startpos ; 2107marktree_itr_set_node (b ,enditr ,d .end .new ,d .end .new_i ); 2108marktree_intersect_pair (b ,start_id ,itr ,enditr , false); 2109 } 2110 } 2111 }); 2112map_destroy (uint64_t ,& damage ); 2113 2114return moved ; 2115} 2116 2117void marktree_move_region (MarkTree * b ,int start_row ,colnr_T start_col ,int extent_row , 2118colnr_T extent_col ,int new_row ,colnr_T new_col ) 2119{ 2120MTPos start = {start_row ,start_col }; 2121MTPos size = {extent_row ,extent_col }; 2122MTPos end = size ; 2123unrelative (start ,& end ); 2124MarkTreeIter itr [1 ]= {0 }; 2125marktree_itr_get_ext (b ,start ,itr , false, true,NULL ,NULL ); 2126kvec_t (MTKey )saved = KV_INITIAL_VALUE ; 2127while (itr -> x ) { 2128MTKey k = marktree_itr_current (itr ); 2129if (!pos_leq (k .pos ,end )|| (k .pos .row == end .row && k .pos .col == end .col 2130&& mt_right (k ))) { 2131break ; 2132 } 2133relative (start ,& k .pos ); 2134kv_push (saved ,k ); 2135marktree_del_itr (b ,itr , false); 2136 } 2137 2138marktree_splice (b ,start .row ,start .col ,size .row ,size .col ,0 ,0 ); 2139MTPos new = {new_row ,new_col }; 2140marktree_splice (b ,new .row ,new .col , 21410 ,0 ,size .row ,size .col ); 2142 2143for (size_t i = 0 ;i < kv_size (saved );i ++ ) { 2144MTKey item = kv_A (saved ,i ); 2145unrelative (new ,& item .pos ); 2146marktree_put_key (b ,item ); 2147if (mt_paired (item )) { 2148// other end might be later in `saved`, this will safely bail out then 2149marktree_restore_pair (b ,item ); 2150 } 2151 } 2152kv_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{ 2158return marktree_lookup (b ,mt_lookup_id (ns ,id ,end ),itr ); 2159} 2160 2161static uint64_t pseudo_index (MTNode * x ,int i ) 2162{ 2163int off = MT_LOG2_BRANCH * x -> level ; 2164uint64_t index = 0 ; 2165 2166while (x ) { 2167index |= (uint64_t )(i + 1 ) <<off ; 2168off += MT_LOG2_BRANCH ; 2169i = x -> p_idx ; 2170x = x -> parent ; 2171 } 2172 2173return 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{ 2180MTNode * n = id2node (b ,id ); 2181if (n == NULL ) { 2182return 0 ;// a valid pseudo-index is never zero! 2183 } 2184 2185int i = 0 ; 2186if (n -> level || !sloppy ) { 2187for (i = 0 ;i < n -> n ;i ++ ) { 2188if (mt_lookup_key (n -> key [i ])== id ) { 2189break ; 2190 } 2191 } 2192assert (i < n -> n ); 2193if (n -> level ) { 2194i += 1 ;// internal key i comes after ptr[i] 2195 } 2196 } 2197 2198return 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{ 2204MTNode * n = id2node (b ,id ); 2205if (n == NULL ) { 2206if (itr ) { 2207itr -> x = NULL ; 2208 } 2209return MT_INVALID_KEY ; 2210 } 2211int i = 0 ; 2212for (i = 0 ;i < n -> n ;i ++ ) { 2213if (mt_lookup_key (n -> key [i ])== id ) { 2214return marktree_itr_set_node (b ,itr ,n ,i ); 2215 } 2216 } 2217 2218abort (); 2219} 2220 2221MTKey marktree_itr_set_node (MarkTree * b ,MarkTreeIter * itr ,MTNode * n ,int i ) 2222{ 2223MTKey key = n -> key [i ]; 2224if (itr ) { 2225itr -> i = i ; 2226itr -> x = n ; 2227itr -> lvl = b -> root -> level - n -> level ; 2228 } 2229while (n -> parent != NULL ) { 2230MTNode * p = n -> parent ; 2231i = n -> p_idx ; 2232assert (p -> ptr [i ]== n ); 2233 2234if (itr ) { 2235itr -> s [b -> root -> level - p -> level ].i = i ; 2236 } 2237if (i > 0 ) { 2238unrelative (p -> key [i - 1 ].pos ,& key .pos ); 2239 } 2240n = p ; 2241 } 2242if (itr ) { 2243marktree_itr_fix_pos (b ,itr ); 2244 } 2245return key ; 2246} 2247 2248MTPos marktree_get_altpos (MarkTree * b ,MTKey mark ,MarkTreeIter * itr ) 2249{ 2250return 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{ 2256return 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{ 2261itr -> pos = (MTPos ){0 ,0 }; 2262MTNode * x = b -> root ; 2263for (int lvl = 0 ;lvl < itr -> lvl ;lvl ++ ) { 2264itr -> s [lvl ].oldcol = itr -> pos .col ; 2265int i = itr -> s [lvl ].i ; 2266if (i > 0 ) { 2267compose (& itr -> pos ,x -> key [i - 1 ].pos ); 2268 } 2269assert (x -> level ); 2270x = x -> ptr [i ]; 2271 } 2272assert (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 , 2277int end_row ,int end_col ,bool end_right ,bool meta_inline ) 2278{ 2279uint16_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. 2282flags |=meta_inline ?MT_FLAG_DECOR_VIRT_TEXT_INLINE :0 ; 2283MTKey key = { {row ,col },ns ,id ,flags , { .hl = DECOR_HIGHLIGHT_INLINE_INIT } }; 2284marktree_put (b ,key ,end_row ,end_col ,end_right ); 2285} 2286 2287// for unit test 2288bool mt_right_test (MTKey key ) 2289{ 2290return mt_right (key ); 2291} 2292 2293// for unit test 2294void marktree_del_pair_test (MarkTree * b ,uint32_t ns ,uint32_t id ) 2295{ 2296MarkTreeIter itr [1 ]; 2297marktree_lookup_ns (b ,ns ,id , false,itr ); 2298 2299uint64_t other = marktree_del_itr (b ,itr , false); 2300assert (other ); 2301marktree_lookup (b ,other ,itr ); 2302marktree_del_itr (b ,itr , false); 2303} 2304 2305void marktree_check (MarkTree * b ) 2306{ 2307#ifndef NDEBUG 2308if (b -> root == NULL ) { 2309assert (b -> n_keys == 0 ); 2310assert (b -> n_nodes == 0 ); 2311assert (b -> id2node == NULL || map_size (b -> id2node )== 0 ); 2312return ; 2313 } 2314 2315MTPos dummy ; 2316bool last_right = false; 2317 2318size_t nkeys = marktree_check_node (b ,b -> root ,& dummy ,& last_right ,b -> meta_root ); 2319assert (b -> n_keys == nkeys ); 2320assert (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 , 2328const uint32_t * meta_node_ref ) 2329{ 2330assert (x -> n <=2 * T - 1 ); 2331// TODO(bfredl): too strict if checking "in repair" post-delete tree. 2332assert (x -> n >= (x != b -> root ?T - 1 :0 )); 2333size_t n_keys = (size_t )x -> n ; 2334 2335for (int i = 0 ;i < x -> n ;i ++ ) { 2336if (x -> level ) { 2337n_keys += marktree_check_node (b ,x -> ptr [i ],last ,last_right ,x -> meta [i ]); 2338 }else { 2339* last = (MTPos ) {0 ,0 }; 2340 } 2341if (i > 0 ) { 2342unrelative (x -> key [i - 1 ].pos ,last ); 2343 } 2344assert (pos_leq (* last ,x -> key [i ].pos )); 2345if (last -> row == x -> key [i ].pos .row && last -> col == x -> key [i ].pos .col ) { 2346assert (!* last_right || mt_right (x -> key [i ])); 2347 } 2348* last_right = mt_right (x -> key [i ]); 2349assert (x -> key [i ].pos .col >=0 ); 2350assert (pmap_get (uint64_t )(b -> id2node ,mt_lookup_key (x -> key [i ]))== x ); 2351 } 2352 2353if (x -> level ) { 2354n_keys += marktree_check_node (b ,x -> ptr [x -> n ],last ,last_right ,x -> meta [x -> n ]); 2355unrelative (x -> key [x -> n - 1 ].pos ,last ); 2356 2357for (int i = 0 ;i < x -> n + 1 ;i ++ ) { 2358assert (x -> ptr [i ]-> parent == x ); 2359assert (x -> ptr [i ]-> p_idx == i ); 2360assert (x -> ptr [i ]-> level == x -> level - 1 ); 2361// PARANOIA: check no double node ref 2362for (int j = 0 ;j < i ;j ++ ) { 2363assert (x -> ptr [i ]!= x -> ptr [j ]); 2364 } 2365 } 2366 }else if (x -> n > 0 ) { 2367* last = x -> key [x -> n - 1 ].pos ; 2368 } 2369 2370uint32_t meta_node [kMTMetaCount ]; 2371meta_describe_node (meta_node ,x ); 2372for (int m = 0 ;m < kMTMetaCount ;m ++ ) { 2373assert (meta_node_ref [m ]== meta_node [m ]); 2374 } 2375 2376return n_keys ; 2377} 2378 2379bool marktree_check_intersections (MarkTree * b ) 2380{ 2381if (!b -> root ) { 2382return true; 2383 } 2384PMap (ptr_t )checked = MAP_INIT ; 2385 2386// 1. move x->intersect to checked[x] and reinit x->intersect 2387mt_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 2391MarkTreeIter itr [1 ]; 2392marktree_itr_first (b ,itr ); 2393while (true) { 2394MTKey mark = marktree_itr_current (itr ); 2395if (mark .pos .row < 0 ) { 2396break ; 2397 } 2398 2399if (mt_start (mark )) { 2400MarkTreeIter start_itr [1 ]; 2401MarkTreeIter end_itr [1 ]; 2402uint64_t end_id = mt_lookup_id (mark .ns ,mark .id , true); 2403MTKey k = marktree_lookup (b ,end_id ,end_itr ); 2404if (k .pos .row >=0 ) { 2405* start_itr = * itr ; 2406marktree_intersect_pair (b ,mt_lookup_key (mark ),start_itr ,end_itr , false); 2407 } 2408 } 2409 2410marktree_itr_next (b ,itr ); 2411 } 2412 2413// 3. for each node check if the recreated intersection 2414// matches the old checked[x] intersection. 2415bool status = mt_recurse_nodes_compare (b -> root ,& checked ); 2416 2417uint64_t * val ; 2418map_foreach_value (& checked ,val , { 2419xfree (val ); 2420 }); 2421map_destroy (ptr_t ,& checked ); 2422 2423return status ; 2424} 2425 2426void mt_recurse_nodes (MTNode * x ,PMap (ptr_t )* checked ) 2427{ 2428if (kv_size (x -> intersect )) { 2429kvi_push (x -> intersect , (uint64_t )-1 );// sentinel 2430uint64_t * val ; 2431if (x -> intersect .items == x -> intersect .init_array ) { 2432val = xmemdup (x -> intersect .items ,x -> intersect .size * sizeof (* x -> intersect .items )); 2433 }else { 2434val = x -> intersect .items ; 2435 } 2436pmap_put (ptr_t )(checked ,x ,val ); 2437kvi_init (x -> intersect ); 2438 } 2439 2440if (x -> level ) { 2441for (int i = 0 ;i < x -> n + 1 ;i ++ ) { 2442mt_recurse_nodes (x -> ptr [i ],checked ); 2443 } 2444 } 2445} 2446 2447bool mt_recurse_nodes_compare (MTNode * x ,PMap (ptr_t )* checked ) 2448{ 2449uint64_t * ref = pmap_get (ptr_t )(checked ,x ); 2450if (ref != NULL ) { 2451for (size_t i = 0 ;;i ++ ) { 2452if (ref [i ]== (uint64_t )-1 ) { 2453if (i != kv_size (x -> intersect )) { 2454return false; 2455 } 2456 2457break ; 2458 }else { 2459if (kv_size (x -> intersect ) <=i || ref [i ]!= kv_A (x -> intersect ,i )) { 2460return false; 2461 } 2462 } 2463 } 2464 }else { 2465if (kv_size (x -> intersect )) { 2466return false; 2467 } 2468 } 2469 2470if (x -> level ) { 2471for (int i = 0 ;i < x -> n + 1 ;i ++ ) { 2472if (!mt_recurse_nodes_compare (x -> ptr [i ],checked )) { 2473return false; 2474 } 2475 } 2476 } 2477 2478return 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{ 2488garray_T ga [1 ]; 2489ga_init (ga , (int )sizeof (char ),80 ); 2490MTPos p = {0 ,0 }; 2491if (b -> root ) { 2492if (dot ) { 2493GA_PUT ("digraph D {\n\n" ); 2494mt_inspect_dotfile_node (b ,ga ,b -> root ,p ,NULL ); 2495GA_PUT ("\n}" ); 2496 }else { 2497mt_inspect_node (b ,ga ,keys ,b -> root ,p ); 2498 } 2499 } 2500return ga_take_string (ga ); 2501} 2502 2503static inline uint64_t mt_dbg_id (uint64_t id ) 2504{ 2505return (id >>1 )& 0xffffffff ; 2506} 2507 2508static void mt_inspect_node (MarkTree * b ,garray_T * ga ,bool keys ,MTNode * n ,MTPos off ) 2509{ 2510static char buf [1024 ]; 2511GA_PUT ("[" ); 2512if (keys && kv_size (n -> intersect )) { 2513for (size_t i = 0 ;i < kv_size (n -> intersect );i ++ ) { 2514GA_PUT (i == 0 ?"{" :";" ); 2515// GA_PRINT("%"PRIu64, kv_A(n->intersect, i)); 2516GA_PRINT ("%" PRIu64 ,mt_dbg_id (kv_A (n -> intersect ,i ))); 2517 } 2518GA_PUT ("}," ); 2519 } 2520if (n -> level ) { 2521mt_inspect_node (b ,ga ,keys ,n -> ptr [0 ],off ); 2522 } 2523for (int i = 0 ;i < n -> n ;i ++ ) { 2524MTPos p = n -> key [i ].pos ; 2525unrelative (off ,& p ); 2526GA_PRINT ("%d/%d" ,p .row ,p .col ); 2527if (keys ) { 2528MTKey key = n -> key [i ]; 2529GA_PUT (":" ); 2530if (mt_start (key )) { 2531GA_PUT ("<" ); 2532 } 2533// GA_PRINT("%"PRIu64, mt_lookup_id(key.ns, key.id, false)); 2534GA_PRINT ("%" PRIu32 ,key .id ); 2535if (mt_end (key )) { 2536GA_PUT (">" ); 2537 } 2538 } 2539if (n -> level ) { 2540mt_inspect_node (b ,ga ,keys ,n -> ptr [i + 1 ],p ); 2541 }else { 2542ga_concat (ga ,"," ); 2543 } 2544 } 2545ga_concat (ga ,"]" ); 2546} 2547 2548static void mt_inspect_dotfile_node (MarkTree * b ,garray_T * ga ,MTNode * n ,MTPos off ,char * parent ) 2549{ 2550static char buf [1024 ]; 2551char namebuf [64 ]; 2552if (parent != NULL ) { 2553snprintf (namebuf ,sizeof namebuf ,"%s_%c%d" ,parent ,'a' + n -> level ,n -> p_idx ); 2554 }else { 2555snprintf (namebuf ,sizeof namebuf ,"MTNode" ); 2556 } 2557 2558GA_PRINT (" %s[shape=plaintext, label=<\n" ,namebuf ); 2559GA_PUT (" <table border='0' cellborder='1' cellspacing='0'>\n" ); 2560if (kv_size (n -> intersect )) { 2561GA_PUT (" <tr><td>" ); 2562for (size_t i = 0 ;i < kv_size (n -> intersect );i ++ ) { 2563if (i > 0 ) { 2564GA_PUT (", " ); 2565 } 2566GA_PRINT ("%" PRIu64 ,mt_dbg_id (kv_A (n -> intersect ,i ))); 2567 } 2568GA_PUT ("</td></tr>\n" ); 2569 } 2570 2571GA_PUT (" <tr><td>" ); 2572for (int i = 0 ;i < n -> n ;i ++ ) { 2573MTKey k = n -> key [i ]; 2574if (i > 0 ) { 2575GA_PUT (", " ); 2576 } 2577GA_PRINT ("%d" ,k .id ); 2578if (mt_paired (k )) { 2579GA_PUT (mt_end (k ) ?"e" :"s" ); 2580 } 2581 } 2582GA_PUT ("</td></tr>\n" ); 2583GA_PUT (" </table>\n" ); 2584GA_PUT (">];\n" ); 2585if (parent ) { 2586GA_PRINT (" %s -> %s\n" ,parent ,namebuf ); 2587 } 2588if (n -> level ) { 2589mt_inspect_dotfile_node (b ,ga ,n -> ptr [0 ],off ,namebuf ); 2590 } 2591for (int i = 0 ;i < n -> n ;i ++ ) { 2592MTPos p = n -> key [i ].pos ; 2593unrelative (off ,& p ); 2594if (n -> level ) { 2595mt_inspect_dotfile_node (b ,ga ,n -> ptr [i + 1 ],p ,namebuf ); 2596 } 2597 } 2598}