tdbBtree.c 26.4 KB
Newer Older
H
Hongze Cheng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
/*
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
 *
 * This program is free software: you can use, redistribute, and/or modify
 * it under the terms of the GNU Affero General Public License, version 3
 * or later ("AGPL"), as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
H
refact  
Hongze Cheng 已提交
14 15
 */

H
Hongze Cheng 已提交
16 17
#include "tdbInt.h"

H
Hongze Cheng 已提交
18 19 20 21 22
#define TDB_BTREE_ROOT 0x1
#define TDB_BTREE_LEAF 0x2

#define TDB_BTREE_PAGE_IS_ROOT(flags) TDB_FLAG_HAS(flags, TDB_BTREE_ROOT)
#define TDB_BTREE_PAGE_IS_LEAF(flags) TDB_FLAG_HAS(flags, TDB_BTREE_LEAF)
H
Hongze Cheng 已提交
23 24 25
#define TDB_BTREE_ASSERT_FLAG(flags)                                                 \
  ASSERT(TDB_FLAG_IS(flags, TDB_BTREE_ROOT) || TDB_FLAG_IS(flags, TDB_BTREE_LEAF) || \
         TDB_FLAG_IS(flags, TDB_BTREE_ROOT | TDB_BTREE_LEAF) || TDB_FLAG_IS(flags, 0))
H
Hongze Cheng 已提交
26

H
Hongze Cheng 已提交
27
struct SBTree {
H
more  
Hongze Cheng 已提交
28 29 30
  SPgno          root;
  int            keyLen;
  int            valLen;
H
Hongze Cheng 已提交
31
  SPager        *pPager;
H
more  
Hongze Cheng 已提交
32
  FKeyComparator kcmpr;
H
more  
Hongze Cheng 已提交
33
  u8             fanout;
H
Hongze Cheng 已提交
34
  int            pageSize;
H
more  
Hongze Cheng 已提交
35 36 37 38
  int            maxLocal;
  int            minLocal;
  int            maxLeaf;
  int            minLeaf;
H
Hongze Cheng 已提交
39
  u8            *pTmp;
H
Hongze Cheng 已提交
40 41
};

H
Hongze Cheng 已提交
42 43
#define TDB_BTREE_PAGE_COMMON_HDR u8 flags;

H
Hongze Cheng 已提交
44 45
#define TDB_BTREE_PAGE_GET_FLAGS(PAGE)        (PAGE)->pData[0]
#define TDB_BTREE_PAGE_SET_FLAGS(PAGE, flags) ((PAGE)->pData[0] = (flags))
H
Hongze Cheng 已提交
46 47 48 49 50

typedef struct __attribute__((__packed__)) {
  TDB_BTREE_PAGE_COMMON_HDR
} SLeafHdr;

H
Hongze Cheng 已提交
51
typedef struct __attribute__((__packed__)) {
H
Hongze Cheng 已提交
52 53 54
  TDB_BTREE_PAGE_COMMON_HDR;
  SPgno pgno;  // right-most child
} SIntHdr;
H
more  
Hongze Cheng 已提交
55

H
Hongze Cheng 已提交
56
typedef struct {
H
Hongze Cheng 已提交
57
  u8      flags;
H
Hongze Cheng 已提交
58
  SBTree *pBt;
H
Hongze Cheng 已提交
59
} SBtreeInitPageArg;
H
Hongze Cheng 已提交
60

H
Hongze Cheng 已提交
61 62 63 64 65 66 67 68 69
typedef struct {
  int   kLen;
  u8   *pKey;
  int   vLen;
  u8   *pVal;
  SPgno pgno;
  u8   *pTmpSpace;
} SCellDecoder;

H
Hongze Cheng 已提交
70
static int tdbBtCursorMoveTo(SBtCursor *pCur, const void *pKey, int kLen, int *pCRst);
H
Hongze Cheng 已提交
71
static int tdbDefaultKeyCmprFn(const void *pKey1, int keyLen1, const void *pKey2, int keyLen2);
H
Hongze Cheng 已提交
72
static int tdbBtreeOpenImpl(SBTree *pBt);
H
Hongze Cheng 已提交
73 74
static int tdbBtreeZeroPage(SPage *pPage, void *arg);
static int tdbBtreeInitPage(SPage *pPage, void *arg);
H
Hongze Cheng 已提交
75 76
static int tdbBtreeEncodeCell(SPage *pPage, const void *pKey, int kLen, const void *pVal, int vLen, SCell *pCell,
                              int *szCell);
H
Hongze Cheng 已提交
77
static int tdbBtreeDecodeCell(SPage *pPage, const SCell *pCell, SCellDecoder *pDecoder);
H
Hongze Cheng 已提交
78
static int tdbBtreeBalance(SBtCursor *pCur);
H
Hongze Cheng 已提交
79
static int tdbBtreeCellSize(const SPage *pPage, SCell *pCell);
H
Hongze Cheng 已提交
80

H
Hongze Cheng 已提交
81
int tdbBtreeOpen(int keyLen, int valLen, SPager *pPager, FKeyComparator kcmpr, SBTree **ppBt) {
H
Hongze Cheng 已提交
82
  SBTree *pBt;
H
Hongze Cheng 已提交
83
  int     ret;
H
more  
Hongze Cheng 已提交
84

H
Hongze Cheng 已提交
85
  *ppBt = NULL;
H
Hongze Cheng 已提交
86 87 88 89 90 91 92 93 94 95

  pBt = (SBTree *)calloc(1, sizeof(*pBt));
  if (pBt == NULL) {
    return -1;
  }

  // pBt->keyLen
  pBt->keyLen = keyLen;
  // pBt->valLen
  pBt->valLen = valLen;
H
refact  
Hongze Cheng 已提交
96 97
  // pBt->pPager
  pBt->pPager = pPager;
H
Hongze Cheng 已提交
98 99
  // pBt->kcmpr
  pBt->kcmpr = kcmpr ? kcmpr : tdbDefaultKeyCmprFn;
H
more  
Hongze Cheng 已提交
100 101 102 103 104 105 106
  // pBt->fanout
  if (keyLen == TDB_VARIANT_LEN) {
    pBt->fanout = TDB_DEFAULT_FANOUT;
  } else {
    ASSERT(0);
    // TODO: pBt->fanout = 0;
  }
H
Hongze Cheng 已提交
107 108 109
  // pBt->pageSize
  pBt->pageSize = tdbPagerGetPageSize(pPager);
  // pBt->maxLocal
H
Hongze Cheng 已提交
110
  pBt->maxLocal = (pBt->pageSize - 14) / pBt->fanout;
H
Hongze Cheng 已提交
111
  // pBt->minLocal: Should not be allowed smaller than 15, which is [nPayload][nKey][nData]
H
Hongze Cheng 已提交
112
  pBt->minLocal = (pBt->pageSize - 14) / pBt->fanout / 2;
H
Hongze Cheng 已提交
113
  // pBt->maxLeaf
H
Hongze Cheng 已提交
114
  pBt->maxLeaf = pBt->pageSize - 14;
H
Hongze Cheng 已提交
115 116
  // pBt->minLeaf
  pBt->minLeaf = pBt->minLocal;
H
Hongze Cheng 已提交
117

H
Hongze Cheng 已提交
118 119 120 121 122 123 124
  // TODO: pBt->root
  ret = tdbBtreeOpenImpl(pBt);
  if (ret < 0) {
    free(pBt);
    return -1;
  }

H
Hongze Cheng 已提交
125
  *ppBt = pBt;
H
Hongze Cheng 已提交
126 127 128 129 130 131 132 133
  return 0;
}

int tdbBtreeClose(SBTree *pBt) {
  // TODO
  return 0;
}

H
more  
Hongze Cheng 已提交
134
int tdbBtreeCursor(SBtCursor *pCur, SBTree *pBt) {
H
more  
Hongze Cheng 已提交
135 136
  pCur->pBt = pBt;
  pCur->iPage = -1;
H
more  
Hongze Cheng 已提交
137
  pCur->pPage = NULL;
H
Hongze Cheng 已提交
138
  pCur->idx = -1;
H
more  
Hongze Cheng 已提交
139

H
more  
Hongze Cheng 已提交
140 141 142
  return 0;
}

H
Hongze Cheng 已提交
143
int tdbBtCursorInsert(SBtCursor *pCur, const void *pKey, int kLen, const void *pVal, int vLen) {
H
Hongze Cheng 已提交
144
  int     ret;
H
Hongze Cheng 已提交
145
  int     idx;
H
Hongze Cheng 已提交
146
  SPager *pPager;
H
Hongze Cheng 已提交
147 148 149
  SCell  *pCell;
  int     szCell;
  int     cret;
H
Hongze Cheng 已提交
150
  SBTree *pBt;
H
Hongze Cheng 已提交
151

H
Hongze Cheng 已提交
152
  ret = tdbBtCursorMoveTo(pCur, pKey, kLen, &cret);
H
Hongze Cheng 已提交
153 154 155 156 157
  if (ret < 0) {
    // TODO: handle error
    return -1;
  }

H
Hongze Cheng 已提交
158
  if (pCur->idx == -1) {
H
Hongze Cheng 已提交
159
    ASSERT(TDB_PAGE_TOTAL_CELLS(pCur->pPage) == 0);
H
Hongze Cheng 已提交
160 161 162
    idx = 0;
  } else {
    if (cret > 0) {
H
Hongze Cheng 已提交
163
      idx = pCur->idx + 1;
H
Hongze Cheng 已提交
164
    } else if (cret < 0) {
H
Hongze Cheng 已提交
165
      idx = pCur->idx;
H
Hongze Cheng 已提交
166 167 168 169 170 171
    } else {
      /* TODO */
      ASSERT(0);
    }
  }

H
Hongze Cheng 已提交
172 173 174 175 176 177 178 179 180 181 182
  // TODO: refact code here
  pBt = pCur->pBt;
  if (!pBt->pTmp) {
    pBt->pTmp = (u8 *)malloc(pBt->pageSize);
    if (pBt->pTmp == NULL) {
      return -1;
    }
  }

  pCell = pBt->pTmp;

H
Hongze Cheng 已提交
183
  // Encode the cell
H
Hongze Cheng 已提交
184 185 186 187
  ret = tdbBtreeEncodeCell(pCur->pPage, pKey, kLen, pVal, vLen, pCell, &szCell);
  if (ret < 0) {
    return -1;
  }
H
Hongze Cheng 已提交
188 189

  // Insert the cell to the index
H
Hongze Cheng 已提交
190
  ret = tdbPageInsertCell(pCur->pPage, idx, pCell, szCell, 0);
H
Hongze Cheng 已提交
191 192
  if (ret < 0) {
    return -1;
H
Hongze Cheng 已提交
193 194
  }

H
Hongze Cheng 已提交
195 196 197 198 199 200 201 202
  // If page is overflow, balance the tree
  if (pCur->pPage->nOverflow > 0) {
    ret = tdbBtreeBalance(pCur);
    if (ret < 0) {
      return -1;
    }
  }

H
more  
Hongze Cheng 已提交
203 204 205
  return 0;
}

H
Hongze Cheng 已提交
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
int tdbBtreeGet(SBTree *pBt, const void *pKey, int kLen, void **ppVal, int *vLen) {
  SBtCursor    btc;
  SCell       *pCell;
  int          cret;
  SCellDecoder cd;

  tdbBtreeCursor(&btc, pBt);

  tdbBtCursorMoveTo(&btc, pKey, kLen, &cret);

  if (cret) {
    return cret;
  }

  pCell = tdbPageGetCell(btc.pPage, btc.idx);
  tdbBtreeDecodeCell(btc.pPage, pCell, &cd);

  *vLen = cd.vLen;
  // TODO: here may have memory leak
  *ppVal = realloc(*ppVal, *vLen);
  if (*ppVal == NULL) {
    return -1;
  }

  memcpy(*ppVal, cd.pVal, cd.vLen);
  return 0;
}

H
Hongze Cheng 已提交
234
static int tdbBtCursorMoveToChild(SBtCursor *pCur, SPgno pgno) {
H
Hongze Cheng 已提交
235 236 237 238 239 240 241 242 243 244 245 246 247
  int ret;

  pCur->pgStack[pCur->iPage] = pCur->pPage;
  pCur->idxStack[pCur->iPage] = pCur->idx;
  pCur->iPage++;
  pCur->pPage = NULL;
  pCur->idx = -1;

  ret = tdbPagerFetchPage(pCur->pBt->pPager, pgno, &pCur->pPage, tdbBtreeInitPage, pCur->pBt);
  if (ret < 0) {
    ASSERT(0);
  }

H
Hongze Cheng 已提交
248 249 250
  return 0;
}

H
Hongze Cheng 已提交
251
static int tdbBtCursorMoveTo(SBtCursor *pCur, const void *pKey, int kLen, int *pCRst) {
H
Hongze Cheng 已提交
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
  int     ret;
  SBTree *pBt;
  SPager *pPager;

  pBt = pCur->pBt;
  pPager = pBt->pPager;

  if (pCur->iPage < 0) {
    ASSERT(pCur->iPage == -1);
    ASSERT(pCur->idx == -1);

    // Move from the root
    ret = tdbPagerFetchPage(pPager, pBt->root, &(pCur->pPage), tdbBtreeInitPage, pBt);
    if (ret < 0) {
      ASSERT(0);
      return -1;
    }

    pCur->iPage = 0;

H
Hongze Cheng 已提交
272
    if (TDB_PAGE_TOTAL_CELLS(pCur->pPage) == 0) {
H
Hongze Cheng 已提交
273
      // Current page is empty
H
Hongze Cheng 已提交
274
      // ASSERT(TDB_FLAG_IS(TDB_PAGE_FLAGS(pCur->pPage), TDB_BTREE_ROOT | TDB_BTREE_LEAF));
H
Hongze Cheng 已提交
275 276 277
      return 0;
    }

H
Hongze Cheng 已提交
278
    for (;;) {
H
Hongze Cheng 已提交
279
      int          lidx, ridx, midx, c, nCells;
H
Hongze Cheng 已提交
280 281 282 283 284
      SCell       *pCell;
      SPage       *pPage;
      SCellDecoder cd = {0};

      pPage = pCur->pPage;
H
Hongze Cheng 已提交
285
      nCells = TDB_PAGE_TOTAL_CELLS(pPage);
H
Hongze Cheng 已提交
286
      lidx = 0;
H
Hongze Cheng 已提交
287 288 289 290
      ridx = nCells - 1;

      ASSERT(nCells > 0);

H
Hongze Cheng 已提交
291
      for (;;) {
H
Hongze Cheng 已提交
292 293 294 295
        if (lidx > ridx) break;

        midx = (lidx + ridx) >> 1;

H
Hongze Cheng 已提交
296
        pCell = tdbPageGetCell(pPage, midx);
H
Hongze Cheng 已提交
297 298 299 300 301 302
        ret = tdbBtreeDecodeCell(pPage, pCell, &cd);
        if (ret < 0) {
          // TODO: handle error
          ASSERT(0);
          return -1;
        }
H
Hongze Cheng 已提交
303

H
Hongze Cheng 已提交
304 305 306
        // Compare the key values
        c = pBt->kcmpr(pKey, kLen, cd.pKey, cd.kLen);
        if (c < 0) {
H
Hongze Cheng 已提交
307 308
          /* input-key < cell-key */
          ridx = midx - 1;
H
Hongze Cheng 已提交
309
        } else if (c > 0) {
H
Hongze Cheng 已提交
310 311
          /* input-key > cell-key */
          lidx = midx + 1;
H
Hongze Cheng 已提交
312
        } else {
H
Hongze Cheng 已提交
313 314 315 316 317
          /* input-key == cell-key */
          break;
        }
      }

H
Hongze Cheng 已提交
318
      // Move downward or break
H
Hongze Cheng 已提交
319 320
      u8 flags = TDB_BTREE_PAGE_GET_FLAGS(pPage);
      u8 leaf = TDB_BTREE_PAGE_IS_LEAF(flags);
H
Hongze Cheng 已提交
321 322
      if (leaf) {
        pCur->idx = midx;
H
Hongze Cheng 已提交
323
        *pCRst = c;
H
Hongze Cheng 已提交
324 325 326 327 328 329
        break;
      } else {
        if (c <= 0) {
          pCur->idx = midx;
          tdbBtCursorMoveToChild(pCur, cd.pgno);
        } else {
H
Hongze Cheng 已提交
330
          pCur->idx = midx + 1;
H
Hongze Cheng 已提交
331 332
          if (midx == nCells - 1) {
            /* Move to right-most child */
H
Hongze Cheng 已提交
333
            tdbBtCursorMoveToChild(pCur, ((SIntHdr *)pCur->pPage->pData)->pgno);
H
Hongze Cheng 已提交
334
          } else {
H
Hongze Cheng 已提交
335
            pCell = tdbPageGetCell(pPage, pCur->idx);
H
Hongze Cheng 已提交
336 337 338
            tdbBtreeDecodeCell(pPage, pCell, &cd);
            tdbBtCursorMoveToChild(pCur, cd.pgno);
          }
H
Hongze Cheng 已提交
339 340
        }
      }
H
Hongze Cheng 已提交
341 342 343 344
    }

  } else {
    // TODO: Move the cursor from a some position instead of a clear state
H
Hongze Cheng 已提交
345
    ASSERT(0);
H
Hongze Cheng 已提交
346
  }
H
more  
Hongze Cheng 已提交
347

H
Hongze Cheng 已提交
348 349
  return 0;
}
H
more  
Hongze Cheng 已提交
350

H
Hongze Cheng 已提交
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
static int tdbDefaultKeyCmprFn(const void *pKey1, int keyLen1, const void *pKey2, int keyLen2) {
  int mlen;
  int cret;

  ASSERT(keyLen1 > 0 && keyLen2 > 0 && pKey1 != NULL && pKey2 != NULL);

  mlen = keyLen1 < keyLen2 ? keyLen1 : keyLen2;
  cret = memcmp(pKey1, pKey2, mlen);
  if (cret == 0) {
    if (keyLen1 < keyLen2) {
      cret = -1;
    } else if (keyLen1 > keyLen2) {
      cret = 1;
    } else {
      cret = 0;
    }
  }
  return cret;
H
Hongze Cheng 已提交
369 370 371 372 373 374 375 376 377 378
}

static int tdbBtreeOpenImpl(SBTree *pBt) {
  // Try to get the root page of the an existing btree

  SPgno  pgno;
  SPage *pPage;
  int    ret;

  {
H
Hongze Cheng 已提交
379
    // 1. TODO: Search the main DB to check if the DB exists
H
Hongze Cheng 已提交
380 381 382 383 384 385 386 387 388
    pgno = 0;
  }

  if (pgno != 0) {
    pBt->root = pgno;
    return 0;
  }

  // Try to create a new database
H
Hongze Cheng 已提交
389
  SBtreeInitPageArg zArg = {.flags = TDB_BTREE_ROOT | TDB_BTREE_LEAF, .pBt = pBt};
H
Hongze Cheng 已提交
390 391 392 393 394 395
  ret = tdbPagerNewPage(pBt->pPager, &pgno, &pPage, tdbBtreeZeroPage, &zArg);
  if (ret < 0) {
    return -1;
  }

  // TODO: Unref the page
H
Hongze Cheng 已提交
396

H
Hongze Cheng 已提交
397 398
  ASSERT(pgno != 0);
  pBt->root = pgno;
H
Hongze Cheng 已提交
399

H
Hongze Cheng 已提交
400 401 402
  return 0;
}

H
Hongze Cheng 已提交
403
static int tdbBtreeInitPage(SPage *pPage, void *arg) {
H
Hongze Cheng 已提交
404
  SBTree *pBt;
H
Hongze Cheng 已提交
405
  u8      flags;
H
Hongze Cheng 已提交
406
  u8      isLeaf;
H
Hongze Cheng 已提交
407

H
Hongze Cheng 已提交
408 409
  pBt = (SBTree *)arg;
  flags = TDB_BTREE_PAGE_GET_FLAGS(pPage);
H
Hongze Cheng 已提交
410
  isLeaf = TDB_BTREE_PAGE_IS_LEAF(flags);
H
Hongze Cheng 已提交
411

H
Hongze Cheng 已提交
412
  ASSERT(flags == TDB_BTREE_PAGE_GET_FLAGS(pPage));
H
Hongze Cheng 已提交
413

H
Hongze Cheng 已提交
414
  tdbPageInit(pPage, isLeaf ? sizeof(SLeafHdr) : sizeof(SIntHdr), tdbBtreeCellSize);
H
Hongze Cheng 已提交
415

H
Hongze Cheng 已提交
416 417
  TDB_BTREE_ASSERT_FLAG(flags);

H
Hongze Cheng 已提交
418
  if (isLeaf) {
H
Hongze Cheng 已提交
419 420 421 422 423 424 425 426 427 428
    pPage->kLen = pBt->keyLen;
    pPage->vLen = pBt->valLen;
    pPage->maxLocal = pBt->maxLeaf;
    pPage->minLocal = pBt->minLeaf;
  } else {
    pPage->kLen = pBt->keyLen;
    pPage->vLen = sizeof(SPgno);
    pPage->maxLocal = pBt->maxLocal;
    pPage->minLocal = pBt->minLocal;
  }
H
Hongze Cheng 已提交
429 430 431 432

  return 0;
}

H
Hongze Cheng 已提交
433
static int tdbBtreeZeroPage(SPage *pPage, void *arg) {
H
Hongze Cheng 已提交
434
  u8      flags;
H
Hongze Cheng 已提交
435
  SBTree *pBt;
H
Hongze Cheng 已提交
436
  u8      isLeaf;
H
Hongze Cheng 已提交
437

H
Hongze Cheng 已提交
438 439
  flags = ((SBtreeInitPageArg *)arg)->flags;
  pBt = ((SBtreeInitPageArg *)arg)->pBt;
H
Hongze Cheng 已提交
440
  isLeaf = TDB_BTREE_PAGE_IS_LEAF(flags);
H
Hongze Cheng 已提交
441

H
Hongze Cheng 已提交
442
  tdbPageZero(pPage, isLeaf ? sizeof(SLeafHdr) : sizeof(SIntHdr), tdbBtreeCellSize);
H
Hongze Cheng 已提交
443 444

  if (isLeaf) {
H
Hongze Cheng 已提交
445
    SLeafHdr *pLeafHdr = (SLeafHdr *)(pPage->pData);
H
Hongze Cheng 已提交
446 447
    pLeafHdr->flags = flags;

H
Hongze Cheng 已提交
448 449 450 451 452
    pPage->kLen = pBt->keyLen;
    pPage->vLen = pBt->valLen;
    pPage->maxLocal = pBt->maxLeaf;
    pPage->minLocal = pBt->minLeaf;
  } else {
H
Hongze Cheng 已提交
453
    SIntHdr *pIntHdr = (SIntHdr *)(pPage->pData);
H
Hongze Cheng 已提交
454 455 456
    pIntHdr->flags = flags;
    pIntHdr->pgno = 0;

H
Hongze Cheng 已提交
457 458 459 460 461
    pPage->kLen = pBt->keyLen;
    pPage->vLen = sizeof(SPgno);
    pPage->maxLocal = pBt->maxLocal;
    pPage->minLocal = pBt->minLocal;
  }
H
Hongze Cheng 已提交
462

H
Hongze Cheng 已提交
463
  return 0;
H
Hongze Cheng 已提交
464 465 466
}

#ifndef TDB_BTREE_BALANCE
H
Hongze Cheng 已提交
467 468 469 470
typedef struct {
  SBTree *pBt;
  SPage  *pParent;
  int     idx;
H
Hongze Cheng 已提交
471
  i8      nOld;
H
Hongze Cheng 已提交
472 473 474 475 476
  SPage  *pOldPages[3];
  i8      nNewPages;
  SPage  *pNewPages[5];
} SBtreeBalanceHelper;

H
Hongze Cheng 已提交
477 478 479 480 481
static int tdbBtreeBalanceDeeper(SBTree *pBt, SPage *pRoot, SPage **ppChild) {
  SPager           *pPager;
  SPage            *pChild;
  SPgno             pgnoChild;
  int               ret;
H
Hongze Cheng 已提交
482
  u8                flags;
H
Hongze Cheng 已提交
483
  SIntHdr          *pIntHdr;
H
Hongze Cheng 已提交
484
  SBtreeInitPageArg zArg;
H
Hongze Cheng 已提交
485
  u8                leaf;
H
Hongze Cheng 已提交
486 487

  pPager = pRoot->pPager;
H
Hongze Cheng 已提交
488
  flags = TDB_BTREE_PAGE_GET_FLAGS(pRoot);
H
Hongze Cheng 已提交
489
  leaf = TDB_BTREE_PAGE_IS_LEAF(flags);
H
Hongze Cheng 已提交
490 491

  // Allocate a new child page
H
Hongze Cheng 已提交
492
  zArg.flags = TDB_FLAG_REMOVE(flags, TDB_BTREE_ROOT);
H
Hongze Cheng 已提交
493 494 495 496 497 498
  zArg.pBt = pBt;
  ret = tdbPagerNewPage(pPager, &pgnoChild, &pChild, tdbBtreeZeroPage, &zArg);
  if (ret < 0) {
    return -1;
  }

H
Hongze Cheng 已提交
499 500 501 502
  if (!leaf) {
    ((SIntHdr *)pChild->pData)->pgno = ((SIntHdr *)(pRoot->pData))->pgno;
  }

H
Hongze Cheng 已提交
503
  // Copy the root page content to the child page
H
Hongze Cheng 已提交
504
  tdbPageCopy(pRoot, pChild);
H
Hongze Cheng 已提交
505 506 507 508 509 510 511 512 513

  // Reinitialize the root page
  zArg.flags = TDB_BTREE_ROOT;
  zArg.pBt = pBt;
  ret = tdbBtreeZeroPage(pRoot, &zArg);
  if (ret < 0) {
    return -1;
  }

H
Hongze Cheng 已提交
514
  pIntHdr = (SIntHdr *)(pRoot->pData);
H
Hongze Cheng 已提交
515
  pIntHdr->pgno = pgnoChild;
H
Hongze Cheng 已提交
516

H
Hongze Cheng 已提交
517 518 519 520
  *ppChild = pChild;
  return 0;
}

H
Hongze Cheng 已提交
521
static int tdbBtreeBalanceNonRoot(SBTree *pBt, SPage *pParent, int idx) {
H
Hongze Cheng 已提交
522 523 524
  int ret;

  int    nOlds;
H
Hongze Cheng 已提交
525
  SPage *pOlds[3] = {0};
H
Hongze Cheng 已提交
526 527
  SCell *pDivCell[3] = {0};
  int    szDivCell[3];
H
Hongze Cheng 已提交
528
  int    sIdx;
H
Hongze Cheng 已提交
529
  u8     childNotLeaf;
H
Hongze Cheng 已提交
530
  SPgno  rPgno;
H
Hongze Cheng 已提交
531

H
Hongze Cheng 已提交
532
  {  // Find 3 child pages at most to do balance
H
Hongze Cheng 已提交
533 534 535
    int    nCells = TDB_PAGE_TOTAL_CELLS(pParent);
    SCell *pCell;

H
Hongze Cheng 已提交
536 537 538 539 540 541 542 543 544 545 546 547 548 549
    if (nCells <= 2) {
      sIdx = 0;
      nOlds = nCells + 1;
    } else {
      // has more than three child pages
      if (idx == 0) {
        sIdx = 0;
      } else if (idx == nCells) {
        sIdx = idx - 2;
      } else {
        sIdx = idx - 1;
      }
      nOlds = 3;
    }
H
Hongze Cheng 已提交
550 551
    for (int i = 0; i < nOlds; i++) {
      ASSERT(sIdx + i <= nCells);
H
Hongze Cheng 已提交
552

H
Hongze Cheng 已提交
553
      SPgno pgno;
H
Hongze Cheng 已提交
554
      if (sIdx + i == nCells) {
H
Hongze Cheng 已提交
555 556 557
        ASSERT(!TDB_BTREE_PAGE_IS_LEAF(TDB_BTREE_PAGE_GET_FLAGS(pParent)));
        pgno = ((SIntHdr *)(pParent->pData))->pgno;
      } else {
H
Hongze Cheng 已提交
558
        pCell = tdbPageGetCell(pParent, sIdx + i);
H
Hongze Cheng 已提交
559 560 561 562 563 564 565 566 567
        pgno = *(SPgno *)pCell;
      }

      ret = tdbPagerFetchPage(pBt->pPager, pgno, pOlds + i, tdbBtreeInitPage, pBt);
      if (ret < 0) {
        ASSERT(0);
        return -1;
      }
    }
H
Hongze Cheng 已提交
568
    // copy the parent key out if child pages are not leaf page
H
Hongze Cheng 已提交
569 570
    childNotLeaf = !TDB_BTREE_PAGE_IS_LEAF(TDB_BTREE_PAGE_GET_FLAGS(pOlds[0]));
    if (childNotLeaf) {
H
Hongze Cheng 已提交
571 572 573 574 575 576 577
      for (int i = 0; i < nOlds; i++) {
        if (sIdx + i < TDB_PAGE_TOTAL_CELLS(pParent)) {
          pCell = tdbPageGetCell(pParent, sIdx + i);
          szDivCell[i] = tdbBtreeCellSize(pParent, pCell);
          pDivCell[i] = malloc(szDivCell[i]);
          memcpy(pDivCell[i], pCell, szDivCell[i]);
        }
H
Hongze Cheng 已提交
578

H
Hongze Cheng 已提交
579 580 581
        if (i < nOlds - 1) {
          ((SPgno *)pDivCell[i])[0] = ((SIntHdr *)pOlds[i]->pData)->pgno;
          ((SIntHdr *)pOlds[i]->pData)->pgno = 0;
H
Hongze Cheng 已提交
582
          tdbPageInsertCell(pOlds[i], TDB_PAGE_TOTAL_CELLS(pOlds[i]), pDivCell[i], szDivCell[i], 1);
H
Hongze Cheng 已提交
583
        }
H
Hongze Cheng 已提交
584
      }
H
Hongze Cheng 已提交
585
      rPgno = ((SIntHdr *)pOlds[nOlds - 1]->pData)->pgno;
H
Hongze Cheng 已提交
586
    }
H
Hongze Cheng 已提交
587
    // drop the cells on parent page
H
Hongze Cheng 已提交
588 589 590 591 592 593 594 595
    for (int i = 0; i < nOlds; i++) {
      nCells = TDB_PAGE_TOTAL_CELLS(pParent);
      if (sIdx < nCells) {
        tdbPageDropCell(pParent, sIdx);
      } else {
        ((SIntHdr *)pParent->pData)->pgno = 0;
      }
    }
H
Hongze Cheng 已提交
596 597
  }

H
Hongze Cheng 已提交
598
  int nNews = 0;
H
Hongze Cheng 已提交
599
  struct {
H
Hongze Cheng 已提交
600 601 602 603
    int cnt;
    int size;
    int iPage;
    int oIdx;
H
Hongze Cheng 已提交
604
  } infoNews[5] = {0};
H
Hongze Cheng 已提交
605 606 607

  {  // Get how many new pages are needed and the new distribution

H
Hongze Cheng 已提交
608 609 610
    // first loop to find minimum number of pages needed
    for (int oPage = 0; oPage < nOlds; oPage++) {
      SPage *pPage = pOlds[oPage];
H
Hongze Cheng 已提交
611 612
      SCell *pCell;
      int    cellBytes;
H
Hongze Cheng 已提交
613
      int    oIdx;
H
Hongze Cheng 已提交
614

H
Hongze Cheng 已提交
615
      for (oIdx = 0; oIdx < TDB_PAGE_TOTAL_CELLS(pPage); oIdx++) {
H
Hongze Cheng 已提交
616
        pCell = tdbPageGetCell(pPage, oIdx);
H
Hongze Cheng 已提交
617 618
        cellBytes = TDB_BYTES_CELL_TAKEN(pPage, pCell);

H
Hongze Cheng 已提交
619 620
        if (infoNews[nNews].size + cellBytes > TDB_PAGE_USABLE_SIZE(pPage)) {
          // page is full, use a new page
H
Hongze Cheng 已提交
621
          nNews++;
H
Hongze Cheng 已提交
622

H
Hongze Cheng 已提交
623 624 625 626 627 628 629
          ASSERT(infoNews[nNews].size + cellBytes <= TDB_PAGE_USABLE_SIZE(pPage));

          if (childNotLeaf) {
            // for non-child page, this cell is used as the right-most child,
            // the divider cell to parent as well
            continue;
          }
H
Hongze Cheng 已提交
630
        }
H
Hongze Cheng 已提交
631 632
        infoNews[nNews].cnt++;
        infoNews[nNews].size += cellBytes;
H
Hongze Cheng 已提交
633
        infoNews[nNews].iPage = oPage;
H
Hongze Cheng 已提交
634
        infoNews[nNews].oIdx = oIdx;
H
Hongze Cheng 已提交
635 636 637
      }
    }

H
Hongze Cheng 已提交
638
    nNews++;
H
Hongze Cheng 已提交
639 640 641

    // back loop to make the distribution even
    for (int iNew = nNews - 1; iNew > 0; iNew--) {
H
Hongze Cheng 已提交
642
      SCell *pCell;
H
Hongze Cheng 已提交
643 644 645
      int    szLCell, szRCell;

      for (;;) {
H
Hongze Cheng 已提交
646
        pCell = tdbPageGetCell(pOlds[infoNews[iNew - 1].iPage], infoNews[iNew - 1].oIdx);
H
Hongze Cheng 已提交
647

H
Hongze Cheng 已提交
648
        if (childNotLeaf) {
H
Hongze Cheng 已提交
649
          szLCell = szRCell = tdbBtreeCellSize(pOlds[infoNews[iNew - 1].iPage], pCell);
H
Hongze Cheng 已提交
650
        } else {
H
Hongze Cheng 已提交
651
          szLCell = tdbBtreeCellSize(pOlds[infoNews[iNew - 1].iPage], pCell);
H
Hongze Cheng 已提交
652

H
Hongze Cheng 已提交
653
          int    iPage = infoNews[iNew - 1].iPage;
H
Hongze Cheng 已提交
654
          int    oIdx = infoNews[iNew - 1].oIdx + 1;
H
Hongze Cheng 已提交
655
          SPage *pPage;
H
Hongze Cheng 已提交
656
          for (;;) {
H
Hongze Cheng 已提交
657
            pPage = pOlds[iPage];
H
Hongze Cheng 已提交
658 659 660 661
            if (oIdx < TDB_PAGE_TOTAL_CELLS(pPage)) {
              break;
            }

H
Hongze Cheng 已提交
662
            iPage++;
H
Hongze Cheng 已提交
663 664 665 666 667
            oIdx = 0;
          }

          pCell = tdbPageGetCell(pPage, oIdx);
          szRCell = tdbBtreeCellSize(pPage, pCell);
H
Hongze Cheng 已提交
668 669 670 671 672 673 674 675
        }

        ASSERT(infoNews[iNew - 1].cnt > 0);

        if (infoNews[iNew].size + szRCell >= infoNews[iNew - 1].size - szRCell) {
          break;
        }

H
Hongze Cheng 已提交
676
        // Move a cell right forward
H
Hongze Cheng 已提交
677 678
        infoNews[iNew - 1].cnt--;
        infoNews[iNew - 1].size -= szLCell;
H
Hongze Cheng 已提交
679
        infoNews[iNew - 1].oIdx--;
H
Hongze Cheng 已提交
680
        for (;;) {
H
Hongze Cheng 已提交
681
          if (infoNews[iNew - 1].oIdx >= 0) {
H
Hongze Cheng 已提交
682 683
            break;
          }
H
Hongze Cheng 已提交
684

H
Hongze Cheng 已提交
685 686
          infoNews[iNew - 1].iPage--;
          infoNews[iNew - 1].oIdx = TDB_PAGE_TOTAL_CELLS(pOlds[infoNews[iNew - 1].iPage]) - 1;
H
Hongze Cheng 已提交
687 688 689
        }

        infoNews[iNew].cnt++;
H
Hongze Cheng 已提交
690
        infoNews[iNew].size += szRCell;
H
Hongze Cheng 已提交
691
      }
H
Hongze Cheng 已提交
692
    }
H
Hongze Cheng 已提交
693 694
  }

H
Hongze Cheng 已提交
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
  SPage *pNews[5] = {0};
  {  // Allocate new pages, reuse the old page when possible

    SPgno             pgno;
    SBtreeInitPageArg iarg;
    u8                flags;

    flags = TDB_BTREE_PAGE_GET_FLAGS(pOlds[0]);

    for (int iNew = 0; iNew < nNews; iNew++) {
      if (iNew < nOlds) {
        pNews[iNew] = pOlds[iNew];
      } else {
        iarg.pBt = pBt;
        iarg.flags = flags;
        ret = tdbPagerNewPage(pBt->pPager, &pgno, pNews + iNew, tdbBtreeZeroPage, &iarg);
        if (ret < 0) {
          ASSERT(0);
        }
      }
    }
H
Hongze Cheng 已提交
716 717

    // TODO: sort the page according to the page number
H
Hongze Cheng 已提交
718 719
  }

H
Hongze Cheng 已提交
720
  {  // Do the real cell distribution
H
Hongze Cheng 已提交
721
    SPage            *pOldsCopy[3] = {0};
H
Hongze Cheng 已提交
722 723 724 725
    SCell            *pCell;
    int               szCell;
    SBtreeInitPageArg iarg;
    int               iNew, nNewCells;
H
Hongze Cheng 已提交
726
    SCellDecoder      cd;
H
Hongze Cheng 已提交
727 728 729 730

    iarg.pBt = pBt;
    iarg.flags = TDB_BTREE_PAGE_GET_FLAGS(pOlds[0]);
    for (int i = 0; i < nOlds; i++) {
H
Hongze Cheng 已提交
731
      tdbPageCreate(pOlds[0]->pageSize, &pOldsCopy[i], NULL, NULL);
H
Hongze Cheng 已提交
732 733 734 735 736
      tdbBtreeZeroPage(pOldsCopy[i], &iarg);
      tdbPageCopy(pOlds[i], pOldsCopy[i]);
    }
    iNew = 0;
    nNewCells = 0;
H
Hongze Cheng 已提交
737
    tdbBtreeZeroPage(pNews[iNew], &iarg);
H
Hongze Cheng 已提交
738 739 740 741 742 743 744 745 746 747 748

    for (int iOld = 0; iOld < nOlds; iOld++) {
      SPage *pPage;

      pPage = pOldsCopy[iOld];

      for (int oIdx = 0; oIdx < TDB_PAGE_TOTAL_CELLS(pPage); oIdx++) {
        pCell = tdbPageGetCell(pPage, oIdx);
        szCell = tdbBtreeCellSize(pPage, pCell);

        ASSERT(nNewCells <= infoNews[iNew].cnt);
H
Hongze Cheng 已提交
749
        ASSERT(iNew < nNews);
H
Hongze Cheng 已提交
750 751 752 753

        if (nNewCells < infoNews[iNew].cnt) {
          tdbPageInsertCell(pNews[iNew], nNewCells, pCell, szCell, 0);
          nNewCells++;
H
Hongze Cheng 已提交
754

H
Hongze Cheng 已提交
755 756 757 758 759 760 761
          // insert parent page
          if (!childNotLeaf && nNewCells == infoNews[iNew].cnt) {
            SIntHdr *pIntHdr = (SIntHdr *)pParent->pData;

            if (iNew == nNews - 1 && pIntHdr->pgno == 0) {
              pIntHdr->pgno = TDB_PAGE_PGNO(pNews[iNew]);
            } else {
H
Hongze Cheng 已提交
762 763
              tdbBtreeDecodeCell(pPage, pCell, &cd);

H
Hongze Cheng 已提交
764
              // TODO: pCell here may be inserted as an overflow cell, handle it
H
Hongze Cheng 已提交
765 766 767 768
              SCell *pNewCell = malloc(cd.kLen + 9);
              int    szNewCell;
              SPgno  pgno;
              pgno = TDB_PAGE_PGNO(pNews[iNew]);
H
Hongze Cheng 已提交
769
              tdbBtreeEncodeCell(pParent, cd.pKey, cd.kLen, (void *)&pgno, sizeof(SPgno), pNewCell, &szNewCell);
H
Hongze Cheng 已提交
770
              tdbPageInsertCell(pParent, sIdx++, pNewCell, szNewCell, 0);
H
Hongze Cheng 已提交
771
            }
H
Hongze Cheng 已提交
772 773

            // move to next new page
H
Hongze Cheng 已提交
774
            iNew++;
H
Hongze Cheng 已提交
775 776 777 778
            nNewCells = 0;
            if (iNew < nNews) {
              tdbBtreeZeroPage(pNews[iNew], &iarg);
            }
H
Hongze Cheng 已提交
779 780 781
          }
        } else {
          ASSERT(childNotLeaf);
H
Hongze Cheng 已提交
782
          ASSERT(iNew < nNews - 1);
H
Hongze Cheng 已提交
783

H
Hongze Cheng 已提交
784 785 786 787
          // set current new page right-most child
          ((SIntHdr *)pNews[iNew]->pData)->pgno = ((SPgno *)pCell)[0];

          // insert to parent as divider cell
H
Hongze Cheng 已提交
788 789 790
          ASSERT(iNew < nNews - 1);
          ((SPgno *)pCell)[0] = TDB_PAGE_PGNO(pNews[iNew]);
          tdbPageInsertCell(pParent, sIdx++, pCell, szCell, 0);
H
Hongze Cheng 已提交
791 792 793 794

          // move to next new page
          iNew++;
          nNewCells = 0;
H
Hongze Cheng 已提交
795 796 797
          if (iNew < nNews) {
            tdbBtreeZeroPage(pNews[iNew], &iarg);
          }
H
Hongze Cheng 已提交
798 799
        }
      }
H
Hongze Cheng 已提交
800
    }
H
Hongze Cheng 已提交
801

H
Hongze Cheng 已提交
802 803 804
    if (childNotLeaf) {
      ASSERT(TDB_PAGE_TOTAL_CELLS(pNews[nNews - 1]) == infoNews[nNews - 1].cnt);
      ((SIntHdr *)(pNews[nNews - 1]->pData))->pgno = rPgno;
H
Hongze Cheng 已提交
805

H
Hongze Cheng 已提交
806 807 808 809 810 811
      SIntHdr *pIntHdr = (SIntHdr *)pParent->pData;
      if (pIntHdr->pgno == 0) {
        pIntHdr->pgno = TDB_PAGE_PGNO(pNews[nNews - 1]);
      } else {
        ((SPgno *)pDivCell[nOlds - 1])[0] = TDB_PAGE_PGNO(pNews[nNews - 1]);
        tdbPageInsertCell(pParent, sIdx, pDivCell[nOlds - 1], szDivCell[nOlds - 1], 0);
H
Hongze Cheng 已提交
812
      }
H
Hongze Cheng 已提交
813 814 815 816 817 818 819
    }

    for (int i = 0; i < nOlds; i++) {
      tdbPageDestroy(pOldsCopy[i], NULL, NULL);
    }
  }

H
Hongze Cheng 已提交
820 821 822 823 824 825
  for (int i = 0; i < 3; i++) {
    if (pDivCell[i]) {
      free(pDivCell[i]);
    }
  }

H
Hongze Cheng 已提交
826
  return 0;
H
Hongze Cheng 已提交
827 828 829 830
}

static int tdbBtreeBalance(SBtCursor *pCur) {
  int    iPage;
H
Hongze Cheng 已提交
831
  SPage *pParent;
H
Hongze Cheng 已提交
832
  SPage *pPage;
H
Hongze Cheng 已提交
833
  int    ret;
H
Hongze Cheng 已提交
834
  u8     flags;
H
Hongze Cheng 已提交
835 836
  u8     leaf;
  u8     root;
H
Hongze Cheng 已提交
837 838 839 840

  // Main loop to balance the BTree
  for (;;) {
    iPage = pCur->iPage;
H
Hongze Cheng 已提交
841
    pPage = pCur->pPage;
H
Hongze Cheng 已提交
842
    flags = TDB_BTREE_PAGE_GET_FLAGS(pPage);
H
Hongze Cheng 已提交
843 844
    leaf = TDB_BTREE_PAGE_IS_LEAF(flags);
    root = TDB_BTREE_PAGE_IS_ROOT(flags);
H
Hongze Cheng 已提交
845

H
Hongze Cheng 已提交
846 847
    // when the page is not overflow and not too empty, the balance work
    // is finished. Just break out the balance loop.
H
Hongze Cheng 已提交
848
    if (pPage->nOverflow == 0 /* TODO: && pPage->nFree <= */) {
H
Hongze Cheng 已提交
849 850 851 852
      break;
    }

    if (iPage == 0) {
H
Hongze Cheng 已提交
853 854 855
      // For the root page, only balance when the page is overfull,
      // ignore the case of empty
      if (pPage->nOverflow == 0) break;
H
Hongze Cheng 已提交
856

H
Hongze Cheng 已提交
857
      ret = tdbBtreeBalanceDeeper(pCur->pBt, pPage, &(pCur->pgStack[1]));
H
Hongze Cheng 已提交
858 859 860 861 862 863 864 865 866
      if (ret < 0) {
        return -1;
      }

      pCur->idx = 0;
      pCur->idxStack[0] = 0;
      pCur->pgStack[0] = pCur->pPage;
      pCur->iPage = 1;
      pCur->pPage = pCur->pgStack[1];
H
Hongze Cheng 已提交
867
    } else {
H
Hongze Cheng 已提交
868
      // Generalized balance step
H
Hongze Cheng 已提交
869
      pParent = pCur->pgStack[iPage - 1];
H
Hongze Cheng 已提交
870

H
Hongze Cheng 已提交
871
      ret = tdbBtreeBalanceNonRoot(pCur->pBt, pParent, pCur->idxStack[pCur->iPage - 1]);
H
Hongze Cheng 已提交
872 873 874 875 876 877
      if (ret < 0) {
        return -1;
      }

      pCur->iPage--;
      pCur->pPage = pCur->pgStack[pCur->iPage];
H
Hongze Cheng 已提交
878 879 880 881 882
    }
  }

  return 0;
}
H
Hongze Cheng 已提交
883 884
#endif

H
Hongze Cheng 已提交
885
#ifndef TDB_BTREE_CELL  // =========================================================
H
Hongze Cheng 已提交
886
static int tdbBtreeEncodePayload(SPage *pPage, u8 *pPayload, const void *pKey, int kLen, const void *pVal, int vLen,
H
Hongze Cheng 已提交
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915
                                 int *szPayload) {
  int nPayload;

  ASSERT(pKey != NULL);

  if (pVal == NULL) {
    vLen = 0;
  }

  nPayload = kLen + vLen;
  if (nPayload <= pPage->maxLocal) {
    // General case without overflow
    memcpy(pPayload, pKey, kLen);
    if (pVal) {
      memcpy(pPayload + kLen, pVal, vLen);
    }

    *szPayload = nPayload;
    return 0;
  }

  {
    // TODO: handle overflow case
    ASSERT(0);
  }

  return 0;
}

H
Hongze Cheng 已提交
916 917
static int tdbBtreeEncodeCell(SPage *pPage, const void *pKey, int kLen, const void *pVal, int vLen, SCell *pCell,
                              int *szCell) {
H
Hongze Cheng 已提交
918
  u8  flags;
H
Hongze Cheng 已提交
919 920 921 922
  u8  leaf;
  int nHeader;
  int nPayload;
  int ret;
H
Hongze Cheng 已提交
923 924 925 926

  ASSERT(pPage->kLen == TDB_VARIANT_LEN || pPage->kLen == kLen);
  ASSERT(pPage->vLen == TDB_VARIANT_LEN || pPage->vLen == vLen);

H
Hongze Cheng 已提交
927 928
  nPayload = 0;
  nHeader = 0;
H
Hongze Cheng 已提交
929
  flags = TDB_BTREE_PAGE_GET_FLAGS(pPage);
H
Hongze Cheng 已提交
930
  leaf = TDB_BTREE_PAGE_IS_LEAF(flags);
H
Hongze Cheng 已提交
931

H
Hongze Cheng 已提交
932
  // 1. Encode Header part
H
Hongze Cheng 已提交
933 934 935 936 937 938 939 940
  /* Encode SPgno if interior page */
  if (!leaf) {
    ASSERT(pPage->vLen == sizeof(SPgno));

    ((SPgno *)(pCell + nHeader))[0] = ((SPgno *)pVal)[0];
    nHeader = nHeader + sizeof(SPgno);
  }

H
Hongze Cheng 已提交
941
  /* Encode kLen if need */
H
Hongze Cheng 已提交
942
  if (pPage->kLen == TDB_VARIANT_LEN) {
H
Hongze Cheng 已提交
943
    nHeader += tdbPutVarInt(pCell + nHeader, kLen);
H
Hongze Cheng 已提交
944 945
  }

H
Hongze Cheng 已提交
946
  /* Encode vLen if need */
H
Hongze Cheng 已提交
947
  if (pPage->vLen == TDB_VARIANT_LEN) {
H
Hongze Cheng 已提交
948
    nHeader += tdbPutVarInt(pCell + nHeader, vLen);
H
Hongze Cheng 已提交
949 950
  }

H
Hongze Cheng 已提交
951 952 953 954 955 956 957 958 959
  // 2. Encode payload part
  if (leaf) {
    ret = tdbBtreeEncodePayload(pPage, pCell + nHeader, pKey, kLen, pVal, vLen, &nPayload);
  } else {
    ret = tdbBtreeEncodePayload(pPage, pCell + nHeader, pKey, kLen, NULL, 0, &nPayload);
  }
  if (ret < 0) {
    // TODO: handle error
    return -1;
H
Hongze Cheng 已提交
960 961
  }

H
Hongze Cheng 已提交
962
  *szCell = nHeader + nPayload;
H
Hongze Cheng 已提交
963 964 965
  return 0;
}

H
Hongze Cheng 已提交
966 967 968 969
static int tdbBtreeDecodePayload(SPage *pPage, const u8 *pPayload, SCellDecoder *pDecoder) {
  int nPayload;

  ASSERT(pDecoder->pKey == NULL);
H
Hongze Cheng 已提交
970

H
Hongze Cheng 已提交
971 972
  if (pDecoder->pVal) {
    nPayload = pDecoder->kLen + pDecoder->vLen;
H
Hongze Cheng 已提交
973
  } else {
H
Hongze Cheng 已提交
974
    nPayload = pDecoder->kLen;
H
Hongze Cheng 已提交
975 976
  }

H
Hongze Cheng 已提交
977 978 979
  if (nPayload <= pPage->maxLocal) {
    // General case without overflow
    pDecoder->pKey = (void *)pPayload;
H
Hongze Cheng 已提交
980 981
    if (!pDecoder->pVal) {
      pDecoder->pVal = (void *)(pPayload + pDecoder->kLen);
H
Hongze Cheng 已提交
982
    }
H
Hongze Cheng 已提交
983
  } else {
H
Hongze Cheng 已提交
984 985
    // TODO: handle overflow case
    ASSERT(0);
H
Hongze Cheng 已提交
986 987
  }

H
Hongze Cheng 已提交
988 989 990 991
  return 0;
}

static int tdbBtreeDecodeCell(SPage *pPage, const SCell *pCell, SCellDecoder *pDecoder) {
H
Hongze Cheng 已提交
992
  u8  flags;
H
Hongze Cheng 已提交
993 994 995 996 997
  u8  leaf;
  int nHeader;
  int ret;

  nHeader = 0;
H
Hongze Cheng 已提交
998
  flags = TDB_BTREE_PAGE_GET_FLAGS(pPage);
H
Hongze Cheng 已提交
999 1000
  leaf = TDB_BTREE_PAGE_IS_LEAF(flags);

H
Hongze Cheng 已提交
1001 1002 1003 1004 1005 1006 1007
  // Clear the state of decoder
  pDecoder->kLen = -1;
  pDecoder->pKey = NULL;
  pDecoder->vLen = -1;
  pDecoder->pVal = NULL;
  pDecoder->pgno = 0;

H
Hongze Cheng 已提交
1008
  // 1. Decode header part
H
Hongze Cheng 已提交
1009 1010 1011 1012 1013 1014 1015 1016
  if (!leaf) {
    ASSERT(pPage->vLen == sizeof(SPgno));

    pDecoder->pgno = ((SPgno *)(pCell + nHeader))[0];
    pDecoder->pVal = (u8 *)(&(pDecoder->pgno));
    nHeader = nHeader + sizeof(SPgno);
  }

H
Hongze Cheng 已提交
1017 1018 1019 1020 1021 1022 1023 1024
  if (pPage->kLen == TDB_VARIANT_LEN) {
    nHeader += tdbGetVarInt(pCell + nHeader, &(pDecoder->kLen));
  } else {
    pDecoder->kLen = pPage->kLen;
  }

  if (pPage->vLen == TDB_VARIANT_LEN) {
    nHeader += tdbGetVarInt(pCell + nHeader, &(pDecoder->vLen));
H
Hongze Cheng 已提交
1025
  } else {
H
Hongze Cheng 已提交
1026 1027
    pDecoder->vLen = pPage->vLen;
  }
H
Hongze Cheng 已提交
1028

H
Hongze Cheng 已提交
1029 1030 1031 1032
  // 2. Decode payload part
  ret = tdbBtreeDecodePayload(pPage, pCell + nHeader, pDecoder);
  if (ret < 0) {
    return -1;
H
Hongze Cheng 已提交
1033 1034 1035 1036 1037
  }

  return 0;
}

H
Hongze Cheng 已提交
1038
static int tdbBtreeCellSize(const SPage *pPage, SCell *pCell) {
H
Hongze Cheng 已提交
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
  u8  flags;
  u8  isLeaf;
  int szCell;
  int kLen = 0, vLen = 0;

  flags = TDB_BTREE_PAGE_GET_FLAGS(pPage);
  isLeaf = TDB_BTREE_PAGE_IS_LEAF(flags);
  szCell = 0;

  if (!isLeaf) {
    szCell += sizeof(SPgno);
  }

  if (pPage->kLen == TDB_VARIANT_LEN) {
    szCell += tdbGetVarInt(pCell + szCell, &kLen);
  } else {
    kLen = pPage->kLen;
  }

  if (isLeaf) {
    if (pPage->vLen == TDB_VARIANT_LEN) {
      szCell += tdbGetVarInt(pCell + szCell, &vLen);
    } else {
      vLen = pPage->vLen;
    }
  }

  szCell = szCell + kLen + vLen;

  return szCell;
}

#endif