tdbBtree.c 31.8 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
#define TDB_BTREE_ROOT 0x1
#define TDB_BTREE_LEAF 0x2

H
Hongze Cheng 已提交
21
struct SBTree {
H
more  
Hongze Cheng 已提交
22 23 24
  SPgno          root;
  int            keyLen;
  int            valLen;
H
Hongze Cheng 已提交
25
  SPager        *pPager;
H
more  
Hongze Cheng 已提交
26
  FKeyComparator kcmpr;
H
Hongze Cheng 已提交
27
  int            pageSize;
H
more  
Hongze Cheng 已提交
28 29 30 31
  int            maxLocal;
  int            minLocal;
  int            maxLeaf;
  int            minLeaf;
H
Hongze Cheng 已提交
32
  u8            *pTmp;
H
Hongze Cheng 已提交
33 34
};

H
Hongze Cheng 已提交
35 36
#define TDB_BTREE_PAGE_COMMON_HDR u8 flags;

H
Hongze Cheng 已提交
37
#define TDB_BTREE_PAGE_GET_FLAGS(PAGE) (PAGE)->pData[0]
H
Hongze Cheng 已提交
38
#define TDB_BTREE_PAGE_SET_FLAGS(PAGE, flags) ((PAGE)->pData[0] = (flags))
H
refact  
Hongze Cheng 已提交
39 40 41 42 43
#define TDB_BTREE_PAGE_IS_ROOT(PAGE) (TDB_BTREE_PAGE_GET_FLAGS(PAGE) & TDB_BTREE_ROOT)
#define TDB_BTREE_PAGE_IS_LEAF(PAGE) (TDB_BTREE_PAGE_GET_FLAGS(PAGE) & TDB_BTREE_LEAF)
#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 已提交
44 45 46 47 48

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  pCell = pBt->pTmp;

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

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

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

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

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

H
Hongze Cheng 已提交
200
  tdbBtcOpen(&btc, pBt);
H
Hongze Cheng 已提交
201

H
refact  
Hongze Cheng 已提交
202
  tdbBtcMoveTo(&btc, pKey, kLen, &cret);
H
Hongze Cheng 已提交
203 204 205 206 207 208 209 210 211

  if (cret) {
    return cret;
  }

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

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

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

222 223 224 225 226 227 228 229 230 231
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);

H
refact  
Hongze Cheng 已提交
232
  tdbBtcMoveTo(&btc, pKey, kLen, &cret);
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
  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;

H
Hongze Cheng 已提交
253 254 255
  memcpy(*ppKey, cd.pKey, cd.kLen);
  memcpy(*ppVal, cd.pVal, cd.vLen);

256 257 258
  return 0;
}

H
Hongze Cheng 已提交
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
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 已提交
277 278 279 280 281 282 283 284 285 286
}

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 已提交
287
    // 1. TODO: Search the main DB to check if the DB exists
H
Hongze Cheng 已提交
288 289 290 291 292 293 294 295 296
    pgno = 0;
  }

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

  // Try to create a new database
H
Hongze Cheng 已提交
297
  SBtreeInitPageArg zArg = {.flags = TDB_BTREE_ROOT | TDB_BTREE_LEAF, .pBt = pBt};
H
Hongze Cheng 已提交
298 299 300 301 302 303
  ret = tdbPagerNewPage(pBt->pPager, &pgno, &pPage, tdbBtreeZeroPage, &zArg);
  if (ret < 0) {
    return -1;
  }

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

H
Hongze Cheng 已提交
305 306
  ASSERT(pgno != 0);
  pBt->root = pgno;
H
Hongze Cheng 已提交
307

H
Hongze Cheng 已提交
308 309 310
  return 0;
}

H
Hongze Cheng 已提交
311
static int tdbBtreeInitPage(SPage *pPage, void *arg) {
H
Hongze Cheng 已提交
312
  SBTree *pBt;
H
Hongze Cheng 已提交
313
  u8      flags;
H
Hongze Cheng 已提交
314
  u8      isLeaf;
H
Hongze Cheng 已提交
315

H
Hongze Cheng 已提交
316 317
  pBt = (SBTree *)arg;
  flags = TDB_BTREE_PAGE_GET_FLAGS(pPage);
H
refact  
Hongze Cheng 已提交
318
  isLeaf = TDB_BTREE_PAGE_IS_LEAF(pPage);
H
Hongze Cheng 已提交
319

H
Hongze Cheng 已提交
320
  ASSERT(flags == TDB_BTREE_PAGE_GET_FLAGS(pPage));
H
Hongze Cheng 已提交
321

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

H
Hongze Cheng 已提交
324 325
  TDB_BTREE_ASSERT_FLAG(flags);

H
Hongze Cheng 已提交
326
  if (isLeaf) {
H
Hongze Cheng 已提交
327 328 329 330 331 332 333 334 335 336
    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 已提交
337 338 339 340

  return 0;
}

H
Hongze Cheng 已提交
341
static int tdbBtreeZeroPage(SPage *pPage, void *arg) {
H
Hongze Cheng 已提交
342
  u8      flags;
H
Hongze Cheng 已提交
343
  SBTree *pBt;
H
refact  
Hongze Cheng 已提交
344
  u8      leaf;
H
Hongze Cheng 已提交
345

H
Hongze Cheng 已提交
346 347
  flags = ((SBtreeInitPageArg *)arg)->flags;
  pBt = ((SBtreeInitPageArg *)arg)->pBt;
H
refact  
Hongze Cheng 已提交
348
  leaf = flags & TDB_BTREE_LEAF;
H
Hongze Cheng 已提交
349

H
refact  
Hongze Cheng 已提交
350
  tdbPageZero(pPage, leaf ? sizeof(SLeafHdr) : sizeof(SIntHdr), tdbBtreeCellSize);
H
Hongze Cheng 已提交
351

H
refact  
Hongze Cheng 已提交
352
  if (leaf) {
H
Hongze Cheng 已提交
353
    SLeafHdr *pLeafHdr = (SLeafHdr *)(pPage->pData);
H
Hongze Cheng 已提交
354 355
    pLeafHdr->flags = flags;

H
Hongze Cheng 已提交
356 357 358 359 360
    pPage->kLen = pBt->keyLen;
    pPage->vLen = pBt->valLen;
    pPage->maxLocal = pBt->maxLeaf;
    pPage->minLocal = pBt->minLeaf;
  } else {
H
Hongze Cheng 已提交
361
    SIntHdr *pIntHdr = (SIntHdr *)(pPage->pData);
H
Hongze Cheng 已提交
362 363 364
    pIntHdr->flags = flags;
    pIntHdr->pgno = 0;

H
Hongze Cheng 已提交
365 366 367 368 369
    pPage->kLen = pBt->keyLen;
    pPage->vLen = sizeof(SPgno);
    pPage->maxLocal = pBt->maxLocal;
    pPage->minLocal = pBt->minLocal;
  }
H
Hongze Cheng 已提交
370

H
Hongze Cheng 已提交
371
  return 0;
H
Hongze Cheng 已提交
372 373 374
}

#ifndef TDB_BTREE_BALANCE
H
Hongze Cheng 已提交
375 376 377 378
typedef struct {
  SBTree *pBt;
  SPage  *pParent;
  int     idx;
H
Hongze Cheng 已提交
379
  i8      nOld;
H
Hongze Cheng 已提交
380 381 382 383 384
  SPage  *pOldPages[3];
  i8      nNewPages;
  SPage  *pNewPages[5];
} SBtreeBalanceHelper;

H
Hongze Cheng 已提交
385 386 387 388 389
static int tdbBtreeBalanceDeeper(SBTree *pBt, SPage *pRoot, SPage **ppChild) {
  SPager           *pPager;
  SPage            *pChild;
  SPgno             pgnoChild;
  int               ret;
H
Hongze Cheng 已提交
390
  u8                flags;
H
Hongze Cheng 已提交
391
  SIntHdr          *pIntHdr;
H
Hongze Cheng 已提交
392
  SBtreeInitPageArg zArg;
H
Hongze Cheng 已提交
393
  u8                leaf;
H
Hongze Cheng 已提交
394 395

  pPager = pRoot->pPager;
H
Hongze Cheng 已提交
396
  flags = TDB_BTREE_PAGE_GET_FLAGS(pRoot);
H
refact  
Hongze Cheng 已提交
397
  leaf = TDB_BTREE_PAGE_IS_LEAF(pRoot);
H
Hongze Cheng 已提交
398 399

  // Allocate a new child page
H
Hongze Cheng 已提交
400
  zArg.flags = TDB_FLAG_REMOVE(flags, TDB_BTREE_ROOT);
H
Hongze Cheng 已提交
401 402 403 404 405 406
  zArg.pBt = pBt;
  ret = tdbPagerNewPage(pPager, &pgnoChild, &pChild, tdbBtreeZeroPage, &zArg);
  if (ret < 0) {
    return -1;
  }

H
Hongze Cheng 已提交
407 408 409 410
  if (!leaf) {
    ((SIntHdr *)pChild->pData)->pgno = ((SIntHdr *)(pRoot->pData))->pgno;
  }

H
Hongze Cheng 已提交
411
  // Copy the root page content to the child page
H
Hongze Cheng 已提交
412
  tdbPageCopy(pRoot, pChild);
H
Hongze Cheng 已提交
413 414 415 416 417 418 419 420 421

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

H
Hongze Cheng 已提交
422
  pIntHdr = (SIntHdr *)(pRoot->pData);
H
Hongze Cheng 已提交
423
  pIntHdr->pgno = pgnoChild;
H
Hongze Cheng 已提交
424

H
Hongze Cheng 已提交
425 426 427 428
  *ppChild = pChild;
  return 0;
}

H
Hongze Cheng 已提交
429
static int tdbBtreeBalanceNonRoot(SBTree *pBt, SPage *pParent, int idx) {
H
Hongze Cheng 已提交
430 431 432
  int ret;

  int    nOlds;
H
Hongze Cheng 已提交
433
  SPage *pOlds[3] = {0};
H
Hongze Cheng 已提交
434 435
  SCell *pDivCell[3] = {0};
  int    szDivCell[3];
H
Hongze Cheng 已提交
436
  int    sIdx;
H
Hongze Cheng 已提交
437
  u8     childNotLeaf;
H
Hongze Cheng 已提交
438
  SPgno  rPgno;
H
Hongze Cheng 已提交
439

H
Hongze Cheng 已提交
440
  {  // Find 3 child pages at most to do balance
H
Hongze Cheng 已提交
441 442 443
    int    nCells = TDB_PAGE_TOTAL_CELLS(pParent);
    SCell *pCell;

H
Hongze Cheng 已提交
444 445 446 447 448 449 450 451 452 453 454 455 456 457
    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 已提交
458 459
    for (int i = 0; i < nOlds; i++) {
      ASSERT(sIdx + i <= nCells);
H
Hongze Cheng 已提交
460

H
Hongze Cheng 已提交
461
      SPgno pgno;
H
Hongze Cheng 已提交
462
      if (sIdx + i == nCells) {
H
refact  
Hongze Cheng 已提交
463
        ASSERT(!TDB_BTREE_PAGE_IS_LEAF(pParent));
H
Hongze Cheng 已提交
464 465
        pgno = ((SIntHdr *)(pParent->pData))->pgno;
      } else {
H
Hongze Cheng 已提交
466
        pCell = tdbPageGetCell(pParent, sIdx + i);
H
Hongze Cheng 已提交
467 468 469 470 471 472 473 474 475
        pgno = *(SPgno *)pCell;
      }

      ret = tdbPagerFetchPage(pBt->pPager, pgno, pOlds + i, tdbBtreeInitPage, pBt);
      if (ret < 0) {
        ASSERT(0);
        return -1;
      }
    }
H
Hongze Cheng 已提交
476
    // copy the parent key out if child pages are not leaf page
H
refact  
Hongze Cheng 已提交
477
    childNotLeaf = !TDB_BTREE_PAGE_IS_LEAF(pOlds[0]);
H
Hongze Cheng 已提交
478
    if (childNotLeaf) {
H
Hongze Cheng 已提交
479 480 481 482
      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 已提交
483
          pDivCell[i] = tdbOsMalloc(szDivCell[i]);
H
Hongze Cheng 已提交
484 485
          memcpy(pDivCell[i], pCell, szDivCell[i]);
        }
H
Hongze Cheng 已提交
486

H
Hongze Cheng 已提交
487 488 489
        if (i < nOlds - 1) {
          ((SPgno *)pDivCell[i])[0] = ((SIntHdr *)pOlds[i]->pData)->pgno;
          ((SIntHdr *)pOlds[i]->pData)->pgno = 0;
H
Hongze Cheng 已提交
490
          tdbPageInsertCell(pOlds[i], TDB_PAGE_TOTAL_CELLS(pOlds[i]), pDivCell[i], szDivCell[i], 1);
H
Hongze Cheng 已提交
491
        }
H
Hongze Cheng 已提交
492
      }
H
Hongze Cheng 已提交
493
      rPgno = ((SIntHdr *)pOlds[nOlds - 1]->pData)->pgno;
H
Hongze Cheng 已提交
494
    }
H
Hongze Cheng 已提交
495
    // drop the cells on parent page
H
Hongze Cheng 已提交
496 497 498 499 500 501 502 503
    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 已提交
504 505
  }

H
Hongze Cheng 已提交
506
  int nNews = 0;
H
Hongze Cheng 已提交
507
  struct {
H
Hongze Cheng 已提交
508 509 510 511
    int cnt;
    int size;
    int iPage;
    int oIdx;
H
Hongze Cheng 已提交
512
  } infoNews[5] = {0};
H
Hongze Cheng 已提交
513 514 515

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

H
Hongze Cheng 已提交
516 517 518
    // first loop to find minimum number of pages needed
    for (int oPage = 0; oPage < nOlds; oPage++) {
      SPage *pPage = pOlds[oPage];
H
Hongze Cheng 已提交
519 520
      SCell *pCell;
      int    cellBytes;
H
Hongze Cheng 已提交
521
      int    oIdx;
H
Hongze Cheng 已提交
522

H
Hongze Cheng 已提交
523
      for (oIdx = 0; oIdx < TDB_PAGE_TOTAL_CELLS(pPage); oIdx++) {
H
Hongze Cheng 已提交
524
        pCell = tdbPageGetCell(pPage, oIdx);
H
Hongze Cheng 已提交
525 526
        cellBytes = TDB_BYTES_CELL_TAKEN(pPage, pCell);

H
Hongze Cheng 已提交
527 528
        if (infoNews[nNews].size + cellBytes > TDB_PAGE_USABLE_SIZE(pPage)) {
          // page is full, use a new page
H
Hongze Cheng 已提交
529
          nNews++;
H
Hongze Cheng 已提交
530

H
Hongze Cheng 已提交
531 532 533 534 535 536 537
          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 已提交
538
        }
H
Hongze Cheng 已提交
539 540
        infoNews[nNews].cnt++;
        infoNews[nNews].size += cellBytes;
H
Hongze Cheng 已提交
541
        infoNews[nNews].iPage = oPage;
H
Hongze Cheng 已提交
542
        infoNews[nNews].oIdx = oIdx;
H
Hongze Cheng 已提交
543 544 545
      }
    }

H
Hongze Cheng 已提交
546
    nNews++;
H
Hongze Cheng 已提交
547 548 549

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

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

H
Hongze Cheng 已提交
556
        if (childNotLeaf) {
H
Hongze Cheng 已提交
557
          szLCell = szRCell = tdbBtreeCellSize(pOlds[infoNews[iNew - 1].iPage], pCell);
H
Hongze Cheng 已提交
558
        } else {
H
Hongze Cheng 已提交
559
          szLCell = tdbBtreeCellSize(pOlds[infoNews[iNew - 1].iPage], pCell);
H
Hongze Cheng 已提交
560

H
Hongze Cheng 已提交
561
          int    iPage = infoNews[iNew - 1].iPage;
H
Hongze Cheng 已提交
562
          int    oIdx = infoNews[iNew - 1].oIdx + 1;
H
Hongze Cheng 已提交
563
          SPage *pPage;
H
Hongze Cheng 已提交
564
          for (;;) {
H
Hongze Cheng 已提交
565
            pPage = pOlds[iPage];
H
Hongze Cheng 已提交
566 567 568 569
            if (oIdx < TDB_PAGE_TOTAL_CELLS(pPage)) {
              break;
            }

H
Hongze Cheng 已提交
570
            iPage++;
H
Hongze Cheng 已提交
571 572 573 574 575
            oIdx = 0;
          }

          pCell = tdbPageGetCell(pPage, oIdx);
          szRCell = tdbBtreeCellSize(pPage, pCell);
H
Hongze Cheng 已提交
576 577 578 579 580 581 582 583
        }

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

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

H
Hongze Cheng 已提交
584
        // Move a cell right forward
H
Hongze Cheng 已提交
585 586
        infoNews[iNew - 1].cnt--;
        infoNews[iNew - 1].size -= szLCell;
H
Hongze Cheng 已提交
587
        infoNews[iNew - 1].oIdx--;
H
Hongze Cheng 已提交
588
        for (;;) {
H
Hongze Cheng 已提交
589
          if (infoNews[iNew - 1].oIdx >= 0) {
H
Hongze Cheng 已提交
590 591
            break;
          }
H
Hongze Cheng 已提交
592

H
Hongze Cheng 已提交
593 594
          infoNews[iNew - 1].iPage--;
          infoNews[iNew - 1].oIdx = TDB_PAGE_TOTAL_CELLS(pOlds[infoNews[iNew - 1].iPage]) - 1;
H
Hongze Cheng 已提交
595 596 597
        }

        infoNews[iNew].cnt++;
H
Hongze Cheng 已提交
598
        infoNews[iNew].size += szRCell;
H
Hongze Cheng 已提交
599
      }
H
Hongze Cheng 已提交
600
    }
H
Hongze Cheng 已提交
601 602
  }

H
Hongze Cheng 已提交
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
  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 已提交
624 625

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

H
Hongze Cheng 已提交
628
  {  // Do the real cell distribution
H
Hongze Cheng 已提交
629
    SPage            *pOldsCopy[3] = {0};
H
Hongze Cheng 已提交
630 631 632 633
    SCell            *pCell;
    int               szCell;
    SBtreeInitPageArg iarg;
    int               iNew, nNewCells;
H
Hongze Cheng 已提交
634
    SCellDecoder      cd;
H
Hongze Cheng 已提交
635 636 637 638

    iarg.pBt = pBt;
    iarg.flags = TDB_BTREE_PAGE_GET_FLAGS(pOlds[0]);
    for (int i = 0; i < nOlds; i++) {
H
Hongze Cheng 已提交
639
      tdbPageCreate(pOlds[0]->pageSize, &pOldsCopy[i], NULL, NULL);
H
Hongze Cheng 已提交
640 641 642 643 644
      tdbBtreeZeroPage(pOldsCopy[i], &iarg);
      tdbPageCopy(pOlds[i], pOldsCopy[i]);
    }
    iNew = 0;
    nNewCells = 0;
H
Hongze Cheng 已提交
645
    tdbBtreeZeroPage(pNews[iNew], &iarg);
H
Hongze Cheng 已提交
646 647 648 649 650 651 652 653 654 655 656

    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 已提交
657
        ASSERT(iNew < nNews);
H
Hongze Cheng 已提交
658 659 660 661

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

H
Hongze Cheng 已提交
663 664 665 666 667 668 669
          // 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 已提交
670 671
              tdbBtreeDecodeCell(pPage, pCell, &cd);

H
Hongze Cheng 已提交
672
              // TODO: pCell here may be inserted as an overflow cell, handle it
H
Hongze Cheng 已提交
673
              SCell *pNewCell = tdbOsMalloc(cd.kLen + 9);
H
Hongze Cheng 已提交
674 675 676
              int    szNewCell;
              SPgno  pgno;
              pgno = TDB_PAGE_PGNO(pNews[iNew]);
H
Hongze Cheng 已提交
677
              tdbBtreeEncodeCell(pParent, cd.pKey, cd.kLen, (void *)&pgno, sizeof(SPgno), pNewCell, &szNewCell);
H
Hongze Cheng 已提交
678
              tdbPageInsertCell(pParent, sIdx++, pNewCell, szNewCell, 0);
H
Hongze Cheng 已提交
679
              tdbOsFree(pNewCell);
H
Hongze Cheng 已提交
680
            }
H
Hongze Cheng 已提交
681 682

            // move to next new page
H
Hongze Cheng 已提交
683
            iNew++;
H
Hongze Cheng 已提交
684 685 686 687
            nNewCells = 0;
            if (iNew < nNews) {
              tdbBtreeZeroPage(pNews[iNew], &iarg);
            }
H
Hongze Cheng 已提交
688 689 690
          }
        } else {
          ASSERT(childNotLeaf);
H
Hongze Cheng 已提交
691
          ASSERT(iNew < nNews - 1);
H
Hongze Cheng 已提交
692

H
Hongze Cheng 已提交
693 694 695 696
          // set current new page right-most child
          ((SIntHdr *)pNews[iNew]->pData)->pgno = ((SPgno *)pCell)[0];

          // insert to parent as divider cell
H
Hongze Cheng 已提交
697 698 699
          ASSERT(iNew < nNews - 1);
          ((SPgno *)pCell)[0] = TDB_PAGE_PGNO(pNews[iNew]);
          tdbPageInsertCell(pParent, sIdx++, pCell, szCell, 0);
H
Hongze Cheng 已提交
700 701 702 703

          // move to next new page
          iNew++;
          nNewCells = 0;
H
Hongze Cheng 已提交
704 705 706
          if (iNew < nNews) {
            tdbBtreeZeroPage(pNews[iNew], &iarg);
          }
H
Hongze Cheng 已提交
707 708
        }
      }
H
Hongze Cheng 已提交
709
    }
H
Hongze Cheng 已提交
710

H
Hongze Cheng 已提交
711 712 713
    if (childNotLeaf) {
      ASSERT(TDB_PAGE_TOTAL_CELLS(pNews[nNews - 1]) == infoNews[nNews - 1].cnt);
      ((SIntHdr *)(pNews[nNews - 1]->pData))->pgno = rPgno;
H
Hongze Cheng 已提交
714

H
Hongze Cheng 已提交
715 716 717 718 719 720
      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 已提交
721
      }
H
Hongze Cheng 已提交
722 723 724 725 726 727 728
    }

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

H
Hongze Cheng 已提交
729 730
  for (int i = 0; i < 3; i++) {
    if (pDivCell[i]) {
H
Hongze Cheng 已提交
731
      tdbOsFree(pDivCell[i]);
H
Hongze Cheng 已提交
732 733
    }
  }
H
Hongze Cheng 已提交
734

H
Hongze Cheng 已提交
735
  return 0;
H
Hongze Cheng 已提交
736 737
}

H
Hongze Cheng 已提交
738
static int tdbBtreeBalance(SBTC *pBtc) {
H
Hongze Cheng 已提交
739
  int    iPage;
H
Hongze Cheng 已提交
740
  SPage *pParent;
H
Hongze Cheng 已提交
741
  SPage *pPage;
H
Hongze Cheng 已提交
742
  int    ret;
H
Hongze Cheng 已提交
743
  u8     flags;
H
Hongze Cheng 已提交
744 745
  u8     leaf;
  u8     root;
H
Hongze Cheng 已提交
746 747 748

  // Main loop to balance the BTree
  for (;;) {
H
Hongze Cheng 已提交
749 750
    iPage = pBtc->iPage;
    pPage = pBtc->pPage;
H
refact  
Hongze Cheng 已提交
751 752
    leaf = TDB_BTREE_PAGE_IS_LEAF(pPage);
    root = TDB_BTREE_PAGE_IS_ROOT(pPage);
H
Hongze Cheng 已提交
753

H
Hongze Cheng 已提交
754 755
    // when the page is not overflow and not too empty, the balance work
    // is finished. Just break out the balance loop.
H
Hongze Cheng 已提交
756
    if (pPage->nOverflow == 0 /* TODO: && pPage->nFree <= */) {
H
Hongze Cheng 已提交
757 758 759 760
      break;
    }

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

H
Hongze Cheng 已提交
765
      ret = tdbBtreeBalanceDeeper(pBtc->pBt, pPage, &(pBtc->pgStack[1]));
H
Hongze Cheng 已提交
766 767 768 769
      if (ret < 0) {
        return -1;
      }

H
Hongze Cheng 已提交
770 771 772 773 774
      pBtc->idx = 0;
      pBtc->idxStack[0] = 0;
      pBtc->pgStack[0] = pBtc->pPage;
      pBtc->iPage = 1;
      pBtc->pPage = pBtc->pgStack[1];
H
Hongze Cheng 已提交
775
    } else {
H
Hongze Cheng 已提交
776
      // Generalized balance step
H
Hongze Cheng 已提交
777
      pParent = pBtc->pgStack[iPage - 1];
H
Hongze Cheng 已提交
778

H
Hongze Cheng 已提交
779
      ret = tdbBtreeBalanceNonRoot(pBtc->pBt, pParent, pBtc->idxStack[pBtc->iPage - 1]);
H
Hongze Cheng 已提交
780 781 782 783
      if (ret < 0) {
        return -1;
      }

H
Hongze Cheng 已提交
784 785
      pBtc->iPage--;
      pBtc->pPage = pBtc->pgStack[pBtc->iPage];
H
Hongze Cheng 已提交
786 787 788 789 790
    }
  }

  return 0;
}
H
Hongze Cheng 已提交
791 792
#endif

H
Hongze Cheng 已提交
793
// TDB_BTREE_CELL =====================
H
Hongze Cheng 已提交
794 795
static int tdbBtreeEncodePayload(SPage *pPage, SCell *pCell, int nHeader, const void *pKey, int kLen, const void *pVal,
                                 int vLen, int *szPayload) {
H
Hongze Cheng 已提交
796 797 798
  int nPayload;

  nPayload = kLen + vLen;
H
Hongze Cheng 已提交
799 800 801
  if (nPayload + nHeader <= pPage->maxLocal) {
    // no overflow page is needed
    memcpy(pCell + nHeader, pKey, kLen);
H
Hongze Cheng 已提交
802
    if (pVal) {
H
Hongze Cheng 已提交
803
      memcpy(pCell + nHeader + kLen, pVal, vLen);
H
Hongze Cheng 已提交
804 805 806 807 808 809 810 811 812 813 814 815 816 817
    }

    *szPayload = nPayload;
    return 0;
  }

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

  return 0;
}

H
Hongze Cheng 已提交
818 819
static int tdbBtreeEncodeCell(SPage *pPage, const void *pKey, int kLen, const void *pVal, int vLen, SCell *pCell,
                              int *szCell) {
H
Hongze Cheng 已提交
820 821 822 823
  u8  leaf;
  int nHeader;
  int nPayload;
  int ret;
H
Hongze Cheng 已提交
824 825 826

  ASSERT(pPage->kLen == TDB_VARIANT_LEN || pPage->kLen == kLen);
  ASSERT(pPage->vLen == TDB_VARIANT_LEN || pPage->vLen == vLen);
H
Hongze Cheng 已提交
827
  ASSERT(pKey != NULL && kLen > 0);
H
Hongze Cheng 已提交
828

H
Hongze Cheng 已提交
829 830
  nPayload = 0;
  nHeader = 0;
H
refact  
Hongze Cheng 已提交
831
  leaf = TDB_BTREE_PAGE_IS_LEAF(pPage);
H
Hongze Cheng 已提交
832

H
Hongze Cheng 已提交
833
  // 1. Encode Header part
H
Hongze Cheng 已提交
834 835 836 837 838 839 840 841
  /* 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 已提交
842
  /* Encode kLen if need */
H
Hongze Cheng 已提交
843
  if (pPage->kLen == TDB_VARIANT_LEN) {
H
Hongze Cheng 已提交
844
    nHeader += tdbPutVarInt(pCell + nHeader, kLen);
H
Hongze Cheng 已提交
845 846
  }

H
Hongze Cheng 已提交
847
  /* Encode vLen if need */
H
Hongze Cheng 已提交
848
  if (pPage->vLen == TDB_VARIANT_LEN) {
H
Hongze Cheng 已提交
849
    nHeader += tdbPutVarInt(pCell + nHeader, vLen);
H
Hongze Cheng 已提交
850 851
  }

H
Hongze Cheng 已提交
852
  // 2. Encode payload part
H
Hongze Cheng 已提交
853 854 855
  if ((!leaf) || pPage->vLen == 0) {
    pVal = NULL;
    vLen = 0;
H
Hongze Cheng 已提交
856
  }
H
Hongze Cheng 已提交
857 858

  ret = tdbBtreeEncodePayload(pPage, pCell, nHeader, pKey, kLen, pVal, vLen, &nPayload);
H
Hongze Cheng 已提交
859
  if (ret < 0) {
H
Hongze Cheng 已提交
860 861 862
    // TODO
    ASSERT(0);
    return 0;
H
Hongze Cheng 已提交
863 864
  }

H
Hongze Cheng 已提交
865
  *szCell = nHeader + nPayload;
H
Hongze Cheng 已提交
866 867 868
  return 0;
}

H
Hongze Cheng 已提交
869
static int tdbBtreeDecodePayload(SPage *pPage, const SCell *pCell, int nHeader, SCellDecoder *pDecoder) {
H
Hongze Cheng 已提交
870 871 872
  int nPayload;

  if (pDecoder->pVal) {
H
Hongze Cheng 已提交
873
    ASSERT(!TDB_BTREE_PAGE_IS_LEAF(pPage));
H
Hongze Cheng 已提交
874
    nPayload = pDecoder->kLen;
H
Hongze Cheng 已提交
875 876
  } else {
    nPayload = pDecoder->kLen + pDecoder->vLen;
H
Hongze Cheng 已提交
877 878
  }

H
Hongze Cheng 已提交
879 880 881 882 883
  if (nHeader + nPayload <= pPage->maxLocal) {
    // no over flow case
    pDecoder->pKey = pCell + nHeader;
    if (pDecoder->pVal == NULL && pDecoder->vLen > 0) {
      pDecoder->pVal = pCell + nHeader + pDecoder->kLen;
H
Hongze Cheng 已提交
884
    }
H
Hongze Cheng 已提交
885 886 887 888
    return 0;
  }

  {
H
Hongze Cheng 已提交
889 890
    // TODO: handle overflow case
    ASSERT(0);
H
Hongze Cheng 已提交
891 892
  }

H
Hongze Cheng 已提交
893 894 895 896 897 898 899 900 901
  return 0;
}

static int tdbBtreeDecodeCell(SPage *pPage, const SCell *pCell, SCellDecoder *pDecoder) {
  u8  leaf;
  int nHeader;
  int ret;

  nHeader = 0;
H
refact  
Hongze Cheng 已提交
902
  leaf = TDB_BTREE_PAGE_IS_LEAF(pPage);
H
Hongze Cheng 已提交
903

H
Hongze Cheng 已提交
904 905 906 907 908 909 910
  // Clear the state of decoder
  pDecoder->kLen = -1;
  pDecoder->pKey = NULL;
  pDecoder->vLen = -1;
  pDecoder->pVal = NULL;
  pDecoder->pgno = 0;

H
Hongze Cheng 已提交
911
  // 1. Decode header part
H
Hongze Cheng 已提交
912 913 914 915 916 917 918 919
  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 已提交
920 921 922 923 924 925 926
  if (pPage->kLen == TDB_VARIANT_LEN) {
    nHeader += tdbGetVarInt(pCell + nHeader, &(pDecoder->kLen));
  } else {
    pDecoder->kLen = pPage->kLen;
  }

  if (pPage->vLen == TDB_VARIANT_LEN) {
H
Hongze Cheng 已提交
927
    ASSERT(leaf);
H
Hongze Cheng 已提交
928
    nHeader += tdbGetVarInt(pCell + nHeader, &(pDecoder->vLen));
H
Hongze Cheng 已提交
929
  } else {
H
Hongze Cheng 已提交
930 931
    pDecoder->vLen = pPage->vLen;
  }
H
Hongze Cheng 已提交
932

H
Hongze Cheng 已提交
933
  // 2. Decode payload part
H
Hongze Cheng 已提交
934
  ret = tdbBtreeDecodePayload(pPage, pCell, nHeader, pDecoder);
H
Hongze Cheng 已提交
935 936
  if (ret < 0) {
    return -1;
H
Hongze Cheng 已提交
937 938 939 940 941
  }

  return 0;
}

H
Hongze Cheng 已提交
942
static int tdbBtreeCellSize(const SPage *pPage, SCell *pCell) {
H
refact  
Hongze Cheng 已提交
943
  u8  leaf;
H
Hongze Cheng 已提交
944 945 946
  int szCell;
  int kLen = 0, vLen = 0;

H
refact  
Hongze Cheng 已提交
947
  leaf = TDB_BTREE_PAGE_IS_LEAF(pPage);
H
Hongze Cheng 已提交
948 949
  szCell = 0;

H
refact  
Hongze Cheng 已提交
950
  if (!leaf) {
H
Hongze Cheng 已提交
951 952 953 954 955 956 957 958 959
    szCell += sizeof(SPgno);
  }

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

H
refact  
Hongze Cheng 已提交
960 961 962 963 964
  if (pPage->vLen == TDB_VARIANT_LEN) {
    ASSERT(leaf);
    szCell += tdbGetVarInt(pCell + szCell, &vLen);
  } else if (leaf) {
    vLen = pPage->vLen;
H
Hongze Cheng 已提交
965 966 967 968
  }

  szCell = szCell + kLen + vLen;

H
refact  
Hongze Cheng 已提交
969 970 971 972 973 974 975 976 977
  if (szCell <= pPage->maxLocal) {
    return szCell;
  }

  {
    // TODO
    ASSERT(0);
    return 0;
  }
H
Hongze Cheng 已提交
978
}
H
Hongze Cheng 已提交
979
// TDB_BTREE_CELL
H
Hongze Cheng 已提交
980

H
refact  
Hongze Cheng 已提交
981
// TDB_BTREE_CURSOR =====================
H
Hongze Cheng 已提交
982 983 984 985 986
int tdbBtcOpen(SBTC *pBtc, SBTree *pBt) {
  pBtc->pBt = pBt;
  pBtc->iPage = -1;
  pBtc->pPage = NULL;
  pBtc->idx = -1;
H
Hongze Cheng 已提交
987 988 989 990

  return 0;
}

H
Hongze Cheng 已提交
991
int tdbBtcMoveToFirst(SBTC *pBtc) {
H
refact  
Hongze Cheng 已提交
992 993 994
  int     ret;
  SBTree *pBt;
  SPager *pPager;
H
Hongze Cheng 已提交
995 996
  SCell  *pCell;
  SPgno   pgno;
H
refact  
Hongze Cheng 已提交
997 998 999 1000 1001

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

  if (pBtc->iPage < 0) {
H
Hongze Cheng 已提交
1002
    // move a clean cursor
H
refact  
Hongze Cheng 已提交
1003 1004 1005 1006 1007 1008
    ret = tdbPagerFetchPage(pPager, pBt->root, &(pBtc->pPage), tdbBtreeInitPage, pBt);
    if (ret < 0) {
      ASSERT(0);
      return -1;
    }

H
Hongze Cheng 已提交
1009
    ASSERT(TDB_BTREE_PAGE_IS_ROOT(pBtc->pPage));
H
refact  
Hongze Cheng 已提交
1010

H
Hongze Cheng 已提交
1011 1012 1013 1014
    pBtc->iPage = 0;
    if (TDB_PAGE_TOTAL_CELLS(pBtc->pPage) > 0) {
      pBtc->idx = 0;
    } else {
H
more  
Hongze Cheng 已提交
1015
      // no any data, point to an invalid position
H
Hongze Cheng 已提交
1016 1017
      ASSERT(TDB_BTREE_PAGE_IS_LEAF(pBtc->pPage));
      pBtc->idx = -1;
H
refact  
Hongze Cheng 已提交
1018 1019
      return 0;
    }
H
Hongze Cheng 已提交
1020 1021 1022
  } else {
    // move from a position
    int iPage = 0;
H
refact  
Hongze Cheng 已提交
1023

H
Hongze Cheng 已提交
1024 1025 1026 1027
    for (; iPage < pBtc->iPage; iPage++) {
      ASSERT(pBtc->idxStack[iPage] >= 0);
      if (pBtc->idxStack[iPage]) break;
    }
H
refact  
Hongze Cheng 已提交
1028

H
Hongze Cheng 已提交
1029 1030 1031 1032
    // move upward
    for (;;) {
      if (pBtc->iPage == 0) {
        pBtc->idx = 0;
H
refact  
Hongze Cheng 已提交
1033 1034
        break;
      }
H
Hongze Cheng 已提交
1035

H
Hongze Cheng 已提交
1036 1037
      if (pBtc->iPage < iPage) break;
      tdbBtcMoveUpward(pBtc);
H
Hongze Cheng 已提交
1038 1039 1040 1041 1042
    }
  }

  // move downward
  for (;;) {
H
refact  
Hongze Cheng 已提交
1043
    if (TDB_BTREE_PAGE_IS_LEAF(pBtc->pPage)) break;
H
Hongze Cheng 已提交
1044

H
Hongze Cheng 已提交
1045
    ret = tdbBtcMoveDownward(pBtc);
H
Hongze Cheng 已提交
1046 1047 1048 1049 1050 1051 1052 1053
    if (ret < 0) {
      ASSERT(0);
      return -1;
    }

    pBtc->idx = 0;
  }

H
Hongze Cheng 已提交
1054 1055 1056 1057
  return 0;
}

int tdbBtcMoveToLast(SBTC *pBtc) {
H
Hongze Cheng 已提交
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
  int     ret;
  SBTree *pBt;
  SPager *pPager;
  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 (;;) {
H
refact  
Hongze Cheng 已提交
1082
    if (TDB_BTREE_PAGE_IS_LEAF(pBtc->pPage)) {
H
Hongze Cheng 已提交
1083 1084 1085 1086 1087 1088 1089
      // 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);

H
Hongze Cheng 已提交
1090
      ret = tdbBtcMoveDownward(pBtc);
H
Hongze Cheng 已提交
1091 1092 1093 1094 1095 1096 1097
      if (ret < 0) {
        ASSERT(0);
        return -1;
      }
    }
  }

H
Hongze Cheng 已提交
1098 1099 1100 1101
  return 0;
}

int tdbBtreeNext(SBTC *pBtc, void **ppKey, int *kLen, void **ppVal, int *vLen) {
H
Hongze Cheng 已提交
1102 1103 1104 1105 1106
  SCell       *pCell;
  SCellDecoder cd;
  void        *pKey, *pVal;
  int          ret;

H
Hongze Cheng 已提交
1107
  if (pBtc->idx < 0) {
H
Hongze Cheng 已提交
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
    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 已提交
1142 1143 1144
  int    nCells;
  SCell *pCell;

H
refact  
Hongze Cheng 已提交
1145
  ASSERT(TDB_BTREE_PAGE_IS_LEAF(pBtc->pPage));
H
Hongze Cheng 已提交
1146 1147 1148

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

H
Hongze Cheng 已提交
1149
  pBtc->idx++;
H
Hongze Cheng 已提交
1150 1151 1152 1153
  if (pBtc->idx < TDB_PAGE_TOTAL_CELLS(pBtc->pPage)) {
    return 0;
  }

H
Hongze Cheng 已提交
1154 1155 1156 1157 1158
  if (pBtc->iPage == 0) {
    pBtc->idx = -1;
    return 0;
  }

H
Hongze Cheng 已提交
1159 1160
  // Move upward
  for (;;) {
H
Hongze Cheng 已提交
1161 1162 1163 1164 1165 1166 1167
    tdbBtcMoveUpward(pBtc);
    pBtc->idx++;

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

H
Hongze Cheng 已提交
1169 1170 1171 1172
    if (pBtc->iPage == 0) {
      pBtc->idx = -1;
      return 0;
    }
H
Hongze Cheng 已提交
1173 1174 1175 1176
  }

  // Move downward
  for (;;) {
H
Hongze Cheng 已提交
1177 1178
    nCells = TDB_PAGE_TOTAL_CELLS(pBtc->pPage);

H
Hongze Cheng 已提交
1179
    tdbBtcMoveDownward(pBtc);
H
Hongze Cheng 已提交
1180 1181
    pBtc->idx = 0;

H
refact  
Hongze Cheng 已提交
1182
    if (TDB_BTREE_PAGE_IS_LEAF(pBtc->pPage)) {
H
Hongze Cheng 已提交
1183 1184
      break;
    }
H
Hongze Cheng 已提交
1185 1186
  }

H
Hongze Cheng 已提交
1187 1188 1189
  return 0;
}

H
Hongze Cheng 已提交
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
static int tdbBtcMoveDownward(SBTC *pBtc) {
  int    ret;
  SPgno  pgno;
  SCell *pCell;

  ASSERT(pBtc->idx >= 0);
  ASSERT(!TDB_BTREE_PAGE_IS_LEAF(pBtc->pPage));

  if (pBtc->idx < TDB_PAGE_TOTAL_CELLS(pBtc->pPage)) {
    pCell = tdbPageGetCell(pBtc->pPage, pBtc->idx);
    pgno = ((SPgno *)pCell)[0];
  } else {
    pgno = ((SIntHdr *)pBtc->pPage->pData)->pgno;
  }
H
Hongze Cheng 已提交
1204

H
Hongze Cheng 已提交
1205 1206 1207 1208 1209
  pBtc->pgStack[pBtc->iPage] = pBtc->pPage;
  pBtc->idxStack[pBtc->iPage] = pBtc->idx;
  pBtc->iPage++;
  pBtc->pPage = NULL;
  pBtc->idx = -1;
H
Hongze Cheng 已提交
1210

H
Hongze Cheng 已提交
1211
  ret = tdbPagerFetchPage(pBtc->pBt->pPager, pgno, &pBtc->pPage, tdbBtreeInitPage, pBtc->pBt);
H
Hongze Cheng 已提交
1212 1213
  if (ret < 0) {
    ASSERT(0);
H
Hongze Cheng 已提交
1214
    return -1;
H
Hongze Cheng 已提交
1215 1216 1217 1218 1219 1220
  }

  return 0;
}

static int tdbBtcMoveUpward(SBTC *pBtc) {
H
Hongze Cheng 已提交
1221 1222
  if (pBtc->iPage == 0) return -1;

H
Hongze Cheng 已提交
1223
  tdbPagerReturnPage(pBtc->pBt->pPager, pBtc->pPage);
H
Hongze Cheng 已提交
1224 1225 1226 1227 1228

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

H
Hongze Cheng 已提交
1229
  return 0;
H
Hongze Cheng 已提交
1230
}
H
refact  
Hongze Cheng 已提交
1231

H
Hongze Cheng 已提交
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
static int tdbBtcMoveTo(SBTC *pBtc, const void *pKey, int kLen, int *pCRst) {
  int     ret;
  SBTree *pBt;
  SPager *pPager;

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

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

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

    pBtc->iPage = 0;

    if (TDB_PAGE_TOTAL_CELLS(pBtc->pPage) == 0) {
      // Current page is empty
      // ASSERT(TDB_FLAG_IS(TDB_PAGE_FLAGS(pBtc->pPage), TDB_BTREE_ROOT | TDB_BTREE_LEAF));
      return 0;
    }

    for (;;) {
      int          lidx, ridx, midx, c, nCells;
      SCell       *pCell;
      SPage       *pPage;
      SCellDecoder cd = {0};

      pPage = pBtc->pPage;
      nCells = TDB_PAGE_TOTAL_CELLS(pPage);
      lidx = 0;
      ridx = nCells - 1;

      ASSERT(nCells > 0);

      for (;;) {
        if (lidx > ridx) break;

        midx = (lidx + ridx) >> 1;

        pCell = tdbPageGetCell(pPage, midx);
        ret = tdbBtreeDecodeCell(pPage, pCell, &cd);
        if (ret < 0) {
          // TODO: handle error
          ASSERT(0);
          return -1;
        }

        // Compare the key values
        c = pBt->kcmpr(pKey, kLen, cd.pKey, cd.kLen);
        if (c < 0) {
          /* input-key < cell-key */
          ridx = midx - 1;
        } else if (c > 0) {
          /* input-key > cell-key */
          lidx = midx + 1;
        } else {
          /* input-key == cell-key */
          break;
        }
      }

      // Move downward or break
      u8 leaf = TDB_BTREE_PAGE_IS_LEAF(pPage);
      if (leaf) {
        pBtc->idx = midx;
        *pCRst = c;
        break;
      } else {
        if (c <= 0) {
          pBtc->idx = midx;
        } else {
          pBtc->idx = midx + 1;
        }
H
Hongze Cheng 已提交
1311
        tdbBtcMoveDownward(pBtc);
H
Hongze Cheng 已提交
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
      }
    }

  } else {
    // TODO: Move the cursor from a some position instead of a clear state
    ASSERT(0);
  }

  return 0;
}

H
refact  
Hongze Cheng 已提交
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
int tdbBtcClose(SBTC *pBtc) {
  if (pBtc->iPage < 0) return 0;

  for (;;) {
    ASSERT(pBtc->pPage);

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

    pBtc->iPage--;
    if (pBtc->iPage < 0) break;

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

  return 0;
}
H
refact  
Hongze Cheng 已提交
1340
// TDB_BTREE_CURSOR
H
Hongze Cheng 已提交
1341

H
refact  
Hongze Cheng 已提交
1342
// TDB_BTREE_DEBUG =====================
H
Hongze Cheng 已提交
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
#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) {
  SBtPageInfo *pBtPageInfo;

  pBtPageInfo = btPageInfos + idx;

  pBtPageInfo->pgno = TDB_PAGE_PGNO(pPage);

H
refact  
Hongze Cheng 已提交
1362 1363
  pBtPageInfo->root = TDB_BTREE_PAGE_IS_ROOT(pPage);
  pBtPageInfo->leaf = TDB_BTREE_PAGE_IS_LEAF(pPage);
H
Hongze Cheng 已提交
1364 1365 1366 1367 1368 1369 1370 1371 1372

  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;
}
H
refact  
Hongze Cheng 已提交
1373 1374
#endif
// TDB_BTREE_DEBUG