tdbBtree.c 31.7 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
Hongze Cheng 已提交
33
  int            pageSize;
H
more  
Hongze Cheng 已提交
34 35 36 37
  int            maxLocal;
  int            minLocal;
  int            maxLeaf;
  int            minLeaf;
H
Hongze Cheng 已提交
38
  u8            *pTmp;
H
Hongze Cheng 已提交
39 40
};

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

H
Hongze Cheng 已提交
43 44
#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 已提交
45 46 47 48 49

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

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

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

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

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

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

H
Hongze Cheng 已提交
87 88
  ASSERT(keyLen != 0);

H
Hongze Cheng 已提交
89
  *ppBt = NULL;
H
Hongze Cheng 已提交
90

H
Hongze Cheng 已提交
91
  pBt = (SBTree *)tdbOsCalloc(1, sizeof(*pBt));
H
Hongze Cheng 已提交
92 93 94 95 96 97 98 99
  if (pBt == NULL) {
    return -1;
  }

  // pBt->keyLen
  pBt->keyLen = keyLen;
  // pBt->valLen
  pBt->valLen = valLen;
H
refact  
Hongze Cheng 已提交
100 101
  // pBt->pPager
  pBt->pPager = pPager;
H
Hongze Cheng 已提交
102 103
  // pBt->kcmpr
  pBt->kcmpr = kcmpr ? kcmpr : tdbDefaultKeyCmprFn;
H
Hongze Cheng 已提交
104 105 106
  // pBt->pageSize
  pBt->pageSize = tdbPagerGetPageSize(pPager);
  // pBt->maxLocal
H
Hongze Cheng 已提交
107
  pBt->maxLocal = tdbPageCapacity(pBt->pageSize, sizeof(SIntHdr)) / 4;
H
Hongze Cheng 已提交
108
  // pBt->minLocal: Should not be allowed smaller than 15, which is [nPayload][nKey][nData]
H
Hongze Cheng 已提交
109
  pBt->minLocal = pBt->maxLocal / 2;
H
Hongze Cheng 已提交
110
  // pBt->maxLeaf
H
Hongze Cheng 已提交
111
  pBt->maxLeaf = tdbPageCapacity(pBt->pageSize, sizeof(SLeafHdr));
H
Hongze Cheng 已提交
112 113
  // pBt->minLeaf
  pBt->minLeaf = pBt->minLocal;
H
Hongze Cheng 已提交
114

H
Hongze Cheng 已提交
115 116 117
  // TODO: pBt->root
  ret = tdbBtreeOpenImpl(pBt);
  if (ret < 0) {
H
Hongze Cheng 已提交
118
    tdbOsFree(pBt);
H
Hongze Cheng 已提交
119 120 121
    return -1;
  }

H
Hongze Cheng 已提交
122
  *ppBt = pBt;
H
Hongze Cheng 已提交
123 124 125 126 127 128 129 130
  return 0;
}

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

H
Hongze Cheng 已提交
131
int tdbBtCursorInsert(SBTC *pBtc, const void *pKey, int kLen, const void *pVal, int vLen) {
H
Hongze Cheng 已提交
132
  int     ret;
H
Hongze Cheng 已提交
133
  int     idx;
H
Hongze Cheng 已提交
134
  SPager *pPager;
H
Hongze Cheng 已提交
135 136 137
  SCell  *pCell;
  int     szCell;
  int     cret;
H
Hongze Cheng 已提交
138
  SBTree *pBt;
H
Hongze Cheng 已提交
139

H
Hongze Cheng 已提交
140
  ret = tdbBtCursorMoveTo(pBtc, pKey, kLen, &cret);
H
Hongze Cheng 已提交
141 142 143 144 145
  if (ret < 0) {
    // TODO: handle error
    return -1;
  }

H
Hongze Cheng 已提交
146 147
  if (pBtc->idx == -1) {
    ASSERT(TDB_PAGE_TOTAL_CELLS(pBtc->pPage) == 0);
H
Hongze Cheng 已提交
148 149 150
    idx = 0;
  } else {
    if (cret > 0) {
H
Hongze Cheng 已提交
151
      idx = pBtc->idx + 1;
H
Hongze Cheng 已提交
152
    } else if (cret < 0) {
H
Hongze Cheng 已提交
153
      idx = pBtc->idx;
H
Hongze Cheng 已提交
154 155 156 157 158 159
    } else {
      /* TODO */
      ASSERT(0);
    }
  }

H
Hongze Cheng 已提交
160
  // TODO: refact code here
H
Hongze Cheng 已提交
161
  pBt = pBtc->pBt;
H
Hongze Cheng 已提交
162
  if (!pBt->pTmp) {
H
Hongze Cheng 已提交
163
    pBt->pTmp = (u8 *)tdbOsMalloc(pBt->pageSize);
H
Hongze Cheng 已提交
164 165 166 167 168 169 170
    if (pBt->pTmp == NULL) {
      return -1;
    }
  }

  pCell = pBt->pTmp;

H
Hongze Cheng 已提交
171
  // Encode the cell
H
Hongze Cheng 已提交
172
  ret = tdbBtreeEncodeCell(pBtc->pPage, pKey, kLen, pVal, vLen, pCell, &szCell);
H
Hongze Cheng 已提交
173 174 175
  if (ret < 0) {
    return -1;
  }
H
Hongze Cheng 已提交
176 177

  // Insert the cell to the index
H
Hongze Cheng 已提交
178
  ret = tdbPageInsertCell(pBtc->pPage, idx, pCell, szCell, 0);
H
Hongze Cheng 已提交
179 180
  if (ret < 0) {
    return -1;
H
Hongze Cheng 已提交
181 182
  }

H
Hongze Cheng 已提交
183
  // If page is overflow, balance the tree
H
Hongze Cheng 已提交
184 185
  if (pBtc->pPage->nOverflow > 0) {
    ret = tdbBtreeBalance(pBtc);
H
Hongze Cheng 已提交
186 187 188 189 190
    if (ret < 0) {
      return -1;
    }
  }

H
more  
Hongze Cheng 已提交
191 192 193
  return 0;
}

H
Hongze Cheng 已提交
194
int tdbBtreeGet(SBTree *pBt, const void *pKey, int kLen, void **ppVal, int *vLen) {
H
refact  
Hongze Cheng 已提交
195
  SBTC         btc;
H
Hongze Cheng 已提交
196 197
  SCell       *pCell;
  int          cret;
H
Hongze Cheng 已提交
198
  void        *pVal;
H
Hongze Cheng 已提交
199 200
  SCellDecoder cd;

H
Hongze Cheng 已提交
201
  tdbBtcOpen(&btc, pBt);
H
Hongze Cheng 已提交
202 203 204 205 206 207 208 209 210 211 212

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

  if (cret) {
    return cret;
  }

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

  *vLen = cd.vLen;
H
Hongze Cheng 已提交
213 214
  pVal = TDB_REALLOC(*ppVal, *vLen);
  if (pVal == NULL) {
H
Hongze Cheng 已提交
215 216 217
    return -1;
  }

H
Hongze Cheng 已提交
218
  *ppVal = pVal;
H
Hongze Cheng 已提交
219 220 221 222
  memcpy(*ppVal, cd.pVal, cd.vLen);
  return 0;
}

223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
int tdbBtreePGet(SBTree *pBt, const void *pKey, int kLen, void **ppKey, int *pkLen, void **ppVal, int *vLen) {
  SBTC         btc;
  SCell       *pCell;
  int          cret;
  void        *pTKey;
  void        *pTVal;
  SCellDecoder cd;

  tdbBtcOpen(&btc, pBt);

  tdbBtCursorMoveTo(&btc, pKey, kLen, &cret);
  if (cret) {
    return cret;
  }

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

  pTKey = TDB_REALLOC(*ppKey, cd.kLen);
  pTVal = TDB_REALLOC(*ppVal, cd.vLen);

  if (pTKey == NULL || pTVal == NULL) {
    TDB_FREE(pTKey);
    TDB_FREE(pTVal);
  }

  *ppKey = pTKey;
  *ppVal = pTVal;
  *pkLen = cd.kLen;
  *vLen = cd.vLen;

  return 0;
}

H
Hongze Cheng 已提交
257
static int tdbBtCursorMoveTo(SBTC *pBtc, const void *pKey, int kLen, int *pCRst) {
H
Hongze Cheng 已提交
258 259 260 261
  int     ret;
  SBTree *pBt;
  SPager *pPager;

H
Hongze Cheng 已提交
262
  pBt = pBtc->pBt;
H
Hongze Cheng 已提交
263 264
  pPager = pBt->pPager;

H
Hongze Cheng 已提交
265 266 267
  if (pBtc->iPage < 0) {
    ASSERT(pBtc->iPage == -1);
    ASSERT(pBtc->idx == -1);
H
Hongze Cheng 已提交
268 269

    // Move from the root
H
Hongze Cheng 已提交
270
    ret = tdbPagerFetchPage(pPager, pBt->root, &(pBtc->pPage), tdbBtreeInitPage, pBt);
H
Hongze Cheng 已提交
271 272 273 274 275
    if (ret < 0) {
      ASSERT(0);
      return -1;
    }

H
Hongze Cheng 已提交
276
    pBtc->iPage = 0;
H
Hongze Cheng 已提交
277

H
Hongze Cheng 已提交
278
    if (TDB_PAGE_TOTAL_CELLS(pBtc->pPage) == 0) {
H
Hongze Cheng 已提交
279
      // Current page is empty
H
Hongze Cheng 已提交
280
      // ASSERT(TDB_FLAG_IS(TDB_PAGE_FLAGS(pBtc->pPage), TDB_BTREE_ROOT | TDB_BTREE_LEAF));
H
Hongze Cheng 已提交
281 282 283
      return 0;
    }

H
Hongze Cheng 已提交
284
    for (;;) {
H
Hongze Cheng 已提交
285
      int          lidx, ridx, midx, c, nCells;
H
Hongze Cheng 已提交
286 287 288 289
      SCell       *pCell;
      SPage       *pPage;
      SCellDecoder cd = {0};

H
Hongze Cheng 已提交
290
      pPage = pBtc->pPage;
H
Hongze Cheng 已提交
291
      nCells = TDB_PAGE_TOTAL_CELLS(pPage);
H
Hongze Cheng 已提交
292
      lidx = 0;
H
Hongze Cheng 已提交
293 294 295 296
      ridx = nCells - 1;

      ASSERT(nCells > 0);

H
Hongze Cheng 已提交
297
      for (;;) {
H
Hongze Cheng 已提交
298 299 300 301
        if (lidx > ridx) break;

        midx = (lidx + ridx) >> 1;

H
Hongze Cheng 已提交
302
        pCell = tdbPageGetCell(pPage, midx);
H
Hongze Cheng 已提交
303 304 305 306 307 308
        ret = tdbBtreeDecodeCell(pPage, pCell, &cd);
        if (ret < 0) {
          // TODO: handle error
          ASSERT(0);
          return -1;
        }
H
Hongze Cheng 已提交
309

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

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

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

H
Hongze Cheng 已提交
354 355
  return 0;
}
H
more  
Hongze Cheng 已提交
356

H
Hongze Cheng 已提交
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
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 已提交
375 376 377 378 379 380 381 382 383 384
}

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 已提交
385
    // 1. TODO: Search the main DB to check if the DB exists
H
Hongze Cheng 已提交
386 387 388 389 390 391 392 393 394
    pgno = 0;
  }

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

  // Try to create a new database
H
Hongze Cheng 已提交
395
  SBtreeInitPageArg zArg = {.flags = TDB_BTREE_ROOT | TDB_BTREE_LEAF, .pBt = pBt};
H
Hongze Cheng 已提交
396 397 398 399 400 401
  ret = tdbPagerNewPage(pBt->pPager, &pgno, &pPage, tdbBtreeZeroPage, &zArg);
  if (ret < 0) {
    return -1;
  }

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

H
Hongze Cheng 已提交
403 404
  ASSERT(pgno != 0);
  pBt->root = pgno;
H
Hongze Cheng 已提交
405

H
Hongze Cheng 已提交
406 407 408
  return 0;
}

H
Hongze Cheng 已提交
409
static int tdbBtreeInitPage(SPage *pPage, void *arg) {
H
Hongze Cheng 已提交
410
  SBTree *pBt;
H
Hongze Cheng 已提交
411
  u8      flags;
H
Hongze Cheng 已提交
412
  u8      isLeaf;
H
Hongze Cheng 已提交
413

H
Hongze Cheng 已提交
414 415
  pBt = (SBTree *)arg;
  flags = TDB_BTREE_PAGE_GET_FLAGS(pPage);
H
Hongze Cheng 已提交
416
  isLeaf = TDB_BTREE_PAGE_IS_LEAF(flags);
H
Hongze Cheng 已提交
417

H
Hongze Cheng 已提交
418
  ASSERT(flags == TDB_BTREE_PAGE_GET_FLAGS(pPage));
H
Hongze Cheng 已提交
419

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

H
Hongze Cheng 已提交
422 423
  TDB_BTREE_ASSERT_FLAG(flags);

H
Hongze Cheng 已提交
424
  if (isLeaf) {
H
Hongze Cheng 已提交
425 426 427 428 429 430 431 432 433 434
    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 已提交
435 436 437 438

  return 0;
}

H
Hongze Cheng 已提交
439
static int tdbBtreeZeroPage(SPage *pPage, void *arg) {
H
Hongze Cheng 已提交
440
  u8      flags;
H
Hongze Cheng 已提交
441
  SBTree *pBt;
H
Hongze Cheng 已提交
442
  u8      isLeaf;
H
Hongze Cheng 已提交
443

H
Hongze Cheng 已提交
444 445
  flags = ((SBtreeInitPageArg *)arg)->flags;
  pBt = ((SBtreeInitPageArg *)arg)->pBt;
H
Hongze Cheng 已提交
446
  isLeaf = TDB_BTREE_PAGE_IS_LEAF(flags);
H
Hongze Cheng 已提交
447

H
Hongze Cheng 已提交
448
  tdbPageZero(pPage, isLeaf ? sizeof(SLeafHdr) : sizeof(SIntHdr), tdbBtreeCellSize);
H
Hongze Cheng 已提交
449 450

  if (isLeaf) {
H
Hongze Cheng 已提交
451
    SLeafHdr *pLeafHdr = (SLeafHdr *)(pPage->pData);
H
Hongze Cheng 已提交
452 453
    pLeafHdr->flags = flags;

H
Hongze Cheng 已提交
454 455 456 457 458
    pPage->kLen = pBt->keyLen;
    pPage->vLen = pBt->valLen;
    pPage->maxLocal = pBt->maxLeaf;
    pPage->minLocal = pBt->minLeaf;
  } else {
H
Hongze Cheng 已提交
459
    SIntHdr *pIntHdr = (SIntHdr *)(pPage->pData);
H
Hongze Cheng 已提交
460 461 462
    pIntHdr->flags = flags;
    pIntHdr->pgno = 0;

H
Hongze Cheng 已提交
463 464 465 466 467
    pPage->kLen = pBt->keyLen;
    pPage->vLen = sizeof(SPgno);
    pPage->maxLocal = pBt->maxLocal;
    pPage->minLocal = pBt->minLocal;
  }
H
Hongze Cheng 已提交
468

H
Hongze Cheng 已提交
469
  return 0;
H
Hongze Cheng 已提交
470 471 472
}

#ifndef TDB_BTREE_BALANCE
H
Hongze Cheng 已提交
473 474 475 476
typedef struct {
  SBTree *pBt;
  SPage  *pParent;
  int     idx;
H
Hongze Cheng 已提交
477
  i8      nOld;
H
Hongze Cheng 已提交
478 479 480 481 482
  SPage  *pOldPages[3];
  i8      nNewPages;
  SPage  *pNewPages[5];
} SBtreeBalanceHelper;

H
Hongze Cheng 已提交
483 484 485 486 487
static int tdbBtreeBalanceDeeper(SBTree *pBt, SPage *pRoot, SPage **ppChild) {
  SPager           *pPager;
  SPage            *pChild;
  SPgno             pgnoChild;
  int               ret;
H
Hongze Cheng 已提交
488
  u8                flags;
H
Hongze Cheng 已提交
489
  SIntHdr          *pIntHdr;
H
Hongze Cheng 已提交
490
  SBtreeInitPageArg zArg;
H
Hongze Cheng 已提交
491
  u8                leaf;
H
Hongze Cheng 已提交
492 493

  pPager = pRoot->pPager;
H
Hongze Cheng 已提交
494
  flags = TDB_BTREE_PAGE_GET_FLAGS(pRoot);
H
Hongze Cheng 已提交
495
  leaf = TDB_BTREE_PAGE_IS_LEAF(flags);
H
Hongze Cheng 已提交
496 497

  // Allocate a new child page
H
Hongze Cheng 已提交
498
  zArg.flags = TDB_FLAG_REMOVE(flags, TDB_BTREE_ROOT);
H
Hongze Cheng 已提交
499 500 501 502 503 504
  zArg.pBt = pBt;
  ret = tdbPagerNewPage(pPager, &pgnoChild, &pChild, tdbBtreeZeroPage, &zArg);
  if (ret < 0) {
    return -1;
  }

H
Hongze Cheng 已提交
505 506 507 508
  if (!leaf) {
    ((SIntHdr *)pChild->pData)->pgno = ((SIntHdr *)(pRoot->pData))->pgno;
  }

H
Hongze Cheng 已提交
509
  // Copy the root page content to the child page
H
Hongze Cheng 已提交
510
  tdbPageCopy(pRoot, pChild);
H
Hongze Cheng 已提交
511 512 513 514 515 516 517 518 519

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

H
Hongze Cheng 已提交
520
  pIntHdr = (SIntHdr *)(pRoot->pData);
H
Hongze Cheng 已提交
521
  pIntHdr->pgno = pgnoChild;
H
Hongze Cheng 已提交
522

H
Hongze Cheng 已提交
523 524 525 526
  *ppChild = pChild;
  return 0;
}

H
Hongze Cheng 已提交
527
static int tdbBtreeBalanceNonRoot(SBTree *pBt, SPage *pParent, int idx) {
H
Hongze Cheng 已提交
528 529 530
  int ret;

  int    nOlds;
H
Hongze Cheng 已提交
531
  SPage *pOlds[3] = {0};
H
Hongze Cheng 已提交
532 533
  SCell *pDivCell[3] = {0};
  int    szDivCell[3];
H
Hongze Cheng 已提交
534
  int    sIdx;
H
Hongze Cheng 已提交
535
  u8     childNotLeaf;
H
Hongze Cheng 已提交
536
  SPgno  rPgno;
H
Hongze Cheng 已提交
537

H
Hongze Cheng 已提交
538
  {  // Find 3 child pages at most to do balance
H
Hongze Cheng 已提交
539 540 541
    int    nCells = TDB_PAGE_TOTAL_CELLS(pParent);
    SCell *pCell;

H
Hongze Cheng 已提交
542 543 544 545 546 547 548 549 550 551 552 553 554 555
    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 已提交
556 557
    for (int i = 0; i < nOlds; i++) {
      ASSERT(sIdx + i <= nCells);
H
Hongze Cheng 已提交
558

H
Hongze Cheng 已提交
559
      SPgno pgno;
H
Hongze Cheng 已提交
560
      if (sIdx + i == nCells) {
H
Hongze Cheng 已提交
561 562 563
        ASSERT(!TDB_BTREE_PAGE_IS_LEAF(TDB_BTREE_PAGE_GET_FLAGS(pParent)));
        pgno = ((SIntHdr *)(pParent->pData))->pgno;
      } else {
H
Hongze Cheng 已提交
564
        pCell = tdbPageGetCell(pParent, sIdx + i);
H
Hongze Cheng 已提交
565 566 567 568 569 570 571 572 573
        pgno = *(SPgno *)pCell;
      }

      ret = tdbPagerFetchPage(pBt->pPager, pgno, pOlds + i, tdbBtreeInitPage, pBt);
      if (ret < 0) {
        ASSERT(0);
        return -1;
      }
    }
H
Hongze Cheng 已提交
574
    // copy the parent key out if child pages are not leaf page
H
Hongze Cheng 已提交
575 576
    childNotLeaf = !TDB_BTREE_PAGE_IS_LEAF(TDB_BTREE_PAGE_GET_FLAGS(pOlds[0]));
    if (childNotLeaf) {
H
Hongze Cheng 已提交
577 578 579 580
      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);
H
Hongze Cheng 已提交
581
          pDivCell[i] = tdbOsMalloc(szDivCell[i]);
H
Hongze Cheng 已提交
582 583
          memcpy(pDivCell[i], pCell, szDivCell[i]);
        }
H
Hongze Cheng 已提交
584

H
Hongze Cheng 已提交
585 586 587
        if (i < nOlds - 1) {
          ((SPgno *)pDivCell[i])[0] = ((SIntHdr *)pOlds[i]->pData)->pgno;
          ((SIntHdr *)pOlds[i]->pData)->pgno = 0;
H
Hongze Cheng 已提交
588
          tdbPageInsertCell(pOlds[i], TDB_PAGE_TOTAL_CELLS(pOlds[i]), pDivCell[i], szDivCell[i], 1);
H
Hongze Cheng 已提交
589
        }
H
Hongze Cheng 已提交
590
      }
H
Hongze Cheng 已提交
591
      rPgno = ((SIntHdr *)pOlds[nOlds - 1]->pData)->pgno;
H
Hongze Cheng 已提交
592
    }
H
Hongze Cheng 已提交
593
    // drop the cells on parent page
H
Hongze Cheng 已提交
594 595 596 597 598 599 600 601
    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 已提交
602 603
  }

H
Hongze Cheng 已提交
604
  int nNews = 0;
H
Hongze Cheng 已提交
605
  struct {
H
Hongze Cheng 已提交
606 607 608 609
    int cnt;
    int size;
    int iPage;
    int oIdx;
H
Hongze Cheng 已提交
610
  } infoNews[5] = {0};
H
Hongze Cheng 已提交
611 612 613

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

H
Hongze Cheng 已提交
614 615 616
    // first loop to find minimum number of pages needed
    for (int oPage = 0; oPage < nOlds; oPage++) {
      SPage *pPage = pOlds[oPage];
H
Hongze Cheng 已提交
617 618
      SCell *pCell;
      int    cellBytes;
H
Hongze Cheng 已提交
619
      int    oIdx;
H
Hongze Cheng 已提交
620

H
Hongze Cheng 已提交
621
      for (oIdx = 0; oIdx < TDB_PAGE_TOTAL_CELLS(pPage); oIdx++) {
H
Hongze Cheng 已提交
622
        pCell = tdbPageGetCell(pPage, oIdx);
H
Hongze Cheng 已提交
623 624
        cellBytes = TDB_BYTES_CELL_TAKEN(pPage, pCell);

H
Hongze Cheng 已提交
625 626
        if (infoNews[nNews].size + cellBytes > TDB_PAGE_USABLE_SIZE(pPage)) {
          // page is full, use a new page
H
Hongze Cheng 已提交
627
          nNews++;
H
Hongze Cheng 已提交
628

H
Hongze Cheng 已提交
629 630 631 632 633 634 635
          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 已提交
636
        }
H
Hongze Cheng 已提交
637 638
        infoNews[nNews].cnt++;
        infoNews[nNews].size += cellBytes;
H
Hongze Cheng 已提交
639
        infoNews[nNews].iPage = oPage;
H
Hongze Cheng 已提交
640
        infoNews[nNews].oIdx = oIdx;
H
Hongze Cheng 已提交
641 642 643
      }
    }

H
Hongze Cheng 已提交
644
    nNews++;
H
Hongze Cheng 已提交
645 646 647

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

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

H
Hongze Cheng 已提交
654
        if (childNotLeaf) {
H
Hongze Cheng 已提交
655
          szLCell = szRCell = tdbBtreeCellSize(pOlds[infoNews[iNew - 1].iPage], pCell);
H
Hongze Cheng 已提交
656
        } else {
H
Hongze Cheng 已提交
657
          szLCell = tdbBtreeCellSize(pOlds[infoNews[iNew - 1].iPage], pCell);
H
Hongze Cheng 已提交
658

H
Hongze Cheng 已提交
659
          int    iPage = infoNews[iNew - 1].iPage;
H
Hongze Cheng 已提交
660
          int    oIdx = infoNews[iNew - 1].oIdx + 1;
H
Hongze Cheng 已提交
661
          SPage *pPage;
H
Hongze Cheng 已提交
662
          for (;;) {
H
Hongze Cheng 已提交
663
            pPage = pOlds[iPage];
H
Hongze Cheng 已提交
664 665 666 667
            if (oIdx < TDB_PAGE_TOTAL_CELLS(pPage)) {
              break;
            }

H
Hongze Cheng 已提交
668
            iPage++;
H
Hongze Cheng 已提交
669 670 671 672 673
            oIdx = 0;
          }

          pCell = tdbPageGetCell(pPage, oIdx);
          szRCell = tdbBtreeCellSize(pPage, pCell);
H
Hongze Cheng 已提交
674 675 676 677 678 679 680 681
        }

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

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

H
Hongze Cheng 已提交
682
        // Move a cell right forward
H
Hongze Cheng 已提交
683 684
        infoNews[iNew - 1].cnt--;
        infoNews[iNew - 1].size -= szLCell;
H
Hongze Cheng 已提交
685
        infoNews[iNew - 1].oIdx--;
H
Hongze Cheng 已提交
686
        for (;;) {
H
Hongze Cheng 已提交
687
          if (infoNews[iNew - 1].oIdx >= 0) {
H
Hongze Cheng 已提交
688 689
            break;
          }
H
Hongze Cheng 已提交
690

H
Hongze Cheng 已提交
691 692
          infoNews[iNew - 1].iPage--;
          infoNews[iNew - 1].oIdx = TDB_PAGE_TOTAL_CELLS(pOlds[infoNews[iNew - 1].iPage]) - 1;
H
Hongze Cheng 已提交
693 694 695
        }

        infoNews[iNew].cnt++;
H
Hongze Cheng 已提交
696
        infoNews[iNew].size += szRCell;
H
Hongze Cheng 已提交
697
      }
H
Hongze Cheng 已提交
698
    }
H
Hongze Cheng 已提交
699 700
  }

H
Hongze Cheng 已提交
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
  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 已提交
722 723

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

H
Hongze Cheng 已提交
726
  {  // Do the real cell distribution
H
Hongze Cheng 已提交
727
    SPage            *pOldsCopy[3] = {0};
H
Hongze Cheng 已提交
728 729 730 731
    SCell            *pCell;
    int               szCell;
    SBtreeInitPageArg iarg;
    int               iNew, nNewCells;
H
Hongze Cheng 已提交
732
    SCellDecoder      cd;
H
Hongze Cheng 已提交
733 734 735 736

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

    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 已提交
755
        ASSERT(iNew < nNews);
H
Hongze Cheng 已提交
756 757 758 759

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

H
Hongze Cheng 已提交
761 762 763 764 765 766 767
          // 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 已提交
768 769
              tdbBtreeDecodeCell(pPage, pCell, &cd);

H
Hongze Cheng 已提交
770
              // TODO: pCell here may be inserted as an overflow cell, handle it
H
Hongze Cheng 已提交
771
              SCell *pNewCell = tdbOsMalloc(cd.kLen + 9);
H
Hongze Cheng 已提交
772 773 774
              int    szNewCell;
              SPgno  pgno;
              pgno = TDB_PAGE_PGNO(pNews[iNew]);
H
Hongze Cheng 已提交
775
              tdbBtreeEncodeCell(pParent, cd.pKey, cd.kLen, (void *)&pgno, sizeof(SPgno), pNewCell, &szNewCell);
H
Hongze Cheng 已提交
776
              tdbPageInsertCell(pParent, sIdx++, pNewCell, szNewCell, 0);
H
Hongze Cheng 已提交
777
              tdbOsFree(pNewCell);
H
Hongze Cheng 已提交
778
            }
H
Hongze Cheng 已提交
779 780

            // move to next new page
H
Hongze Cheng 已提交
781
            iNew++;
H
Hongze Cheng 已提交
782 783 784 785
            nNewCells = 0;
            if (iNew < nNews) {
              tdbBtreeZeroPage(pNews[iNew], &iarg);
            }
H
Hongze Cheng 已提交
786 787 788
          }
        } else {
          ASSERT(childNotLeaf);
H
Hongze Cheng 已提交
789
          ASSERT(iNew < nNews - 1);
H
Hongze Cheng 已提交
790

H
Hongze Cheng 已提交
791 792 793 794
          // set current new page right-most child
          ((SIntHdr *)pNews[iNew]->pData)->pgno = ((SPgno *)pCell)[0];

          // insert to parent as divider cell
H
Hongze Cheng 已提交
795 796 797
          ASSERT(iNew < nNews - 1);
          ((SPgno *)pCell)[0] = TDB_PAGE_PGNO(pNews[iNew]);
          tdbPageInsertCell(pParent, sIdx++, pCell, szCell, 0);
H
Hongze Cheng 已提交
798 799 800 801

          // move to next new page
          iNew++;
          nNewCells = 0;
H
Hongze Cheng 已提交
802 803 804
          if (iNew < nNews) {
            tdbBtreeZeroPage(pNews[iNew], &iarg);
          }
H
Hongze Cheng 已提交
805 806
        }
      }
H
Hongze Cheng 已提交
807
    }
H
Hongze Cheng 已提交
808

H
Hongze Cheng 已提交
809 810 811
    if (childNotLeaf) {
      ASSERT(TDB_PAGE_TOTAL_CELLS(pNews[nNews - 1]) == infoNews[nNews - 1].cnt);
      ((SIntHdr *)(pNews[nNews - 1]->pData))->pgno = rPgno;
H
Hongze Cheng 已提交
812

H
Hongze Cheng 已提交
813 814 815 816 817 818
      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 已提交
819
      }
H
Hongze Cheng 已提交
820 821 822 823 824 825 826
    }

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

H
Hongze Cheng 已提交
827 828
  for (int i = 0; i < 3; i++) {
    if (pDivCell[i]) {
H
Hongze Cheng 已提交
829
      tdbOsFree(pDivCell[i]);
H
Hongze Cheng 已提交
830 831
    }
  }
H
Hongze Cheng 已提交
832

H
Hongze Cheng 已提交
833
  return 0;
H
Hongze Cheng 已提交
834 835
}

H
Hongze Cheng 已提交
836
static int tdbBtreeBalance(SBTC *pBtc) {
H
Hongze Cheng 已提交
837
  int    iPage;
H
Hongze Cheng 已提交
838
  SPage *pParent;
H
Hongze Cheng 已提交
839
  SPage *pPage;
H
Hongze Cheng 已提交
840
  int    ret;
H
Hongze Cheng 已提交
841
  u8     flags;
H
Hongze Cheng 已提交
842 843
  u8     leaf;
  u8     root;
H
Hongze Cheng 已提交
844 845 846

  // Main loop to balance the BTree
  for (;;) {
H
Hongze Cheng 已提交
847 848
    iPage = pBtc->iPage;
    pPage = pBtc->pPage;
H
Hongze Cheng 已提交
849
    flags = TDB_BTREE_PAGE_GET_FLAGS(pPage);
H
Hongze Cheng 已提交
850 851
    leaf = TDB_BTREE_PAGE_IS_LEAF(flags);
    root = TDB_BTREE_PAGE_IS_ROOT(flags);
H
Hongze Cheng 已提交
852

H
Hongze Cheng 已提交
853 854
    // when the page is not overflow and not too empty, the balance work
    // is finished. Just break out the balance loop.
H
Hongze Cheng 已提交
855
    if (pPage->nOverflow == 0 /* TODO: && pPage->nFree <= */) {
H
Hongze Cheng 已提交
856 857 858 859
      break;
    }

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

H
Hongze Cheng 已提交
864
      ret = tdbBtreeBalanceDeeper(pBtc->pBt, pPage, &(pBtc->pgStack[1]));
H
Hongze Cheng 已提交
865 866 867 868
      if (ret < 0) {
        return -1;
      }

H
Hongze Cheng 已提交
869 870 871 872 873
      pBtc->idx = 0;
      pBtc->idxStack[0] = 0;
      pBtc->pgStack[0] = pBtc->pPage;
      pBtc->iPage = 1;
      pBtc->pPage = pBtc->pgStack[1];
H
Hongze Cheng 已提交
874
    } else {
H
Hongze Cheng 已提交
875
      // Generalized balance step
H
Hongze Cheng 已提交
876
      pParent = pBtc->pgStack[iPage - 1];
H
Hongze Cheng 已提交
877

H
Hongze Cheng 已提交
878
      ret = tdbBtreeBalanceNonRoot(pBtc->pBt, pParent, pBtc->idxStack[pBtc->iPage - 1]);
H
Hongze Cheng 已提交
879 880 881 882
      if (ret < 0) {
        return -1;
      }

H
Hongze Cheng 已提交
883 884
      pBtc->iPage--;
      pBtc->pPage = pBtc->pgStack[pBtc->iPage];
H
Hongze Cheng 已提交
885 886 887 888 889
    }
  }

  return 0;
}
H
Hongze Cheng 已提交
890 891
#endif

H
Hongze Cheng 已提交
892
#ifndef TDB_BTREE_CELL  // =========================================================
H
Hongze Cheng 已提交
893
static int tdbBtreeEncodePayload(SPage *pPage, u8 *pPayload, const void *pKey, int kLen, const void *pVal, int vLen,
H
Hongze Cheng 已提交
894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
                                 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 已提交
923
// TODO: allow vLen = 0
H
Hongze Cheng 已提交
924 925
static int tdbBtreeEncodeCell(SPage *pPage, const void *pKey, int kLen, const void *pVal, int vLen, SCell *pCell,
                              int *szCell) {
H
Hongze Cheng 已提交
926
  u8  flags;
H
Hongze Cheng 已提交
927 928 929 930
  u8  leaf;
  int nHeader;
  int nPayload;
  int ret;
H
Hongze Cheng 已提交
931 932 933 934

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

H
Hongze Cheng 已提交
935 936
  nPayload = 0;
  nHeader = 0;
H
Hongze Cheng 已提交
937
  flags = TDB_BTREE_PAGE_GET_FLAGS(pPage);
H
Hongze Cheng 已提交
938
  leaf = TDB_BTREE_PAGE_IS_LEAF(flags);
H
Hongze Cheng 已提交
939

H
Hongze Cheng 已提交
940
  // 1. Encode Header part
H
Hongze Cheng 已提交
941 942 943 944 945 946 947 948
  /* 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 已提交
949
  /* Encode kLen if need */
H
Hongze Cheng 已提交
950
  if (pPage->kLen == TDB_VARIANT_LEN) {
H
Hongze Cheng 已提交
951
    nHeader += tdbPutVarInt(pCell + nHeader, kLen);
H
Hongze Cheng 已提交
952 953
  }

H
Hongze Cheng 已提交
954
  /* Encode vLen if need */
H
Hongze Cheng 已提交
955
  if (pPage->vLen == TDB_VARIANT_LEN) {
H
Hongze Cheng 已提交
956
    nHeader += tdbPutVarInt(pCell + nHeader, vLen);
H
Hongze Cheng 已提交
957 958
  }

H
Hongze Cheng 已提交
959
  // 2. Encode payload part
H
Hongze Cheng 已提交
960
  if (leaf && vLen > 0) {
H
Hongze Cheng 已提交
961 962 963 964 965 966 967
    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 已提交
968 969
  }

H
Hongze Cheng 已提交
970
  *szCell = nHeader + nPayload;
H
Hongze Cheng 已提交
971 972 973
  return 0;
}

H
Hongze Cheng 已提交
974 975 976 977
static int tdbBtreeDecodePayload(SPage *pPage, const u8 *pPayload, SCellDecoder *pDecoder) {
  int nPayload;

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

H
Hongze Cheng 已提交
979 980
  if (pDecoder->pVal) {
    nPayload = pDecoder->kLen + pDecoder->vLen;
H
Hongze Cheng 已提交
981
  } else {
H
Hongze Cheng 已提交
982
    nPayload = pDecoder->kLen;
H
Hongze Cheng 已提交
983 984
  }

H
Hongze Cheng 已提交
985 986 987
  if (nPayload <= pPage->maxLocal) {
    // General case without overflow
    pDecoder->pKey = (void *)pPayload;
H
Hongze Cheng 已提交
988 989
    if (!pDecoder->pVal) {
      pDecoder->pVal = (void *)(pPayload + pDecoder->kLen);
H
Hongze Cheng 已提交
990
    }
H
Hongze Cheng 已提交
991
  } else {
H
Hongze Cheng 已提交
992 993
    // TODO: handle overflow case
    ASSERT(0);
H
Hongze Cheng 已提交
994 995
  }

H
Hongze Cheng 已提交
996 997 998
  return 0;
}

H
Hongze Cheng 已提交
999
// TODO: here has problem
H
Hongze Cheng 已提交
1000
static int tdbBtreeDecodeCell(SPage *pPage, const SCell *pCell, SCellDecoder *pDecoder) {
H
Hongze Cheng 已提交
1001
  u8  flags;
H
Hongze Cheng 已提交
1002 1003 1004 1005 1006
  u8  leaf;
  int nHeader;
  int ret;

  nHeader = 0;
H
Hongze Cheng 已提交
1007
  flags = TDB_BTREE_PAGE_GET_FLAGS(pPage);
H
Hongze Cheng 已提交
1008 1009
  leaf = TDB_BTREE_PAGE_IS_LEAF(flags);

H
Hongze Cheng 已提交
1010 1011 1012 1013 1014 1015 1016
  // Clear the state of decoder
  pDecoder->kLen = -1;
  pDecoder->pKey = NULL;
  pDecoder->vLen = -1;
  pDecoder->pVal = NULL;
  pDecoder->pgno = 0;

H
Hongze Cheng 已提交
1017
  // 1. Decode header part
H
Hongze Cheng 已提交
1018 1019 1020 1021 1022 1023 1024 1025
  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 已提交
1026 1027 1028 1029 1030 1031 1032 1033
  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 已提交
1034
  } else {
H
Hongze Cheng 已提交
1035 1036
    pDecoder->vLen = pPage->vLen;
  }
H
Hongze Cheng 已提交
1037

H
Hongze Cheng 已提交
1038 1039 1040 1041
  // 2. Decode payload part
  ret = tdbBtreeDecodePayload(pPage, pCell + nHeader, pDecoder);
  if (ret < 0) {
    return -1;
H
Hongze Cheng 已提交
1042 1043 1044 1045 1046
  }

  return 0;
}

H
Hongze Cheng 已提交
1047
static int tdbBtreeCellSize(const SPage *pPage, SCell *pCell) {
H
Hongze Cheng 已提交
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
  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
H
Hongze Cheng 已提交
1081

H
Hongze Cheng 已提交
1082 1083 1084 1085 1086
int tdbBtcOpen(SBTC *pBtc, SBTree *pBt) {
  pBtc->pBt = pBt;
  pBtc->iPage = -1;
  pBtc->pPage = NULL;
  pBtc->idx = -1;
H
Hongze Cheng 已提交
1087 1088 1089 1090

  return 0;
}

H
Hongze Cheng 已提交
1091
int tdbBtcMoveToFirst(SBTC *pBtc) {
H
Hongze Cheng 已提交
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
  int     ret;
  SBTree *pBt;
  SPager *pPager;
  u8      flags;
  SCell  *pCell;
  SPgno   pgno;

  pBt = pBtc->pBt;
  pPager = pBt->pPager;

  if (pBtc->iPage < 0) {
    // move a clean cursor
    ret = tdbPagerFetchPage(pPager, pBt->root, &(pBtc->pPage), tdbBtreeInitPage, pBt);
    if (ret < 0) {
      ASSERT(0);
      return -1;
    }

    pBtc->iPage = 0;
    pBtc->idx = 0;
  } else {
    // move from a position
    ASSERT(0);
  }

  // move downward
  for (;;) {
    flags = TDB_BTREE_PAGE_GET_FLAGS(pBtc->pPage);

    if (TDB_BTREE_PAGE_IS_LEAF(flags)) break;

    pCell = tdbPageGetCell(pBtc->pPage, 0);
    pgno = *(SPgno *)pCell;

H
Hongze Cheng 已提交
1126
    ret = tdbBtcMoveDownward(pBtc, pgno);
H
Hongze Cheng 已提交
1127 1128 1129 1130 1131 1132 1133 1134
    if (ret < 0) {
      ASSERT(0);
      return -1;
    }

    pBtc->idx = 0;
  }

H
Hongze Cheng 已提交
1135 1136 1137 1138
  return 0;
}

int tdbBtcMoveToLast(SBTC *pBtc) {
H
Hongze Cheng 已提交
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
  int     ret;
  SBTree *pBt;
  SPager *pPager;
  u8      flags;
  SPgno   pgno;

  pBt = pBtc->pBt;
  pPager = pBt->pPager;

  if (pBtc->iPage < 0) {
    // move a clean cursor
    ret = tdbPagerFetchPage(pPager, pBt->root, &(pBtc->pPage), tdbBtreeInitPage, pBt);
    if (ret < 0) {
      ASSERT(0);
      return -1;
    }

    pBtc->iPage = 0;
  } else {
    // move from a position
    ASSERT(0);
  }

  // move downward
  for (;;) {
    flags = TDB_BTREE_PAGE_GET_FLAGS(pBtc->pPage);

    if (TDB_BTREE_PAGE_IS_LEAF(flags)) {
      // TODO: handle empty case
      ASSERT(TDB_PAGE_TOTAL_CELLS(pBtc->pPage) > 0);
      pBtc->idx = TDB_PAGE_TOTAL_CELLS(pBtc->pPage) - 1;
      break;
    } else {
      pBtc->idx = TDB_PAGE_TOTAL_CELLS(pBtc->pPage);
      pgno = ((SIntHdr *)pBtc->pPage->pData)->pgno;

H
Hongze Cheng 已提交
1175
      ret = tdbBtcMoveDownward(pBtc, pgno);
H
Hongze Cheng 已提交
1176 1177 1178 1179 1180 1181 1182
      if (ret < 0) {
        ASSERT(0);
        return -1;
      }
    }
  }

H
Hongze Cheng 已提交
1183 1184 1185 1186 1187 1188 1189 1190 1191
  return 0;
}

int tdbBtcMoveTo(SBTC *pBtc, const void *pKey, int kLen) {
  // TODO
  return 0;
}

int tdbBtreeNext(SBTC *pBtc, void **ppKey, int *kLen, void **ppVal, int *vLen) {
H
Hongze Cheng 已提交
1192 1193 1194 1195 1196
  SCell       *pCell;
  SCellDecoder cd;
  void        *pKey, *pVal;
  int          ret;

H
Hongze Cheng 已提交
1197
  if (pBtc->idx < 0) {
H
Hongze Cheng 已提交
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
    return -1;
  }

  pCell = tdbPageGetCell(pBtc->pPage, pBtc->idx);

  tdbBtreeDecodeCell(pBtc->pPage, pCell, &cd);

  pKey = TDB_REALLOC(*ppKey, cd.kLen);
  if (pKey == NULL) {
    return -1;
  }

  // TODO: vLen may be zero
  pVal = TDB_REALLOC(*ppVal, cd.vLen);
  if (pVal == NULL) {
    TDB_FREE(pKey);
    return -1;
  }

  *ppKey = pKey;
  *ppVal = pVal;

  *kLen = cd.kLen;
  *vLen = cd.vLen;

  memcpy(pKey, cd.pKey, cd.kLen);
  memcpy(pVal, cd.pVal, cd.vLen);

  ret = tdbBtcMoveToNext(pBtc);

  return 0;
}

static int tdbBtcMoveToNext(SBTC *pBtc) {
H
Hongze Cheng 已提交
1232 1233 1234 1235 1236 1237
  int    nCells;
  SPgno  pgno;
  SCell *pCell;
  u8     flags;

  ASSERT(TDB_BTREE_PAGE_IS_LEAF(TDB_BTREE_PAGE_GET_FLAGS(pBtc->pPage)));
H
Hongze Cheng 已提交
1238 1239 1240

  if (pBtc->idx < 0) return -1;

H
Hongze Cheng 已提交
1241
  pBtc->idx++;
H
Hongze Cheng 已提交
1242 1243 1244 1245
  if (pBtc->idx < TDB_PAGE_TOTAL_CELLS(pBtc->pPage)) {
    return 0;
  }

H
Hongze Cheng 已提交
1246 1247 1248 1249 1250
  if (pBtc->iPage == 0) {
    pBtc->idx = -1;
    return 0;
  }

H
Hongze Cheng 已提交
1251 1252
  // Move upward
  for (;;) {
H
Hongze Cheng 已提交
1253 1254 1255 1256 1257 1258 1259
    tdbBtcMoveUpward(pBtc);
    pBtc->idx++;

    nCells = TDB_PAGE_TOTAL_CELLS(pBtc->pPage);
    if (pBtc->idx <= nCells) {
      break;
    }
H
Hongze Cheng 已提交
1260

H
Hongze Cheng 已提交
1261 1262 1263 1264
    if (pBtc->iPage == 0) {
      pBtc->idx = -1;
      return 0;
    }
H
Hongze Cheng 已提交
1265 1266 1267 1268
  }

  // Move downward
  for (;;) {
H
Hongze Cheng 已提交
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
    nCells = TDB_PAGE_TOTAL_CELLS(pBtc->pPage);
    if (pBtc->idx < nCells) {
      pCell = tdbPageGetCell(pBtc->pPage, pBtc->idx);
      pgno = *(SPgno *)pCell;
    } else {
      pgno = ((SIntHdr *)pBtc->pPage->pData)->pgno;
    }

    tdbBtcMoveDownward(pBtc, pgno);
    pBtc->idx = 0;

    flags = TDB_BTREE_PAGE_GET_FLAGS(pBtc->pPage);
    if (TDB_BTREE_PAGE_IS_LEAF(flags)) {
      break;
    }
H
Hongze Cheng 已提交
1284 1285
  }

H
Hongze Cheng 已提交
1286 1287 1288 1289 1290 1291
  return 0;
}

int tdbBtcClose(SBTC *pBtc) {
  // TODO
  return 0;
H
Hongze Cheng 已提交
1292 1293
}

H
Hongze Cheng 已提交
1294
static int tdbBtcMoveDownward(SBTC *pBtc, SPgno pgno) {
H
Hongze Cheng 已提交
1295 1296
  int ret;

H
Hongze Cheng 已提交
1297 1298 1299 1300 1301
  pBtc->pgStack[pBtc->iPage] = pBtc->pPage;
  pBtc->idxStack[pBtc->iPage] = pBtc->idx;
  pBtc->iPage++;
  pBtc->pPage = NULL;
  pBtc->idx = -1;
H
Hongze Cheng 已提交
1302

H
Hongze Cheng 已提交
1303
  ret = tdbPagerFetchPage(pBtc->pBt->pPager, pgno, &pBtc->pPage, tdbBtreeInitPage, pBtc->pBt);
H
Hongze Cheng 已提交
1304 1305 1306 1307 1308 1309 1310 1311
  if (ret < 0) {
    ASSERT(0);
  }

  return 0;
}

static int tdbBtcMoveUpward(SBTC *pBtc) {
H
Hongze Cheng 已提交
1312 1313 1314 1315 1316 1317 1318 1319
  if (pBtc->iPage == 0) return -1;

  // tdbPagerReturnPage(pBtc->pBt->pPager, pBtc->pPage);

  pBtc->iPage--;
  pBtc->pPage = pBtc->pgStack[pBtc->iPage];
  pBtc->idx = pBtc->idxStack[pBtc->iPage];

H
Hongze Cheng 已提交
1320
  return 0;
H
Hongze Cheng 已提交
1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
}

#ifndef NODEBUG
typedef struct {
  SPgno pgno;
  u8    root;
  u8    leaf;
  SPgno rChild;
  int   nCells;
  int   nOvfl;
} SBtPageInfo;

SBtPageInfo btPageInfos[20];

void tdbBtPageInfo(SPage *pPage, int idx) {
  u8           flags;
  SBtPageInfo *pBtPageInfo;

  pBtPageInfo = btPageInfos + idx;

  pBtPageInfo->pgno = TDB_PAGE_PGNO(pPage);

  flags = TDB_BTREE_PAGE_GET_FLAGS(pPage);

  pBtPageInfo->root = TDB_BTREE_PAGE_IS_ROOT(flags);
  pBtPageInfo->leaf = TDB_BTREE_PAGE_IS_LEAF(flags);

  pBtPageInfo->rChild = 0;
  if (!pBtPageInfo->leaf) {
    pBtPageInfo->rChild = *(SPgno *)(pPage->pData + 1);
  }

  pBtPageInfo->nCells = TDB_PAGE_TOTAL_CELLS(pPage) - pPage->nOverflow;
  pBtPageInfo->nOvfl = pPage->nOverflow;
}
#endif