indexFst.c 44.0 KB
Newer Older
dengyihao's avatar
dengyihao 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * 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/>.
 */

dengyihao's avatar
dengyihao 已提交
16 17
#include "indexFst.h"
#include "indexFstAutomation.h"
18 19 20
#include "indexInt.h"
#include "tchecksum.h"
#include "tcoding.h"
dengyihao's avatar
dengyihao 已提交
21

dengyihao's avatar
dengyihao 已提交
22
static void fstPackDeltaIn(FstCountingWriter* wrt, CompiledAddr nodeAddr, CompiledAddr transAddr, uint8_t nBytes) {
dengyihao's avatar
dengyihao 已提交
23
  CompiledAddr deltaAddr = (transAddr == EMPTY_ADDRESS) ? EMPTY_ADDRESS : nodeAddr - transAddr;
24
  fstCountingWriterPackUintIn(wrt, deltaAddr, nBytes);
dengyihao's avatar
dengyihao 已提交
25
}
dengyihao's avatar
dengyihao 已提交
26
static uint8_t fstPackDetla(FstCountingWriter* wrt, CompiledAddr nodeAddr, CompiledAddr transAddr) {
dengyihao's avatar
dengyihao 已提交
27
  uint8_t nBytes = packDeltaSize(nodeAddr, transAddr);
28
  fstPackDeltaIn(wrt, nodeAddr, transAddr, nBytes);
dengyihao's avatar
dengyihao 已提交
29
  return nBytes;
dengyihao's avatar
dengyihao 已提交
30
}
dengyihao's avatar
dengyihao 已提交
31

dengyihao's avatar
dengyihao 已提交
32
FstUnFinishedNodes* fstUnFinishedNodesCreate() {
wafwerar's avatar
wafwerar 已提交
33
  FstUnFinishedNodes* nodes = taosMemoryMalloc(sizeof(FstUnFinishedNodes));
dengyihao's avatar
dengyihao 已提交
34 35 36
  if (nodes == NULL) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
37

dengyihao's avatar
dengyihao 已提交
38
  nodes->stack = (SArray*)taosArrayInit(64, sizeof(FstBuilderNodeUnfinished));
dengyihao's avatar
dengyihao 已提交
39 40 41
  fstUnFinishedNodesPushEmpty(nodes, false);
  return nodes;
}
dengyihao's avatar
dengyihao 已提交
42
static void unFinishedNodeDestroyElem(void* elem) {
dengyihao's avatar
dengyihao 已提交
43
  FstBuilderNodeUnfinished* b = (FstBuilderNodeUnfinished*)elem;
44
  fstBuilderNodeDestroy(b->node);
wafwerar's avatar
wafwerar 已提交
45
  taosMemoryFree(b->last);
dengyihao's avatar
dengyihao 已提交
46
  b->last = NULL;
47
}
dengyihao's avatar
dengyihao 已提交
48
void fstUnFinishedNodesDestroy(FstUnFinishedNodes* nodes) {
dengyihao's avatar
dengyihao 已提交
49 50 51
  if (nodes == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
52

53
  taosArrayDestroyEx(nodes->stack, unFinishedNodeDestroyElem);
wafwerar's avatar
wafwerar 已提交
54
  taosMemoryFree(nodes);
dengyihao's avatar
dengyihao 已提交
55 56
}

dengyihao's avatar
dengyihao 已提交
57
void fstUnFinishedNodesPushEmpty(FstUnFinishedNodes* nodes, bool isFinal) {
wafwerar's avatar
wafwerar 已提交
58
  FstBuilderNode* node = taosMemoryMalloc(sizeof(FstBuilderNode));
59
  node->isFinal = isFinal;
dengyihao's avatar
dengyihao 已提交
60
  node->finalOutput = 0;
61
  node->trans = taosArrayInit(16, sizeof(FstTransition));
dengyihao's avatar
dengyihao 已提交
62

63
  FstBuilderNodeUnfinished un = {.node = node, .last = NULL};
dengyihao's avatar
dengyihao 已提交
64 65
  taosArrayPush(nodes->stack, &un);
}
dengyihao's avatar
dengyihao 已提交
66
FstBuilderNode* fstUnFinishedNodesPopRoot(FstUnFinishedNodes* nodes) {
dengyihao's avatar
dengyihao 已提交
67 68
  assert(taosArrayGetSize(nodes->stack) == 1);

dengyihao's avatar
dengyihao 已提交
69
  FstBuilderNodeUnfinished* un = taosArrayPop(nodes->stack);
70 71
  assert(un->last == NULL);
  return un->node;
dengyihao's avatar
dengyihao 已提交
72 73
}

dengyihao's avatar
dengyihao 已提交
74 75
FstBuilderNode* fstUnFinishedNodesPopFreeze(FstUnFinishedNodes* nodes, CompiledAddr addr) {
  FstBuilderNodeUnfinished* un = taosArrayPop(nodes->stack);
dengyihao's avatar
dengyihao 已提交
76
  fstBuilderNodeUnfinishedLastCompiled(un, addr);
wafwerar's avatar
wafwerar 已提交
77
  // taosMemoryFree(un->last); // TODO add func FstLastTransitionFree()
78 79
  // un->last = NULL;
  return un->node;
dengyihao's avatar
dengyihao 已提交
80 81
}

dengyihao's avatar
dengyihao 已提交
82 83
FstBuilderNode* fstUnFinishedNodesPopEmpty(FstUnFinishedNodes* nodes) {
  FstBuilderNodeUnfinished* un = taosArrayPop(nodes->stack);
84 85
  assert(un->last == NULL);
  return un->node;
dengyihao's avatar
dengyihao 已提交
86
}
dengyihao's avatar
dengyihao 已提交
87 88
void fstUnFinishedNodesSetRootOutput(FstUnFinishedNodes* nodes, Output out) {
  FstBuilderNodeUnfinished* un = taosArrayGet(nodes->stack, 0);
89
  un->node->isFinal = true;
dengyihao's avatar
dengyihao 已提交
90
  un->node->finalOutput = out;
91 92
  // un->node->trans       = NULL;
}
dengyihao's avatar
dengyihao 已提交
93 94
void fstUnFinishedNodesTopLastFreeze(FstUnFinishedNodes* nodes, CompiledAddr addr) {
  FstBuilderNodeUnfinished* un = taosArrayGet(nodes->stack, taosArrayGetSize(nodes->stack) - 1);
dengyihao's avatar
dengyihao 已提交
95 96
  fstBuilderNodeUnfinishedLastCompiled(un, addr);
}
dengyihao's avatar
dengyihao 已提交
97 98
void fstUnFinishedNodesAddSuffix(FstUnFinishedNodes* nodes, FstSlice bs, Output out) {
  FstSlice* s = &bs;
dengyihao's avatar
dengyihao 已提交
99 100 101
  if (fstSliceIsEmpty(s)) {
    return;
  }
102
  size_t                    sz = taosArrayGetSize(nodes->stack) - 1;
dengyihao's avatar
dengyihao 已提交
103
  FstBuilderNodeUnfinished* un = taosArrayGet(nodes->stack, sz);
dengyihao's avatar
dengyihao 已提交
104 105
  assert(un->last == NULL);

wafwerar's avatar
wafwerar 已提交
106
  // FstLastTransition *trn = taosMemoryMalloc(sizeof(FstLastTransition));
107 108 109
  // trn->inp = s->data[s->start];
  // trn->out = out;
  int32_t  len = 0;
dengyihao's avatar
dengyihao 已提交
110
  uint8_t* data = fstSliceData(s, &len);
111
  un->last = fstLastTransitionCreate(data[0], out);
dengyihao's avatar
dengyihao 已提交
112

dengyihao's avatar
dengyihao 已提交
113
  for (uint64_t i = 1; i < len; i++) {
wafwerar's avatar
wafwerar 已提交
114
    FstBuilderNode* n = taosMemoryMalloc(sizeof(FstBuilderNode));
115
    n->isFinal = false;
dengyihao's avatar
dengyihao 已提交
116
    n->finalOutput = 0;
117 118
    n->trans = taosArrayInit(16, sizeof(FstTransition));

wafwerar's avatar
wafwerar 已提交
119
    // FstLastTransition *trn = taosMemoryMalloc(sizeof(FstLastTransition));
120 121
    // trn->inp = s->data[i];
    // trn->out = out;
dengyihao's avatar
dengyihao 已提交
122
    FstLastTransition* trn = fstLastTransitionCreate(data[i], 0);
dengyihao's avatar
dengyihao 已提交
123

124 125
    FstBuilderNodeUnfinished un = {.node = n, .last = trn};
    taosArrayPush(nodes->stack, &un);
dengyihao's avatar
dengyihao 已提交
126
  }
127
  fstUnFinishedNodesPushEmpty(nodes, true);
dengyihao's avatar
dengyihao 已提交
128 129
}

dengyihao's avatar
dengyihao 已提交
130 131
uint64_t fstUnFinishedNodesFindCommPrefix(FstUnFinishedNodes* node, FstSlice bs) {
  FstSlice* s = &bs;
dengyihao's avatar
dengyihao 已提交
132

133
  size_t   ssz = taosArrayGetSize(node->stack);  // stack size
dengyihao's avatar
dengyihao 已提交
134
  uint64_t count = 0;
135
  int32_t  lsz;  // data len
dengyihao's avatar
dengyihao 已提交
136
  uint8_t* data = fstSliceData(s, &lsz);
dengyihao's avatar
dengyihao 已提交
137
  for (size_t i = 0; i < ssz && i < lsz; i++) {
dengyihao's avatar
dengyihao 已提交
138
    FstBuilderNodeUnfinished* un = taosArrayGet(node->stack, i);
dengyihao's avatar
dengyihao 已提交
139
    if (un->last->inp == data[i]) {
dengyihao's avatar
dengyihao 已提交
140 141 142
      count++;
    } else {
      break;
143
    }
dengyihao's avatar
dengyihao 已提交
144 145 146
  }
  return count;
}
dengyihao's avatar
dengyihao 已提交
147 148
uint64_t fstUnFinishedNodesFindCommPrefixAndSetOutput(FstUnFinishedNodes* node, FstSlice bs, Output in, Output* out) {
  FstSlice* s = &bs;
dengyihao's avatar
dengyihao 已提交
149

150 151
  size_t lsz = (size_t)(s->end - s->start + 1);  // data len
  size_t ssz = taosArrayGetSize(node->stack);    // stack size
dengyihao's avatar
dengyihao 已提交
152
  *out = in;
dengyihao's avatar
dengyihao 已提交
153 154
  uint64_t i = 0;
  for (i = 0; i < lsz && i < ssz; i++) {
dengyihao's avatar
dengyihao 已提交
155
    FstBuilderNodeUnfinished* un = taosArrayGet(node->stack, i);
dengyihao's avatar
dengyihao 已提交
156

dengyihao's avatar
dengyihao 已提交
157
    FstLastTransition* t = un->last;
158
    uint64_t           addPrefix = 0;
dengyihao's avatar
dengyihao 已提交
159
    uint8_t*           data = fstSliceData(s, NULL);
dengyihao's avatar
dengyihao 已提交
160
    if (t && t->inp == data[i]) {
dengyihao's avatar
dengyihao 已提交
161
      uint64_t commPrefix = TMIN(t->out, *out);
162 163
      uint64_t tAddPrefix = t->out - commPrefix;
      (*out) = (*out) - commPrefix;
dengyihao's avatar
dengyihao 已提交
164
      t->out = commPrefix;
165
      addPrefix = tAddPrefix;
dengyihao's avatar
dengyihao 已提交
166
    } else {
167
      break;
dengyihao's avatar
dengyihao 已提交
168 169
    }
    if (addPrefix != 0) {
dengyihao's avatar
dengyihao 已提交
170
      if (i + 1 < ssz) {
dengyihao's avatar
dengyihao 已提交
171
        FstBuilderNodeUnfinished* unf = taosArrayGet(node->stack, i + 1);
172
        fstBuilderNodeUnfinishedAddOutputPrefix(unf, addPrefix);
dengyihao's avatar
dengyihao 已提交
173
      }
dengyihao's avatar
dengyihao 已提交
174
    }
175
  }
dengyihao's avatar
dengyihao 已提交
176
  return i;
177
}
dengyihao's avatar
dengyihao 已提交
178

dengyihao's avatar
dengyihao 已提交
179
FstState fstStateCreateFrom(FstSlice* slice, CompiledAddr addr) {
dengyihao's avatar
dengyihao 已提交
180
  FstState fs = {.state = EmptyFinal, .val = 0};
dengyihao's avatar
dengyihao 已提交
181 182 183
  if (addr == EMPTY_ADDRESS) {
    return fs;
  }
184

dengyihao's avatar
dengyihao 已提交
185
  uint8_t* data = fstSliceData(slice, NULL);
186 187
  uint8_t  v = data[addr];
  uint8_t  t = (v & 0b11000000) >> 6;
dengyihao's avatar
dengyihao 已提交
188 189 190
  if (t == 0b11) {
    fs.state = OneTransNext;
  } else if (t == 0b10) {
191
    fs.state = OneTrans;
dengyihao's avatar
dengyihao 已提交
192
  } else {
193
    fs.state = AnyTrans;
dengyihao's avatar
dengyihao 已提交
194
  }
dengyihao's avatar
dengyihao 已提交
195
  fs.val = v;
dengyihao's avatar
dengyihao 已提交
196 197
  return fs;
}
dengyihao's avatar
dengyihao 已提交
198

dengyihao's avatar
dengyihao 已提交
199 200 201 202
static FstState fstStateDict[] = {{.state = OneTransNext, .val = 0b11000000},
                                  {.state = OneTrans, .val = 0b10000000},
                                  {.state = AnyTrans, .val = 0b00000000},
                                  {.state = EmptyFinal, .val = 0b00000000}};
203
// debug
dengyihao's avatar
dengyihao 已提交
204
static const char* fstStateStr[] = {"ONE_TRANS_NEXT", "ONE_TRANS", "ANY_TRANS", "EMPTY_FINAL"};
dengyihao's avatar
dengyihao 已提交
205

206
FstState fstStateCreate(State state) {
dengyihao's avatar
dengyihao 已提交
207
  uint8_t idx = (uint8_t)state;
dengyihao's avatar
dengyihao 已提交
208
  return fstStateDict[idx];
dengyihao's avatar
dengyihao 已提交
209
}
210
// compile
dengyihao's avatar
dengyihao 已提交
211
void fstStateCompileForOneTransNext(FstCountingWriter* w, CompiledAddr addr, uint8_t inp) {
212
  FstState s = fstStateCreate(OneTransNext);
dengyihao's avatar
dengyihao 已提交
213 214
  fstStateSetCommInput(&s, inp);

215
  bool    null = false;
dengyihao's avatar
dengyihao 已提交
216 217 218
  uint8_t v = fstStateCommInput(&s, &null);
  if (null) {
    // w->write_all(&[inp])
dengyihao's avatar
dengyihao 已提交
219
    fstCountingWriterWrite(w, &inp, 1);
220
  }
dengyihao's avatar
dengyihao 已提交
221
  fstCountingWriterWrite(w, &(s.val), 1);
dengyihao's avatar
dengyihao 已提交
222
  // w->write_all(&[s.val])
dengyihao's avatar
dengyihao 已提交
223
  return;
dengyihao's avatar
dengyihao 已提交
224
}
dengyihao's avatar
dengyihao 已提交
225
void fstStateCompileForOneTrans(FstCountingWriter* w, CompiledAddr addr, FstTransition* trn) {
226 227 228
  Output    out = trn->out;
  uint8_t   outPackSize = (out == 0 ? 0 : fstCountingWriterPackUint(w, out));
  uint8_t   transPackSize = fstPackDetla(w, addr, trn->addr);
dengyihao's avatar
dengyihao 已提交
229 230 231 232
  PackSizes packSizes = 0;

  FST_SET_OUTPUT_PACK_SIZE(packSizes, outPackSize);
  FST_SET_TRANSITION_PACK_SIZE(packSizes, transPackSize);
dengyihao's avatar
dengyihao 已提交
233
  fstCountingWriterWrite(w, (char*)&packSizes, sizeof(packSizes));
234 235

  FstState st = fstStateCreate(OneTrans);
dengyihao's avatar
dengyihao 已提交
236 237

  fstStateSetCommInput(&st, trn->inp);
dengyihao's avatar
dengyihao 已提交
238

239 240
  bool    null = false;
  uint8_t inp = fstStateCommInput(&st, &null);
dengyihao's avatar
dengyihao 已提交
241 242 243
  if (null == true) {
    fstCountingWriterWrite(w, (char*)&trn->inp, sizeof(trn->inp));
  }
dengyihao's avatar
dengyihao 已提交
244
  fstCountingWriterWrite(w, (char*)(&(st.val)), sizeof(st.val));
245
  return;
dengyihao's avatar
dengyihao 已提交
246
}
dengyihao's avatar
dengyihao 已提交
247
void fstStateCompileForAnyTrans(FstCountingWriter* w, CompiledAddr addr, FstBuilderNode* node) {
248
  size_t sz = taosArrayGetSize(node->trans);
dengyihao's avatar
dengyihao 已提交
249 250 251
  assert(sz <= 256);

  uint8_t tSize = 0;
252 253
  uint8_t oSize = packSize(node->finalOutput);

dengyihao's avatar
dengyihao 已提交
254
  // finalOutput.is_zero()
255
  bool anyOuts = (node->finalOutput != 0);
dengyihao's avatar
dengyihao 已提交
256
  for (size_t i = 0; i < sz; i++) {
dengyihao's avatar
dengyihao 已提交
257
    FstTransition* t = taosArrayGet(node->trans, i);
dengyihao's avatar
dengyihao 已提交
258 259
    tSize = TMAX(tSize, packDeltaSize(addr, t->addr));
    oSize = TMAX(oSize, packSize(t->out));
260
    anyOuts = anyOuts || (t->out != 0);
dengyihao's avatar
dengyihao 已提交
261 262
  }

263 264 265 266 267 268
  PackSizes packSizes = 0;
  if (anyOuts) {
    FST_SET_OUTPUT_PACK_SIZE(packSizes, oSize);
  } else {
    FST_SET_OUTPUT_PACK_SIZE(packSizes, 0);
  }
dengyihao's avatar
dengyihao 已提交
269 270

  FST_SET_TRANSITION_PACK_SIZE(packSizes, tSize);
271

dengyihao's avatar
dengyihao 已提交
272
  FstState st = fstStateCreate(AnyTrans);
273
  fstStateSetFinalState(&st, node->isFinal);
dengyihao's avatar
dengyihao 已提交
274
  fstStateSetStateNtrans(&st, (uint8_t)sz);
275

dengyihao's avatar
dengyihao 已提交
276
  if (anyOuts) {
dengyihao's avatar
dengyihao 已提交
277 278 279
    if (FST_BUILDER_NODE_IS_FINAL(node)) {
      fstCountingWriterPackUintIn(w, node->finalOutput, oSize);
    }
dengyihao's avatar
dengyihao 已提交
280
    for (int32_t i = sz - 1; i >= 0; i--) {
dengyihao's avatar
dengyihao 已提交
281
      FstTransition* t = taosArrayGet(node->trans, i);
dengyihao's avatar
dengyihao 已提交
282 283
      fstCountingWriterPackUintIn(w, t->out, oSize);
    }
284
  }
dengyihao's avatar
dengyihao 已提交
285
  for (int32_t i = sz - 1; i >= 0; i--) {
dengyihao's avatar
dengyihao 已提交
286
    FstTransition* t = taosArrayGet(node->trans, i);
287
    fstPackDeltaIn(w, addr, t->addr, tSize);
dengyihao's avatar
dengyihao 已提交
288
  }
dengyihao's avatar
dengyihao 已提交
289
  for (int32_t i = sz - 1; i >= 0; i--) {
dengyihao's avatar
dengyihao 已提交
290 291
    FstTransition* t = taosArrayGet(node->trans, i);
    fstCountingWriterWrite(w, (char*)&t->inp, 1);
292
    // fstPackDeltaIn(w, addr, t->addr, tSize);
dengyihao's avatar
dengyihao 已提交
293 294 295 296 297 298
  }
  if (sz > TRANS_INDEX_THRESHOLD) {
    // A value of 255 indicates that no transition exists for the byte
    // at that index. (Except when there are 256 transitions.) Namely,
    // any value greater than or equal to the number of transitions in
    // this node indicates an absent transition.
wafwerar's avatar
wafwerar 已提交
299
    uint8_t* index = (uint8_t*)taosMemoryMalloc(sizeof(uint8_t) * 256);
dengyihao's avatar
dengyihao 已提交
300
    memset(index, 255, sizeof(uint8_t) * 256);
301
    /// for (uint8_t i = 0; i < 256; i++) {
dengyihao's avatar
dengyihao 已提交
302 303
    //  index[i] = 255;
    ///}
dengyihao's avatar
dengyihao 已提交
304
    for (size_t i = 0; i < sz; i++) {
dengyihao's avatar
dengyihao 已提交
305
      FstTransition* t = taosArrayGet(node->trans, i);
dengyihao's avatar
dengyihao 已提交
306
      index[t->inp] = i;
307
      // fstPackDeltaIn(w, addr, t->addr, tSize);
dengyihao's avatar
dengyihao 已提交
308
    }
dengyihao's avatar
dengyihao 已提交
309
    fstCountingWriterWrite(w, (char*)index, 256);
wafwerar's avatar
wafwerar 已提交
310
    taosMemoryFree(index);
dengyihao's avatar
dengyihao 已提交
311
  }
dengyihao's avatar
dengyihao 已提交
312
  fstCountingWriterWrite(w, (char*)&packSizes, 1);
dengyihao's avatar
dengyihao 已提交
313 314 315
  bool null = false;
  fstStateStateNtrans(&st, &null);
  if (null == true) {
316 317 318
    // 256 can't be represented in a u8, so we abuse the fact that
    // the # of transitions can never be 1 here, since 1 is always
    // encoded in the state byte.
dengyihao's avatar
dengyihao 已提交
319
    uint8_t v = 1;
320
    if (sz == 256) {
dengyihao's avatar
dengyihao 已提交
321
      fstCountingWriterWrite(w, (char*)&v, 1);
322
    } else {
dengyihao's avatar
dengyihao 已提交
323
      fstCountingWriterWrite(w, (char*)&sz, 1);
324
    }
dengyihao's avatar
dengyihao 已提交
325
  }
dengyihao's avatar
dengyihao 已提交
326
  fstCountingWriterWrite(w, (char*)(&(st.val)), 1);
dengyihao's avatar
dengyihao 已提交
327 328 329 330
  return;
}

// set_comm_input
dengyihao's avatar
dengyihao 已提交
331
void fstStateSetCommInput(FstState* s, uint8_t inp) {
dengyihao's avatar
dengyihao 已提交
332 333 334
  assert(s->state == OneTransNext || s->state == OneTrans);

  uint8_t val;
dengyihao's avatar
dengyihao 已提交
335
  COMMON_INDEX(inp, 0b111111, val);
336
  s->val = (s->val & fstStateDict[s->state].val) | val;
dengyihao's avatar
dengyihao 已提交
337 338 339
}

// comm_input
dengyihao's avatar
dengyihao 已提交
340
uint8_t fstStateCommInput(FstState* s, bool* null) {
dengyihao's avatar
dengyihao 已提交
341 342
  assert(s->state == OneTransNext || s->state == OneTrans);
  uint8_t v = s->val & 0b00111111;
343 344
  if (v == 0) {
    *null = true;
dengyihao's avatar
dengyihao 已提交
345
    return v;
346 347 348
  }
  // v = 0 indicate that common_input is None
  return v == 0 ? 0 : COMMON_INPUT(v);
dengyihao's avatar
dengyihao 已提交
349 350 351 352
}

// input_len

dengyihao's avatar
dengyihao 已提交
353
uint64_t fstStateInputLen(FstState* s) {
dengyihao's avatar
dengyihao 已提交
354
  assert(s->state == OneTransNext || s->state == OneTrans);
dengyihao's avatar
dengyihao 已提交
355
  bool null = false;
356 357 358 359 360
  fstStateCommInput(s, &null);
  return null ? 1 : 0;
}

// end_addr
dengyihao's avatar
dengyihao 已提交
361
uint64_t fstStateEndAddrForOneTransNext(FstState* s, FstSlice* data) {
dengyihao's avatar
dengyihao 已提交
362
  assert(s->state == OneTransNext);
dengyihao's avatar
dengyihao 已提交
363 364
  return FST_SLICE_LEN(data) - 1 - fstStateInputLen(s);
}
dengyihao's avatar
dengyihao 已提交
365
uint64_t fstStateEndAddrForOneTrans(FstState* s, FstSlice* data, PackSizes sizes) {
dengyihao's avatar
dengyihao 已提交
366
  assert(s->state == OneTrans);
367 368 369
  return FST_SLICE_LEN(data) - 1 - fstStateInputLen(s) - 1  // pack size
         - FST_GET_TRANSITION_PACK_SIZE(sizes) - FST_GET_OUTPUT_PACK_SIZE(sizes);
}
dengyihao's avatar
dengyihao 已提交
370 371
uint64_t fstStateEndAddrForAnyTrans(FstState* state, uint64_t version, FstSlice* date, PackSizes sizes,
                                    uint64_t nTrans) {
372 373 374 375 376 377 378
  uint8_t oSizes = FST_GET_OUTPUT_PACK_SIZE(sizes);
  uint8_t finalOsize = !fstStateIsFinalState(state) ? 0 : oSizes;
  return FST_SLICE_LEN(date) - 1 - fstStateNtransLen(state) - 1                     // pack size
         - fstStateTotalTransSize(state, version, sizes, nTrans) - nTrans * oSizes  // output values
         - finalOsize;                                                              // final output
}
// input
dengyihao's avatar
dengyihao 已提交
379
uint8_t fstStateInput(FstState* s, FstNode* node) {
dengyihao's avatar
dengyihao 已提交
380
  assert(s->state == OneTransNext || s->state == OneTrans);
dengyihao's avatar
dengyihao 已提交
381
  FstSlice* slice = &node->data;
382 383
  bool      null = false;
  uint8_t   inp = fstStateCommInput(s, &null);
dengyihao's avatar
dengyihao 已提交
384
  uint8_t*  data = fstSliceData(slice, NULL);
dengyihao's avatar
dengyihao 已提交
385
  return null == false ? inp : data[node->start - 1];
dengyihao's avatar
dengyihao 已提交
386
}
dengyihao's avatar
dengyihao 已提交
387
uint8_t fstStateInputForAnyTrans(FstState* s, FstNode* node, uint64_t i) {
dengyihao's avatar
dengyihao 已提交
388
  assert(s->state == AnyTrans);
dengyihao's avatar
dengyihao 已提交
389
  FstSlice* slice = &node->data;
dengyihao's avatar
dengyihao 已提交
390

391 392
  uint64_t at = node->start - fstStateNtransLen(s) - 1                             // pack size
                - fstStateTransIndexSize(s, node->version, node->nTrans) - i - 1;  // the output size
dengyihao's avatar
dengyihao 已提交
393

dengyihao's avatar
dengyihao 已提交
394
  uint8_t* data = fstSliceData(slice, NULL);
dengyihao's avatar
dengyihao 已提交
395
  return data[at];
dengyihao's avatar
dengyihao 已提交
396 397 398
}

// trans_addr
dengyihao's avatar
dengyihao 已提交
399
CompiledAddr fstStateTransAddr(FstState* s, FstNode* node) {
dengyihao's avatar
dengyihao 已提交
400
  assert(s->state == OneTransNext || s->state == OneTrans);
dengyihao's avatar
dengyihao 已提交
401
  FstSlice* slice = &node->data;
dengyihao's avatar
dengyihao 已提交
402
  if (s->state == OneTransNext) {
403
    return (CompiledAddr)(node->end) - 1;
dengyihao's avatar
dengyihao 已提交
404
  } else {
405 406 407 408 409 410
    PackSizes sizes = node->sizes;
    uint8_t   tSizes = FST_GET_TRANSITION_PACK_SIZE(sizes);
    uint64_t  i = node->start - fstStateInputLen(s) - 1  // PackSizes
                 - tSizes;

    // refactor error logic
dengyihao's avatar
dengyihao 已提交
411
    uint8_t* data = fstSliceData(slice, NULL);
412 413
    return unpackDelta(data + i, tSizes, node->end);
  }
dengyihao's avatar
dengyihao 已提交
414
}
dengyihao's avatar
dengyihao 已提交
415
CompiledAddr fstStateTransAddrForAnyTrans(FstState* s, FstNode* node, uint64_t i) {
dengyihao's avatar
dengyihao 已提交
416 417
  assert(s->state == AnyTrans);

dengyihao's avatar
dengyihao 已提交
418
  FstSlice* slice = &node->data;
419
  uint8_t   tSizes = FST_GET_TRANSITION_PACK_SIZE(node->sizes);
dengyihao's avatar
dengyihao 已提交
420 421
  uint64_t  at = node->start - fstStateNtransLen(s) - 1 - fstStateTransIndexSize(s, node->version, node->nTrans) -
                node->nTrans - (i * tSizes) - tSizes;
dengyihao's avatar
dengyihao 已提交
422
  uint8_t* data = fstSliceData(slice, NULL);
423
  return unpackDelta(data + at, tSizes, node->end);
dengyihao's avatar
dengyihao 已提交
424 425
}

426
// sizes
dengyihao's avatar
dengyihao 已提交
427
PackSizes fstStateSizes(FstState* s, FstSlice* slice) {
428 429
  assert(s->state == OneTrans || s->state == AnyTrans);
  uint64_t i;
dengyihao's avatar
dengyihao 已提交
430
  if (s->state == OneTrans) {
431
    i = FST_SLICE_LEN(slice) - 1 - fstStateInputLen(s) - 1;
dengyihao's avatar
dengyihao 已提交
432 433 434 435
  } else {
    i = FST_SLICE_LEN(slice) - 1 - fstStateNtransLen(s) - 1;
  }

dengyihao's avatar
dengyihao 已提交
436
  uint8_t* data = fstSliceData(slice, NULL);
437
  return (PackSizes)(*(data + i));
dengyihao's avatar
dengyihao 已提交
438
}
439
// Output
dengyihao's avatar
dengyihao 已提交
440
Output fstStateOutput(FstState* s, FstNode* node) {
441 442
  assert(s->state == OneTrans);

dengyihao's avatar
dengyihao 已提交
443
  uint8_t oSizes = FST_GET_OUTPUT_PACK_SIZE(node->sizes);
dengyihao's avatar
dengyihao 已提交
444 445 446
  if (oSizes == 0) {
    return 0;
  }
dengyihao's avatar
dengyihao 已提交
447
  FstSlice* slice = &node->data;
448 449 450
  uint8_t   tSizes = FST_GET_TRANSITION_PACK_SIZE(node->sizes);

  uint64_t i = node->start - fstStateInputLen(s) - 1 - tSizes - oSizes;
dengyihao's avatar
dengyihao 已提交
451
  uint8_t* data = fstSliceData(slice, NULL);
dengyihao's avatar
dengyihao 已提交
452
  return unpackUint64(data + i, oSizes);
dengyihao's avatar
dengyihao 已提交
453
}
dengyihao's avatar
dengyihao 已提交
454
Output fstStateOutputForAnyTrans(FstState* s, FstNode* node, uint64_t i) {
dengyihao's avatar
dengyihao 已提交
455 456
  assert(s->state == AnyTrans);

457
  uint8_t oSizes = FST_GET_OUTPUT_PACK_SIZE(node->sizes);
dengyihao's avatar
dengyihao 已提交
458 459 460
  if (oSizes == 0) {
    return 0;
  }
dengyihao's avatar
dengyihao 已提交
461 462
  FstSlice* slice = &node->data;
  uint8_t*  data = fstSliceData(slice, NULL);
463 464
  uint64_t  at = node->start - fstStateNtransLen(s) - 1  // pack size
                - fstStateTotalTransSize(s, node->version, node->sizes, node->nTrans) - (i * oSizes) - oSizes;
dengyihao's avatar
dengyihao 已提交
465 466

  return unpackUint64(data + at, oSizes);
dengyihao's avatar
dengyihao 已提交
467 468 469 470
}

// anyTrans specify function

dengyihao's avatar
dengyihao 已提交
471
void fstStateSetFinalState(FstState* s, bool yes) {
472
  assert(s->state == AnyTrans);
dengyihao's avatar
dengyihao 已提交
473 474 475
  if (yes) {
    s->val |= 0b01000000;
  }
dengyihao's avatar
dengyihao 已提交
476 477
  return;
}
dengyihao's avatar
dengyihao 已提交
478
bool fstStateIsFinalState(FstState* s) {
479 480 481
  assert(s->state == AnyTrans);
  return (s->val & 0b01000000) == 0b01000000;
}
dengyihao's avatar
dengyihao 已提交
482

dengyihao's avatar
dengyihao 已提交
483
void fstStateSetStateNtrans(FstState* s, uint8_t n) {
484
  assert(s->state == AnyTrans);
dengyihao's avatar
dengyihao 已提交
485 486 487
  if (n <= 0b00111111) {
    s->val = (s->val & 0b11000000) | n;
  }
dengyihao's avatar
dengyihao 已提交
488 489 490
  return;
}
// state_ntrans
dengyihao's avatar
dengyihao 已提交
491
uint8_t fstStateStateNtrans(FstState* s, bool* null) {
492
  assert(s->state == AnyTrans);
dengyihao's avatar
dengyihao 已提交
493
  *null = false;
494
  uint8_t n = s->val & 0b00111111;
dengyihao's avatar
dengyihao 已提交
495 496

  if (n == 0) {
497 498
    *null = true;  // None
  }
dengyihao's avatar
dengyihao 已提交
499
  return n;
dengyihao's avatar
dengyihao 已提交
500
}
dengyihao's avatar
dengyihao 已提交
501
uint64_t fstStateTotalTransSize(FstState* s, uint64_t version, PackSizes sizes, uint64_t nTrans) {
502 503
  assert(s->state == AnyTrans);
  uint64_t idxSize = fstStateTransIndexSize(s, version, nTrans);
dengyihao's avatar
dengyihao 已提交
504
  return nTrans + (nTrans * FST_GET_TRANSITION_PACK_SIZE(sizes)) + idxSize;
dengyihao's avatar
dengyihao 已提交
505
}
dengyihao's avatar
dengyihao 已提交
506
uint64_t fstStateTransIndexSize(FstState* s, uint64_t version, uint64_t nTrans) {
507 508
  assert(s->state == AnyTrans);
  return (version >= 2 && nTrans > TRANS_INDEX_THRESHOLD) ? 256 : 0;
dengyihao's avatar
dengyihao 已提交
509
}
dengyihao's avatar
dengyihao 已提交
510
uint64_t fstStateNtransLen(FstState* s) {
dengyihao's avatar
dengyihao 已提交
511 512 513
  assert(s->state == AnyTrans);
  bool null = false;
  fstStateStateNtrans(s, &null);
514
  return null == true ? 1 : 0;
dengyihao's avatar
dengyihao 已提交
515
}
dengyihao's avatar
dengyihao 已提交
516
uint64_t fstStateNtrans(FstState* s, FstSlice* slice) {
517
  bool    null = false;
dengyihao's avatar
dengyihao 已提交
518
  uint8_t n = fstStateStateNtrans(s, &null);
dengyihao's avatar
dengyihao 已提交
519 520 521
  if (null != true) {
    return n;
  }
522
  int32_t  len;
dengyihao's avatar
dengyihao 已提交
523
  uint8_t* data = fstSliceData(slice, &len);
dengyihao's avatar
dengyihao 已提交
524
  n = data[len - 2];
525 526 527 528
  // n = data[slice->end - 1]; // data[data.len() - 2]
  return n == 1 ? 256 : n;  // // "1" is never a normal legal value here, because if there, // is only 1 transition,
                            // then it is encoded in the state byte
}
dengyihao's avatar
dengyihao 已提交
529
Output fstStateFinalOutput(FstState* s, uint64_t version, FstSlice* slice, PackSizes sizes, uint64_t nTrans) {
530
  uint8_t oSizes = FST_GET_OUTPUT_PACK_SIZE(sizes);
dengyihao's avatar
dengyihao 已提交
531 532 533
  if (oSizes == 0 || !fstStateIsFinalState(s)) {
    return 0;
  }
dengyihao's avatar
dengyihao 已提交
534

535 536
  uint64_t at = FST_SLICE_LEN(slice) - 1 - fstStateNtransLen(s) - 1  // pack size
                - fstStateTotalTransSize(s, version, sizes, nTrans) - (nTrans * oSizes) - oSizes;
dengyihao's avatar
dengyihao 已提交
537
  uint8_t* data = fstSliceData(slice, NULL);
538
  return unpackUint64(data + at, (uint8_t)oSizes);
dengyihao's avatar
dengyihao 已提交
539
}
dengyihao's avatar
dengyihao 已提交
540
uint64_t fstStateFindInput(FstState* s, FstNode* node, uint8_t b, bool* null) {
dengyihao's avatar
dengyihao 已提交
541
  assert(s->state == AnyTrans);
dengyihao's avatar
dengyihao 已提交
542
  FstSlice* slice = &node->data;
dengyihao's avatar
dengyihao 已提交
543
  if (node->version >= 2 && node->nTrans > TRANS_INDEX_THRESHOLD) {
544
    uint64_t at = node->start - fstStateNtransLen(s) - 1  // pack size
dengyihao's avatar
dengyihao 已提交
545
                  - fstStateTransIndexSize(s, node->version, node->nTrans);
546
    int32_t  dlen = 0;
dengyihao's avatar
dengyihao 已提交
547
    uint8_t* data = fstSliceData(slice, &dlen);
dengyihao's avatar
dengyihao 已提交
548
    uint64_t i = data[at + b];
549
    // uint64_t i = slice->data[slice->start + at + b];
dengyihao's avatar
dengyihao 已提交
550 551 552
    if (i >= node->nTrans) {
      *null = true;
    }
dengyihao's avatar
dengyihao 已提交
553 554
    return i;
  } else {
555 556 557
    uint64_t start = node->start - fstStateNtransLen(s) - 1  // pack size
                     - node->nTrans;
    uint64_t end = start + node->nTrans;
dengyihao's avatar
dengyihao 已提交
558
    FstSlice t = fstSliceCopy(slice, start, end - 1);
559
    int32_t  len = 0;
dengyihao's avatar
dengyihao 已提交
560
    uint8_t* data = fstSliceData(&t, &len);
561 562 563
    int      i = 0;
    for (; i < len; i++) {
      uint8_t v = data[i];
dengyihao's avatar
dengyihao 已提交
564
      if (v == b) {
dengyihao's avatar
dengyihao 已提交
565
        fstSliceDestroy(&t);
566
        return node->nTrans - i - 1;  // bug
dengyihao's avatar
dengyihao 已提交
567
      }
568
    }
dengyihao's avatar
dengyihao 已提交
569 570 571
    if (i == len) {
      *null = true;
    }
dengyihao's avatar
dengyihao 已提交
572
    fstSliceDestroy(&t);
573
  }
574 575

  return 0;
dengyihao's avatar
dengyihao 已提交
576 577
}

578
// fst node function
dengyihao's avatar
dengyihao 已提交
579

dengyihao's avatar
dengyihao 已提交
580
FstNode* fstNodeCreate(int64_t version, CompiledAddr addr, FstSlice* slice) {
wafwerar's avatar
wafwerar 已提交
581
  FstNode* n = (FstNode*)taosMemoryMalloc(sizeof(FstNode));
dengyihao's avatar
dengyihao 已提交
582 583 584
  if (n == NULL) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
585

586
  FstState st = fstStateCreateFrom(slice, addr);
dengyihao's avatar
dengyihao 已提交
587 588

  if (st.state == EmptyFinal) {
589 590 591 592 593 594 595 596 597
    n->data = fstSliceCreate(NULL, 0);
    n->version = version;
    n->state = st;
    n->start = EMPTY_ADDRESS;
    n->end = EMPTY_ADDRESS;
    n->isFinal = true;
    n->nTrans = 0;
    n->sizes = 0;
    n->finalOutput = 0;
dengyihao's avatar
dengyihao 已提交
598
  } else if (st.state == OneTransNext) {
599 600 601 602 603 604 605 606 607
    n->data = fstSliceCopy(slice, 0, addr);
    n->version = version;
    n->state = st;
    n->start = addr;
    n->end = fstStateEndAddrForOneTransNext(&st, &n->data);  //? s.end_addr(data);
    n->isFinal = false;
    n->sizes = 0;
    n->nTrans = 1;
    n->finalOutput = 0;
dengyihao's avatar
dengyihao 已提交
608
  } else if (st.state == OneTrans) {
609 610 611 612 613 614 615 616 617 618 619
    FstSlice  data = fstSliceCopy(slice, 0, addr);
    PackSizes sz = fstStateSizes(&st, &data);
    n->data = data;
    n->version = version;
    n->state = st;
    n->start = addr;
    n->end = fstStateEndAddrForOneTrans(&st, &data, sz);  // s.end_addr(data, sz);
    n->isFinal = false;
    n->nTrans = 1;
    n->sizes = sz;
    n->finalOutput = 0;
dengyihao's avatar
dengyihao 已提交
620
  } else {
621 622 623 624 625 626 627 628 629 630 631
    FstSlice data = fstSliceCopy(slice, 0, addr);
    uint64_t sz = fstStateSizes(&st, &data);       // s.sizes(data)
    uint32_t nTrans = fstStateNtrans(&st, &data);  // s.ntrans(data)
    n->data = data;
    n->version = version;
    n->state = st;
    n->start = addr;
    n->end = fstStateEndAddrForAnyTrans(&st, version, &data, sz, nTrans);  // s.end_addr(version, data, sz, ntrans);
    n->isFinal = fstStateIsFinalState(&st);                                // s.is_final_state();
    n->nTrans = nTrans;
    n->sizes = sz;
dengyihao's avatar
dengyihao 已提交
632 633
    n->finalOutput =
        fstStateFinalOutput(&st, version, &data, sz, nTrans);  // s.final_output(version, data, sz, ntrans);
634 635
  }
  return n;
dengyihao's avatar
dengyihao 已提交
636
}
dengyihao's avatar
dengyihao 已提交
637 638

// debug state transition
dengyihao's avatar
dengyihao 已提交
639 640
static const char* fstNodeState(FstNode* node) {
  FstState* st = &node->state;
641
  return fstStateStr[st->state];
dengyihao's avatar
dengyihao 已提交
642 643
}

dengyihao's avatar
dengyihao 已提交
644
void fstNodeDestroy(FstNode* node) {
645
  fstSliceDestroy(&node->data);
wafwerar's avatar
wafwerar 已提交
646
  taosMemoryFree(node);
dengyihao's avatar
dengyihao 已提交
647
}
dengyihao's avatar
dengyihao 已提交
648
FstTransitions* fstNodeTransitions(FstNode* node) {
wafwerar's avatar
wafwerar 已提交
649
  FstTransitions* t = taosMemoryMalloc(sizeof(FstTransitions));
dengyihao's avatar
dengyihao 已提交
650 651 652
  if (NULL == t) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
653 654
  FstRange range = {.start = 0, .end = FST_NODE_LEN(node)};
  t->range = range;
655 656 657
  t->node = node;
  return t;
}
dengyihao's avatar
dengyihao 已提交
658

659
// Returns the transition at index `i`.
dengyihao's avatar
dengyihao 已提交
660
bool fstNodeGetTransitionAt(FstNode* node, uint64_t i, FstTransition* trn) {
661
  bool      s = true;
dengyihao's avatar
dengyihao 已提交
662
  FstState* st = &node->state;
dengyihao's avatar
dengyihao 已提交
663
  if (st->state == OneTransNext) {
664 665 666
    trn->inp = fstStateInput(st, node);
    trn->out = 0;
    trn->addr = fstStateTransAddr(st, node);
dengyihao's avatar
dengyihao 已提交
667
  } else if (st->state == OneTrans) {
668 669 670
    trn->inp = fstStateInput(st, node);
    trn->out = fstStateOutput(st, node);
    trn->addr = fstStateTransAddr(st, node);
dengyihao's avatar
dengyihao 已提交
671
  } else if (st->state == AnyTrans) {
672 673 674
    trn->inp = fstStateInputForAnyTrans(st, node, i);
    trn->out = fstStateOutputForAnyTrans(st, node, i);
    trn->addr = fstStateTransAddrForAnyTrans(st, node, i);
dengyihao's avatar
dengyihao 已提交
675 676 677 678
  } else {
    s = false;
  }
  return s;
679
}
dengyihao's avatar
dengyihao 已提交
680

dengyihao's avatar
dengyihao 已提交
681
// Returns the transition address of the `i`th transition
dengyihao's avatar
dengyihao 已提交
682
bool fstNodeGetTransitionAddrAt(FstNode* node, uint64_t i, CompiledAddr* res) {
683
  bool      s = true;
dengyihao's avatar
dengyihao 已提交
684
  FstState* st = &node->state;
dengyihao's avatar
dengyihao 已提交
685 686 687 688
  if (st->state == OneTransNext) {
    assert(i == 0);
    fstStateTransAddr(st, node);
  } else if (st->state == OneTrans) {
689
    assert(i == 0);
dengyihao's avatar
dengyihao 已提交
690 691 692
    fstStateTransAddr(st, node);
  } else if (st->state == AnyTrans) {
    fstStateTransAddrForAnyTrans(st, node, i);
693
  } else if (FST_STATE_EMPTY_FINAL(node)) {
dengyihao's avatar
dengyihao 已提交
694
    s = false;
dengyihao's avatar
dengyihao 已提交
695 696
  } else {
    assert(0);
dengyihao's avatar
dengyihao 已提交
697 698
  }
  return s;
dengyihao's avatar
dengyihao 已提交
699 700
}

dengyihao's avatar
dengyihao 已提交
701
//  Finds the `i`th transition corresponding to the given input byte.
702
//  If no transition for this byte exists, then `false` is returned.
dengyihao's avatar
dengyihao 已提交
703
bool fstNodeFindInput(FstNode* node, uint8_t b, uint64_t* res) {
704
  bool      s = true;
dengyihao's avatar
dengyihao 已提交
705
  FstState* st = &node->state;
dengyihao's avatar
dengyihao 已提交
706
  if (st->state == OneTransNext) {
707 708 709 710 711 712 713 714 715 716 717
    if (fstStateInput(st, node) == b) {
      *res = 0;
    } else {
      s = false;
    }
  } else if (st->state == OneTrans) {
    if (fstStateInput(st, node) == b) {
      *res = 0;
    } else {
      s = false;
    }
dengyihao's avatar
dengyihao 已提交
718
  } else if (st->state == AnyTrans) {
719 720 721 722
    bool     null = false;
    uint64_t out = fstStateFindInput(st, node, b, &null);
    if (null == false) {
      *res = out;
dengyihao's avatar
dengyihao 已提交
723
    } else {
724 725
      s = false;
    }
dengyihao's avatar
dengyihao 已提交
726
  }
dengyihao's avatar
dengyihao 已提交
727
  return s;
728
}
dengyihao's avatar
dengyihao 已提交
729

dengyihao's avatar
dengyihao 已提交
730
bool fstNodeCompile(FstNode* node, void* w, CompiledAddr lastAddr, CompiledAddr addr, FstBuilderNode* builderNode) {
731
  size_t sz = taosArrayGetSize(builderNode->trans);
dengyihao's avatar
dengyihao 已提交
732 733
  assert(sz < 256);
  if (sz == 0 && builderNode->isFinal && builderNode->finalOutput == 0) {
734
    return true;
dengyihao's avatar
dengyihao 已提交
735
  } else if (sz != 1 || builderNode->isFinal) {
736
    fstStateCompileForAnyTrans(w, addr, builderNode);
dengyihao's avatar
dengyihao 已提交
737 738
    // AnyTrans->Compile(w, addr, node);
  } else {
dengyihao's avatar
dengyihao 已提交
739
    FstTransition* tran = taosArrayGet(builderNode->trans, 0);
dengyihao's avatar
dengyihao 已提交
740
    if (tran->addr == lastAddr && tran->out == 0) {
741 742 743
      fstStateCompileForOneTransNext(w, addr, tran->inp);
      // OneTransNext::compile(w, lastAddr, tran->inp);
      return true;
dengyihao's avatar
dengyihao 已提交
744
    } else {
745 746 747 748 749 750 751
      fstStateCompileForOneTrans(w, addr, tran);
      // OneTrans::Compile(w, lastAddr, *tran);
      return true;
    }
  }
  return true;
}
dengyihao's avatar
dengyihao 已提交
752

dengyihao's avatar
dengyihao 已提交
753
bool fstBuilderNodeCompileTo(FstBuilderNode* b, FstCountingWriter* wrt, CompiledAddr lastAddr, CompiledAddr startAddr) {
dengyihao's avatar
dengyihao 已提交
754 755 756
  return fstNodeCompile(NULL, wrt, lastAddr, startAddr, b);
}

dengyihao's avatar
dengyihao 已提交
757
FstBuilder* fstBuilderCreate(void* w, FstType ty) {
wafwerar's avatar
wafwerar 已提交
758
  FstBuilder* b = taosMemoryMalloc(sizeof(FstBuilder));
dengyihao's avatar
dengyihao 已提交
759 760 761
  if (NULL == b) {
    return b;
  }
dengyihao's avatar
dengyihao 已提交
762

763 764 765 766 767 768
  b->wrt = fstCountingWriterCreate(w);
  b->unfinished = fstUnFinishedNodesCreate();
  b->registry = fstRegistryCreate(10000, 2);
  b->last = fstSliceCreate(NULL, 0);
  b->lastAddr = NONE_ADDRESS;
  b->len = 0;
dengyihao's avatar
dengyihao 已提交
769

770
  char  buf64[8] = {0};
dengyihao's avatar
dengyihao 已提交
771
  void* pBuf64 = buf64;
772
  taosEncodeFixedU64(&pBuf64, VERSION);
dengyihao's avatar
dengyihao 已提交
773
  fstCountingWriterWrite(b->wrt, buf64, sizeof(buf64));
774

dengyihao's avatar
dengyihao 已提交
775
  pBuf64 = buf64;
dengyihao's avatar
dengyihao 已提交
776
  memset(buf64, 0, sizeof(buf64));
777
  taosEncodeFixedU64(&pBuf64, ty);
dengyihao's avatar
dengyihao 已提交
778 779
  fstCountingWriterWrite(b->wrt, buf64, sizeof(buf64));

dengyihao's avatar
dengyihao 已提交
780 781
  return b;
}
dengyihao's avatar
dengyihao 已提交
782
void fstBuilderDestroy(FstBuilder* b) {
dengyihao's avatar
dengyihao 已提交
783 784 785
  if (b == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
786

787 788
  fstCountingWriterDestroy(b->wrt);
  fstUnFinishedNodesDestroy(b->unfinished);
dengyihao's avatar
dengyihao 已提交
789
  fstRegistryDestroy(b->registry);
dengyihao's avatar
dengyihao 已提交
790
  fstSliceDestroy(&b->last);
wafwerar's avatar
wafwerar 已提交
791
  taosMemoryFree(b);
dengyihao's avatar
dengyihao 已提交
792
}
dengyihao's avatar
dengyihao 已提交
793

dengyihao's avatar
dengyihao 已提交
794
bool fstBuilderInsert(FstBuilder* b, FstSlice bs, Output in) {
795
  OrderType t = fstBuilderCheckLastKey(b, bs, true);
dengyihao's avatar
dengyihao 已提交
796 797
  if (t == Ordered) {
    // add log info
798 799 800
    fstBuilderInsertOutput(b, bs, in);
    return true;
  }
dengyihao's avatar
dengyihao 已提交
801
  indexInfo("fst write key must be ordered");
dengyihao's avatar
dengyihao 已提交
802 803 804
  return false;
}

dengyihao's avatar
dengyihao 已提交
805 806
void fstBuilderInsertOutput(FstBuilder* b, FstSlice bs, Output in) {
  FstSlice* s = &bs;
807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
  if (fstSliceIsEmpty(s)) {
    b->len = 1;
    fstUnFinishedNodesSetRootOutput(b->unfinished, in);
    return;
  }
  // if (in != 0) { //if let Some(in) = in
  //   prefixLen = fstUnFinishedNodesFindCommPrefixAndSetOutput(b->unfinished, bs, in, &out);
  //} else {
  //   prefixLen = fstUnFinishedNodesFindCommPrefix(b->unfinished, bs);
  //   out = 0;
  //}
  Output   out;
  uint64_t prefixLen = fstUnFinishedNodesFindCommPrefixAndSetOutput(b->unfinished, bs, in, &out);

  if (prefixLen == FST_SLICE_LEN(s)) {
    assert(out == 0);
    return;
  }

  b->len += 1;
  fstBuilderCompileFrom(b, prefixLen);

  FstSlice sub = fstSliceCopy(s, prefixLen, s->end);
  fstUnFinishedNodesAddSuffix(b->unfinished, sub, out);
  fstSliceDestroy(&sub);
  return;
}
dengyihao's avatar
dengyihao 已提交
834

dengyihao's avatar
dengyihao 已提交
835 836
OrderType fstBuilderCheckLastKey(FstBuilder* b, FstSlice bs, bool ckDup) {
  FstSlice* input = &bs;
dengyihao's avatar
dengyihao 已提交
837
  if (fstSliceIsEmpty(&b->last)) {
dengyihao's avatar
dengyihao 已提交
838
    fstSliceDestroy(&b->last);
dengyihao's avatar
dengyihao 已提交
839
    // deep copy or not
dengyihao's avatar
dengyihao 已提交
840
    b->last = fstSliceDeepCopy(&bs, input->start, input->end);
dengyihao's avatar
dengyihao 已提交
841 842 843
  } else {
    int comp = fstSliceCompare(&b->last, &bs);
    if (comp == 0 && ckDup) {
844
      return DuplicateKey;
dengyihao's avatar
dengyihao 已提交
845 846 847 848
    } else if (comp == 1) {
      return OutOfOrdered;
    }
    // deep copy or not
dengyihao's avatar
dengyihao 已提交
849
    fstSliceDestroy(&b->last);
850 851
    b->last = fstSliceDeepCopy(&bs, input->start, input->end);
  }
dengyihao's avatar
dengyihao 已提交
852
  return Ordered;
853
}
dengyihao's avatar
dengyihao 已提交
854
void fstBuilderCompileFrom(FstBuilder* b, uint64_t istate) {
dengyihao's avatar
dengyihao 已提交
855 856
  CompiledAddr addr = NONE_ADDRESS;
  while (istate + 1 < FST_UNFINISHED_NODES_LEN(b->unfinished)) {
dengyihao's avatar
dengyihao 已提交
857
    FstBuilderNode* bn = NULL;
dengyihao's avatar
dengyihao 已提交
858
    if (addr == NONE_ADDRESS) {
dengyihao's avatar
dengyihao 已提交
859
      bn = fstUnFinishedNodesPopEmpty(b->unfinished);
dengyihao's avatar
dengyihao 已提交
860
    } else {
dengyihao's avatar
dengyihao 已提交
861
      bn = fstUnFinishedNodesPopFreeze(b->unfinished, addr);
dengyihao's avatar
dengyihao 已提交
862
    }
dengyihao's avatar
dengyihao 已提交
863 864 865
    addr = fstBuilderCompile(b, bn);

    fstBuilderNodeDestroy(bn);
866 867
    assert(addr != NONE_ADDRESS);
    // fstBuilderNodeDestroy(n);
dengyihao's avatar
dengyihao 已提交
868 869
  }
  fstUnFinishedNodesTopLastFreeze(b->unfinished, addr);
870
  return;
dengyihao's avatar
dengyihao 已提交
871
}
dengyihao's avatar
dengyihao 已提交
872

dengyihao's avatar
dengyihao 已提交
873
CompiledAddr fstBuilderCompile(FstBuilder* b, FstBuilderNode* bn) {
874 875
  if (FST_BUILDER_NODE_IS_FINAL(bn) && FST_BUILDER_NODE_TRANS_ISEMPTY(bn) && FST_BUILDER_NODE_FINALOUTPUT_ISZERO(bn)) {
    return EMPTY_ADDRESS;
dengyihao's avatar
dengyihao 已提交
876
  }
dengyihao's avatar
dengyihao 已提交
877
  FstRegistryEntry* entry = fstRegistryGetEntry(b->registry, bn);
878
  if (entry->state == FOUND) {
dengyihao's avatar
dengyihao 已提交
879
    CompiledAddr ret = entry->addr;
dengyihao's avatar
dengyihao 已提交
880
    fstRegistryEntryDestroy(entry);
dengyihao's avatar
dengyihao 已提交
881
    return ret;
882
  }
dengyihao's avatar
dengyihao 已提交
883 884
  CompiledAddr startAddr = (CompiledAddr)(FST_WRITER_COUNT(b->wrt));

885 886
  fstBuilderNodeCompileTo(bn, b->wrt, b->lastAddr, startAddr);
  b->lastAddr = (CompiledAddr)(FST_WRITER_COUNT(b->wrt) - 1);
dengyihao's avatar
dengyihao 已提交
887 888 889
  if (entry->state == NOTFOUND) {
    FST_REGISTRY_CELL_INSERT(entry->cell, b->lastAddr);
  }
dengyihao's avatar
dengyihao 已提交
890
  fstRegistryEntryDestroy(entry);
891 892

  return b->lastAddr;
dengyihao's avatar
dengyihao 已提交
893 894
}

dengyihao's avatar
dengyihao 已提交
895
void* fstBuilderInsertInner(FstBuilder* b) {
896
  fstBuilderCompileFrom(b, 0);
dengyihao's avatar
dengyihao 已提交
897
  FstBuilderNode* rootNode = fstUnFinishedNodesPopRoot(b->unfinished);
898
  CompiledAddr    rootAddr = fstBuilderCompile(b, rootNode);
dengyihao's avatar
dengyihao 已提交
899
  fstBuilderNodeDestroy(rootNode);
dengyihao's avatar
dengyihao 已提交
900

901 902
  char buf64[8] = {0};

dengyihao's avatar
dengyihao 已提交
903
  void* pBuf64 = buf64;
904 905
  taosEncodeFixedU64(&pBuf64, b->len);
  fstCountingWriterWrite(b->wrt, buf64, sizeof(buf64));
dengyihao's avatar
dengyihao 已提交
906

dengyihao's avatar
dengyihao 已提交
907
  pBuf64 = buf64;
908 909
  taosEncodeFixedU64(&pBuf64, rootAddr);
  fstCountingWriterWrite(b->wrt, buf64, sizeof(buf64));
dengyihao's avatar
dengyihao 已提交
910

911
  char     buf32[4] = {0};
dengyihao's avatar
dengyihao 已提交
912
  void*    pBuf32 = buf32;
dengyihao's avatar
dengyihao 已提交
913
  uint32_t sum = fstCountingWriterMaskedCheckSum(b->wrt);
914 915 916
  taosEncodeFixedU32(&pBuf32, sum);
  fstCountingWriterWrite(b->wrt, buf32, sizeof(buf32));

dengyihao's avatar
dengyihao 已提交
917
  fstCountingWriterFlush(b->wrt);
918 919
  // fstCountingWriterDestroy(b->wrt);
  // b->wrt = NULL;
dengyihao's avatar
dengyihao 已提交
920 921
  return b->wrt;
}
dengyihao's avatar
dengyihao 已提交
922
void fstBuilderFinish(FstBuilder* b) { fstBuilderInsertInner(b); }
dengyihao's avatar
dengyihao 已提交
923

dengyihao's avatar
dengyihao 已提交
924 925
FstSlice fstNodeAsSlice(FstNode* node) {
  FstSlice* slice = &node->data;
926 927
  FstSlice  s = fstSliceCopy(slice, slice->end, FST_SLICE_LEN(slice) - 1);
  return s;
dengyihao's avatar
dengyihao 已提交
928
}
dengyihao's avatar
dengyihao 已提交
929

dengyihao's avatar
dengyihao 已提交
930
FstLastTransition* fstLastTransitionCreate(uint8_t inp, Output out) {
wafwerar's avatar
wafwerar 已提交
931
  FstLastTransition* trn = taosMemoryMalloc(sizeof(FstLastTransition));
dengyihao's avatar
dengyihao 已提交
932 933 934
  if (trn == NULL) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
935 936 937 938 939 940

  trn->inp = inp;
  trn->out = out;
  return trn;
}

wafwerar's avatar
wafwerar 已提交
941
void fstLastTransitionDestroy(FstLastTransition* trn) { taosMemoryFree(trn); }
dengyihao's avatar
dengyihao 已提交
942

dengyihao's avatar
dengyihao 已提交
943 944
void fstBuilderNodeUnfinishedLastCompiled(FstBuilderNodeUnfinished* unNode, CompiledAddr addr) {
  FstLastTransition* trn = unNode->last;
dengyihao's avatar
dengyihao 已提交
945 946 947
  if (trn == NULL) {
    return;
  }
948 949 950
  FstTransition t = {.inp = trn->inp, .out = trn->out, .addr = addr};
  taosArrayPush(unNode->node->trans, &t);
  fstLastTransitionDestroy(trn);
dengyihao's avatar
dengyihao 已提交
951
  unNode->last = NULL;
dengyihao's avatar
dengyihao 已提交
952 953 954
  return;
}

dengyihao's avatar
dengyihao 已提交
955
void fstBuilderNodeUnfinishedAddOutputPrefix(FstBuilderNodeUnfinished* unNode, Output out) {
dengyihao's avatar
dengyihao 已提交
956 957 958
  if (FST_BUILDER_NODE_IS_FINAL(unNode->node)) {
    unNode->node->finalOutput += out;
  }
dengyihao's avatar
dengyihao 已提交
959 960
  size_t sz = taosArrayGetSize(unNode->node->trans);
  for (size_t i = 0; i < sz; i++) {
dengyihao's avatar
dengyihao 已提交
961
    FstTransition* trn = taosArrayGet(unNode->node->trans, i);
dengyihao's avatar
dengyihao 已提交
962 963
    trn->out += out;
  }
dengyihao's avatar
dengyihao 已提交
964 965 966
  if (unNode->last) {
    unNode->last->out += out;
  }
dengyihao's avatar
dengyihao 已提交
967 968 969
  return;
}

dengyihao's avatar
dengyihao 已提交
970
Fst* fstCreate(FstSlice* slice) {
dengyihao's avatar
dengyihao 已提交
971
  int32_t slen;
dengyihao's avatar
dengyihao 已提交
972
  char*   buf = fstSliceData(slice, &slen);
dengyihao's avatar
dengyihao 已提交
973 974 975
  if (slen < 36) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
976
  uint64_t len = slen;
977
  uint64_t skip = 0;
dengyihao's avatar
dengyihao 已提交
978

979 980 981
  uint64_t version;
  taosDecodeFixedU64(buf, &version);
  skip += sizeof(version);
dengyihao's avatar
dengyihao 已提交
982 983 984
  if (version == 0 || version > VERSION) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
985 986 987

  uint64_t type;
  taosDecodeFixedU64(buf + skip, &type);
988
  skip += sizeof(type);
dengyihao's avatar
dengyihao 已提交
989 990 991

  uint32_t checkSum = 0;
  len -= sizeof(checkSum);
992
  taosDecodeFixedU32(buf + len, &checkSum);
dengyihao's avatar
dengyihao 已提交
993
  if (taosCheckChecksum(buf, len, checkSum)) {
dengyihao's avatar
dengyihao 已提交
994
    indexError("index file is corrupted");
dengyihao's avatar
dengyihao 已提交
995 996 997
    // verify fst
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
998
  CompiledAddr rootAddr;
999 1000
  len -= sizeof(rootAddr);
  taosDecodeFixedU64(buf + len, &rootAddr);
dengyihao's avatar
dengyihao 已提交
1001

1002 1003
  uint64_t fstLen;
  len -= sizeof(fstLen);
dengyihao's avatar
dengyihao 已提交
1004
  taosDecodeFixedU64(buf + len, &fstLen);
1005
  // TODO(validate root addr)
wafwerar's avatar
wafwerar 已提交
1006
  Fst* fst = (Fst*)taosMemoryCalloc(1, sizeof(Fst));
dengyihao's avatar
dengyihao 已提交
1007 1008 1009
  if (fst == NULL) {
    return NULL;
  }
1010

wafwerar's avatar
wafwerar 已提交
1011
  fst->meta = (FstMeta*)taosMemoryMalloc(sizeof(FstMeta));
dengyihao's avatar
dengyihao 已提交
1012 1013 1014
  if (NULL == fst->meta) {
    goto FST_CREAT_FAILED;
  }
dengyihao's avatar
dengyihao 已提交
1015

1016 1017 1018 1019
  fst->meta->version = version;
  fst->meta->rootAddr = rootAddr;
  fst->meta->ty = type;
  fst->meta->len = fstLen;
dengyihao's avatar
dengyihao 已提交
1020
  fst->meta->checkSum = checkSum;
dengyihao's avatar
dengyihao 已提交
1021

wafwerar's avatar
wafwerar 已提交
1022
  FstSlice* s = taosMemoryCalloc(1, sizeof(FstSlice));
dengyihao's avatar
dengyihao 已提交
1023
  *s = fstSliceCopy(slice, 0, FST_SLICE_LEN(slice) - 1);
1024 1025
  fst->data = s;

wafwerar's avatar
wafwerar 已提交
1026
  taosThreadMutexInit(&fst->mtx, NULL);
dengyihao's avatar
dengyihao 已提交
1027 1028
  return fst;

1029
FST_CREAT_FAILED:
wafwerar's avatar
wafwerar 已提交
1030 1031
  taosMemoryFree(fst->meta);
  taosMemoryFree(fst);
1032 1033

  return NULL;
dengyihao's avatar
dengyihao 已提交
1034
}
dengyihao's avatar
dengyihao 已提交
1035
void fstDestroy(Fst* fst) {
1036
  if (fst) {
wafwerar's avatar
wafwerar 已提交
1037
    taosMemoryFree(fst->meta);
dengyihao's avatar
dengyihao 已提交
1038
    fstSliceDestroy(fst->data);
wafwerar's avatar
wafwerar 已提交
1039
    taosMemoryFree(fst->data);
wafwerar's avatar
wafwerar 已提交
1040
    taosThreadMutexDestroy(&fst->mtx);
1041
  }
wafwerar's avatar
wafwerar 已提交
1042
  taosMemoryFree(fst);
dengyihao's avatar
dengyihao 已提交
1043 1044
}

dengyihao's avatar
dengyihao 已提交
1045
bool fstGet(Fst* fst, FstSlice* b, Output* out) {
dengyihao's avatar
dengyihao 已提交
1046
  // dec lock range
wafwerar's avatar
wafwerar 已提交
1047
  // taosThreadMutexLock(&fst->mtx);
dengyihao's avatar
dengyihao 已提交
1048
  FstNode* root = fstGetRoot(fst);
1049 1050
  Output   tOut = 0;
  int32_t  len;
dengyihao's avatar
dengyihao 已提交
1051

dengyihao's avatar
dengyihao 已提交
1052
  uint8_t* data = fstSliceData(b, &len);
dengyihao's avatar
dengyihao 已提交
1053

dengyihao's avatar
dengyihao 已提交
1054
  SArray* nodes = (SArray*)taosArrayInit(len, sizeof(FstNode*));
dengyihao's avatar
dengyihao 已提交
1055
  taosArrayPush(nodes, &root);
dengyihao's avatar
dengyihao 已提交
1056 1057
  for (uint32_t i = 0; i < len; i++) {
    uint8_t inp = data[i];
dengyihao's avatar
dengyihao 已提交
1058
    Output  res = 0;
dengyihao's avatar
dengyihao 已提交
1059
    if (false == fstNodeFindInput(root, inp, &res)) {
wafwerar's avatar
wafwerar 已提交
1060
      // taosThreadMutexUnlock(&fst->mtx);
dengyihao's avatar
dengyihao 已提交
1061 1062
      return false;
    }
dengyihao's avatar
dengyihao 已提交
1063

1064
    FstTransition trn;
dengyihao's avatar
dengyihao 已提交
1065
    fstNodeGetTransitionAt(root, res, &trn);
1066
    tOut += trn.out;
dengyihao's avatar
dengyihao 已提交
1067
    root = fstGetNode(fst, trn.addr);
dengyihao's avatar
dengyihao 已提交
1068
    taosArrayPush(nodes, &root);
dengyihao's avatar
dengyihao 已提交
1069 1070
  }
  if (!FST_NODE_IS_FINAL(root)) {
wafwerar's avatar
wafwerar 已提交
1071
    // taosThreadMutexUnlock(&fst->mtx);
dengyihao's avatar
dengyihao 已提交
1072 1073
    return false;
  } else {
1074
    tOut = tOut + FST_NODE_FINAL_OUTPUT(root);
dengyihao's avatar
dengyihao 已提交
1075
  }
dengyihao's avatar
dengyihao 已提交
1076

dengyihao's avatar
dengyihao 已提交
1077
  for (size_t i = 0; i < taosArrayGetSize(nodes); i++) {
dengyihao's avatar
dengyihao 已提交
1078
    FstNode** node = (FstNode**)taosArrayGet(nodes, i);
1079
    fstNodeDestroy(*node);
dengyihao's avatar
dengyihao 已提交
1080 1081
  }
  taosArrayDestroy(nodes);
dengyihao's avatar
dengyihao 已提交
1082
  // fst->root = NULL;
wafwerar's avatar
wafwerar 已提交
1083
  // taosThreadMutexUnlock(&fst->mtx);
dengyihao's avatar
dengyihao 已提交
1084
  *out = tOut;
1085
  return true;
dengyihao's avatar
dengyihao 已提交
1086
}
dengyihao's avatar
dengyihao 已提交
1087
FstStreamBuilder* fstSearch(Fst* fst, AutomationCtx* ctx) {
dengyihao's avatar
dengyihao 已提交
1088
  // refactor later
dengyihao's avatar
dengyihao 已提交
1089 1090 1091
  return fstStreamBuilderCreate(fst, ctx);
}
StreamWithState* streamBuilderIntoStream(FstStreamBuilder* sb) {
dengyihao's avatar
dengyihao 已提交
1092 1093 1094
  if (sb == NULL) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
1095 1096
  return streamWithStateCreate(sb->fst, sb->aut, sb->min, sb->max);
}
dengyihao's avatar
dengyihao 已提交
1097
FstStreamWithStateBuilder* fstSearchWithState(Fst* fst, AutomationCtx* ctx) {
dengyihao's avatar
dengyihao 已提交
1098
  // refactor later
dengyihao's avatar
dengyihao 已提交
1099 1100
  return fstStreamBuilderCreate(fst, ctx);
}
dengyihao's avatar
dengyihao 已提交
1101

dengyihao's avatar
dengyihao 已提交
1102
FstNode* fstGetRoot(Fst* fst) {
1103
  CompiledAddr rAddr = fstGetRootAddr(fst);
dengyihao's avatar
dengyihao 已提交
1104
  return fstGetNode(fst, rAddr);
dengyihao's avatar
dengyihao 已提交
1105
}
dengyihao's avatar
dengyihao 已提交
1106

dengyihao's avatar
dengyihao 已提交
1107
FstNode* fstGetNode(Fst* fst, CompiledAddr addr) {
dengyihao's avatar
dengyihao 已提交
1108
  // refactor later
dengyihao's avatar
dengyihao 已提交
1109 1110
  return fstNodeCreate(fst->meta->version, addr, fst->data);
}
dengyihao's avatar
dengyihao 已提交
1111 1112
FstType      fstGetType(Fst* fst) { return fst->meta->ty; }
CompiledAddr fstGetRootAddr(Fst* fst) { return fst->meta->rootAddr; }
dengyihao's avatar
dengyihao 已提交
1113

dengyihao's avatar
dengyihao 已提交
1114
Output fstEmptyFinalOutput(Fst* fst, bool* null) {
1115
  Output   res = 0;
dengyihao's avatar
dengyihao 已提交
1116
  FstNode* node = fstGetRoot(fst);
dengyihao's avatar
dengyihao 已提交
1117 1118
  if (FST_NODE_IS_FINAL(node)) {
    *null = false;
1119
    res = FST_NODE_FINAL_OUTPUT(node);
dengyihao's avatar
dengyihao 已提交
1120 1121 1122
  } else {
    *null = true;
  }
1123
  fstNodeDestroy(node);
dengyihao's avatar
dengyihao 已提交
1124 1125 1126
  return res;
}

dengyihao's avatar
dengyihao 已提交
1127
bool fstVerify(Fst* fst) {
dengyihao's avatar
dengyihao 已提交
1128
  uint32_t len, checkSum = fst->meta->checkSum;
dengyihao's avatar
dengyihao 已提交
1129
  uint8_t* data = fstSliceData(fst->data, &len);
1130
  TSCKSUM  initSum = 0;
dengyihao's avatar
dengyihao 已提交
1131 1132 1133
  if (!taosCheckChecksumWhole(data, len)) {
    return false;
  }
dengyihao's avatar
dengyihao 已提交
1134
  return true;
dengyihao's avatar
dengyihao 已提交
1135 1136
}

dengyihao's avatar
dengyihao 已提交
1137
// data bound function
dengyihao's avatar
dengyihao 已提交
1138
FstBoundWithData* fstBoundStateCreate(FstBound type, FstSlice* data) {
wafwerar's avatar
wafwerar 已提交
1139
  FstBoundWithData* b = taosMemoryCalloc(1, sizeof(FstBoundWithData));
dengyihao's avatar
dengyihao 已提交
1140 1141 1142
  if (b == NULL) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
1143 1144 1145 1146 1147 1148

  if (data != NULL) {
    b->data = fstSliceCopy(data, data->start, data->end);
  } else {
    b->data = fstSliceCreate(NULL, 0);
  }
dengyihao's avatar
dengyihao 已提交
1149
  b->type = type;
dengyihao's avatar
dengyihao 已提交
1150

1151
  return b;
dengyihao's avatar
dengyihao 已提交
1152 1153
}

dengyihao's avatar
dengyihao 已提交
1154
bool fstBoundWithDataExceededBy(FstBoundWithData* bound, FstSlice* slice) {
dengyihao's avatar
dengyihao 已提交
1155 1156 1157 1158 1159 1160
  int comp = fstSliceCompare(slice, &bound->data);
  if (bound->type == Included) {
    return comp > 0 ? true : false;
  } else if (bound->type == Excluded) {
    return comp >= 0 ? true : false;
  } else {
dengyihao's avatar
dengyihao 已提交
1161
    return false;
dengyihao's avatar
dengyihao 已提交
1162 1163
  }
}
dengyihao's avatar
dengyihao 已提交
1164
bool fstBoundWithDataIsEmpty(FstBoundWithData* bound) {
dengyihao's avatar
dengyihao 已提交
1165 1166
  if (bound->type == Unbounded) {
    return true;
1167 1168 1169
  } else {
    return fstSliceIsEmpty(&bound->data);
  }
dengyihao's avatar
dengyihao 已提交
1170 1171
}

dengyihao's avatar
dengyihao 已提交
1172
bool fstBoundWithDataIsIncluded(FstBoundWithData* bound) { return bound->type == Excluded ? false : true; }
dengyihao's avatar
dengyihao 已提交
1173

wafwerar's avatar
wafwerar 已提交
1174
void fstBoundDestroy(FstBoundWithData* bound) { taosMemoryFree(bound); }
dengyihao's avatar
dengyihao 已提交
1175

dengyihao's avatar
dengyihao 已提交
1176 1177
StreamWithState* streamWithStateCreate(Fst* fst, AutomationCtx* automation, FstBoundWithData* min,
                                       FstBoundWithData* max) {
wafwerar's avatar
wafwerar 已提交
1178
  StreamWithState* sws = taosMemoryCalloc(1, sizeof(StreamWithState));
dengyihao's avatar
dengyihao 已提交
1179 1180 1181
  if (sws == NULL) {
    return NULL;
  }
1182 1183 1184

  sws->fst = fst;
  sws->aut = automation;
dengyihao's avatar
dengyihao 已提交
1185
  sws->inp = (SArray*)taosArrayInit(256, sizeof(uint8_t));
dengyihao's avatar
dengyihao 已提交
1186

dengyihao's avatar
dengyihao 已提交
1187
  sws->emptyOutput.null = true;
1188
  sws->emptyOutput.out = 0;
dengyihao's avatar
dengyihao 已提交
1189

dengyihao's avatar
dengyihao 已提交
1190
  sws->stack = (SArray*)taosArrayInit(256, sizeof(StreamState));
1191
  sws->endAt = max;
dengyihao's avatar
dengyihao 已提交
1192 1193 1194 1195
  streamWithStateSeekMin(sws, min);

  return sws;
}
dengyihao's avatar
dengyihao 已提交
1196
void streamWithStateDestroy(StreamWithState* sws) {
dengyihao's avatar
dengyihao 已提交
1197 1198 1199
  if (sws == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
1200 1201

  taosArrayDestroy(sws->inp);
dengyihao's avatar
dengyihao 已提交
1202
  taosArrayDestroyEx(sws->stack, streamStateDestroy);
dengyihao's avatar
dengyihao 已提交
1203

wafwerar's avatar
wafwerar 已提交
1204
  taosMemoryFree(sws);
dengyihao's avatar
dengyihao 已提交
1205 1206
}

dengyihao's avatar
dengyihao 已提交
1207 1208
bool streamWithStateSeekMin(StreamWithState* sws, FstBoundWithData* min) {
  AutomationCtx* aut = sws->aut;
dengyihao's avatar
dengyihao 已提交
1209
  if (fstBoundWithDataIsEmpty(min)) {
dengyihao's avatar
dengyihao 已提交
1210 1211 1212
    if (fstBoundWithDataIsIncluded(min)) {
      sws->emptyOutput.out = fstEmptyFinalOutput(sws->fst, &(sws->emptyOutput.null));
    }
1213
    StreamState s = {.node = fstGetRoot(sws->fst),
dengyihao's avatar
dengyihao 已提交
1214 1215 1216
                     .trans = 0,
                     .out = {.null = false, .out = 0},
                     .autState = automFuncs[aut->type].start(aut)};  // auto.start callback
dengyihao's avatar
dengyihao 已提交
1217 1218
    taosArrayPush(sws->stack, &s);
    return true;
1219
  }
dengyihao's avatar
dengyihao 已提交
1220
  FstSlice* key = NULL;
1221
  bool      inclusize = false;
dengyihao's avatar
dengyihao 已提交
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231

  if (min->type == Included) {
    key = &min->data;
    inclusize = true;
  } else if (min->type == Excluded) {
    key = &min->data;
  } else {
    return false;
  }

dengyihao's avatar
dengyihao 已提交
1232
  FstNode* node = fstGetRoot(sws->fst);
1233 1234
  Output   out = 0;
  // void*   autState = sws->aut->start();
dengyihao's avatar
dengyihao 已提交
1235
  void* autState = automFuncs[aut->type].start(aut);
dengyihao's avatar
dengyihao 已提交
1236

1237
  int32_t  len;
dengyihao's avatar
dengyihao 已提交
1238
  uint8_t* data = fstSliceData(key, &len);
dengyihao's avatar
dengyihao 已提交
1239
  for (uint32_t i = 0; i < len; i++) {
1240
    uint8_t  b = data[i];
dengyihao's avatar
dengyihao 已提交
1241
    uint64_t res = 0;
dengyihao's avatar
dengyihao 已提交
1242 1243
    bool     find = fstNodeFindInput(node, b, &res);
    if (find == true) {
dengyihao's avatar
dengyihao 已提交
1244
      FstTransition trn;
1245
      fstNodeGetTransitionAt(node, res, &trn);
dengyihao's avatar
dengyihao 已提交
1246
      void* preState = autState;
dengyihao's avatar
dengyihao 已提交
1247 1248
      // autState = sws->aut->accept(preState, b);
      autState = automFuncs[aut->type].accept(aut, preState, b);
dengyihao's avatar
dengyihao 已提交
1249
      taosArrayPush(sws->inp, &b);
1250
      StreamState s = {.node = node, .trans = res + 1, .out = {.null = false, .out = out}, .autState = preState};
dengyihao's avatar
dengyihao 已提交
1251 1252
      taosArrayPush(sws->stack, &s);
      out += trn.out;
1253
      node = fstGetNode(sws->fst, trn.addr);
dengyihao's avatar
dengyihao 已提交
1254 1255 1256 1257 1258
    } else {
      // This is a little tricky. We're in this case if the
      // given bound is not a prefix of any key in the FST.
      // Since this is a minimum bound, we need to find the
      // first transition in this node that proceeds the current
1259
      // input byte.
dengyihao's avatar
dengyihao 已提交
1260
      FstTransitions* trans = fstNodeTransitions(node);
1261
      uint64_t        i = 0;
dengyihao's avatar
dengyihao 已提交
1262 1263
      for (i = trans->range.start; i < trans->range.end; i++) {
        FstTransition trn;
dengyihao's avatar
dengyihao 已提交
1264 1265 1266
        if (fstNodeGetTransitionAt(node, i, &trn) && trn.inp > b) {
          break;
        }
dengyihao's avatar
dengyihao 已提交
1267
      }
1268 1269 1270 1271

      StreamState s = {.node = node, .trans = i, .out = {.null = false, .out = out}, .autState = autState};
      taosArrayPush(sws->stack, &s);
      return true;
dengyihao's avatar
dengyihao 已提交
1272 1273
    }
  }
1274
  uint32_t sz = taosArrayGetSize(sws->stack);
dengyihao's avatar
dengyihao 已提交
1275
  if (sz != 0) {
dengyihao's avatar
dengyihao 已提交
1276
    StreamState* s = taosArrayGet(sws->stack, sz - 1);
dengyihao's avatar
dengyihao 已提交
1277 1278 1279 1280
    if (inclusize) {
      s->trans -= 1;
      taosArrayPop(sws->inp);
    } else {
dengyihao's avatar
dengyihao 已提交
1281
      FstNode*      n = s->node;
1282 1283
      uint64_t      trans = s->trans;
      FstTransition trn;
dengyihao's avatar
dengyihao 已提交
1284
      fstNodeGetTransitionAt(n, trans - 1, &trn);
dengyihao's avatar
dengyihao 已提交
1285 1286
      StreamState s = {
          .node = fstGetNode(sws->fst, trn.addr), .trans = 0, .out = {.null = false, .out = out}, .autState = autState};
dengyihao's avatar
dengyihao 已提交
1287
      taosArrayPush(sws->stack, &s);
1288 1289 1290 1291
      return true;
    }
    return false;
  }
1292 1293

  return false;
1294
}
dengyihao's avatar
dengyihao 已提交
1295 1296
StreamWithStateResult* streamWithStateNextWith(StreamWithState* sws, StreamCallback callback) {
  AutomationCtx* aut = sws->aut;
1297
  FstOutput      output = sws->emptyOutput;
dengyihao's avatar
dengyihao 已提交
1298
  if (output.null == false) {
1299
    FstSlice emptySlice = fstSliceCreate(NULL, 0);
dengyihao's avatar
dengyihao 已提交
1300 1301
    if (fstBoundWithDataExceededBy(sws->endAt, &emptySlice)) {
      taosArrayDestroyEx(sws->stack, streamStateDestroy);
dengyihao's avatar
dengyihao 已提交
1302
      sws->stack = (SArray*)taosArrayInit(256, sizeof(StreamState));
dengyihao's avatar
dengyihao 已提交
1303 1304
      return NULL;
    }
dengyihao's avatar
dengyihao 已提交
1305
    void* start = automFuncs[aut->type].start(aut);
dengyihao's avatar
dengyihao 已提交
1306
    if (automFuncs[aut->type].isMatch(aut, start)) {
dengyihao's avatar
dengyihao 已提交
1307
      FstSlice s = fstSliceCreate(NULL, 0);
dengyihao's avatar
dengyihao 已提交
1308
      return swsResultCreate(&s, output, callback == NULL ? NULL : callback(start));
dengyihao's avatar
dengyihao 已提交
1309 1310
    }
  }
dengyihao's avatar
dengyihao 已提交
1311
  SArray* nodes = taosArrayInit(8, sizeof(FstNode*));
dengyihao's avatar
dengyihao 已提交
1312
  while (taosArrayGetSize(sws->stack) > 0) {
dengyihao's avatar
dengyihao 已提交
1313
    StreamState* p = (StreamState*)taosArrayPop(sws->stack);
dengyihao's avatar
dengyihao 已提交
1314
    if (p->trans >= FST_NODE_LEN(p->node) || !automFuncs[aut->type].canMatch(aut, p->autState)) {
dengyihao's avatar
dengyihao 已提交
1315 1316 1317
      if (FST_NODE_ADDR(p->node) != fstGetRootAddr(sws->fst)) {
        taosArrayPop(sws->inp);
      }
dengyihao's avatar
dengyihao 已提交
1318
      streamStateDestroy(p);
dengyihao's avatar
dengyihao 已提交
1319 1320
      continue;
    }
1321
    FstTransition trn;
dengyihao's avatar
dengyihao 已提交
1322
    fstNodeGetTransitionAt(p->node, p->trans, &trn);
dengyihao's avatar
dengyihao 已提交
1323 1324 1325 1326 1327 1328

    Output out = p->out.out + trn.out;
    void*  nextState = automFuncs[aut->type].accept(aut, p->autState, trn.inp);
    void*  tState = (callback == NULL) ? NULL : callback(nextState);
    bool   isMatch = automFuncs[aut->type].isMatch(aut, nextState);

dengyihao's avatar
dengyihao 已提交
1329
    FstNode* nextNode = fstGetNode(sws->fst, trn.addr);
1330 1331
    taosArrayPush(nodes, &nextNode);
    taosArrayPush(sws->inp, &(trn.inp));
dengyihao's avatar
dengyihao 已提交
1332 1333

    if (FST_NODE_IS_FINAL(nextNode)) {
1334
      // void *eofState = sws->aut->acceptEof(nextState);
dengyihao's avatar
dengyihao 已提交
1335
      void* eofState = automFuncs[aut->type].acceptEof(aut, nextState);
dengyihao's avatar
dengyihao 已提交
1336 1337 1338
      if (eofState != NULL) {
        isMatch = automFuncs[aut->type].isMatch(aut, eofState);
      }
1339 1340
    }
    StreamState s1 = {.node = p->node, .trans = p->trans + 1, .out = p->out, .autState = p->autState};
dengyihao's avatar
dengyihao 已提交
1341 1342 1343 1344
    taosArrayPush(sws->stack, &s1);

    StreamState s2 = {.node = nextNode, .trans = 0, .out = {.null = false, .out = out}, .autState = nextState};
    taosArrayPush(sws->stack, &s2);
dengyihao's avatar
dengyihao 已提交
1345

1346
    size_t   isz = taosArrayGetSize(sws->inp);
wafwerar's avatar
wafwerar 已提交
1347
    uint8_t* buf = (uint8_t*)taosMemoryMalloc(isz * sizeof(uint8_t));
dengyihao's avatar
dengyihao 已提交
1348 1349 1350
    for (uint32_t i = 0; i < isz; i++) {
      buf[i] = *(uint8_t*)taosArrayGet(sws->inp, i);
    }
dengyihao's avatar
dengyihao 已提交
1351
    FstSlice slice = fstSliceCreate(buf, isz);
dengyihao's avatar
dengyihao 已提交
1352 1353
    if (fstBoundWithDataExceededBy(sws->endAt, &slice)) {
      taosArrayDestroyEx(sws->stack, streamStateDestroy);
dengyihao's avatar
dengyihao 已提交
1354
      sws->stack = (SArray*)taosArrayInit(256, sizeof(StreamState));
wafwerar's avatar
wafwerar 已提交
1355
      taosMemoryFreeClear(buf);
dengyihao's avatar
dengyihao 已提交
1356
      fstSliceDestroy(&slice);
dengyihao's avatar
dengyihao 已提交
1357
      taosArrayDestroy(nodes);
dengyihao's avatar
dengyihao 已提交
1358 1359 1360
      return NULL;
    }
    if (FST_NODE_IS_FINAL(nextNode) && isMatch) {
1361
      FstOutput              fOutput = {.null = false, .out = out + FST_NODE_FINAL_OUTPUT(nextNode)};
dengyihao's avatar
dengyihao 已提交
1362
      StreamWithStateResult* result = swsResultCreate(&slice, fOutput, tState);
wafwerar's avatar
wafwerar 已提交
1363
      taosMemoryFreeClear(buf);
dengyihao's avatar
dengyihao 已提交
1364
      fstSliceDestroy(&slice);
dengyihao's avatar
dengyihao 已提交
1365
      taosArrayDestroy(nodes);
dengyihao's avatar
dengyihao 已提交
1366
      nodes = NULL;
1367
      return result;
dengyihao's avatar
dengyihao 已提交
1368
    }
wafwerar's avatar
wafwerar 已提交
1369
    taosMemoryFreeClear(buf);
dengyihao's avatar
dengyihao 已提交
1370
    fstSliceDestroy(&slice);
dengyihao's avatar
dengyihao 已提交
1371
  };
dengyihao's avatar
dengyihao 已提交
1372
  taosArrayDestroy(nodes);
1373
  return NULL;
dengyihao's avatar
dengyihao 已提交
1374 1375
}

dengyihao's avatar
dengyihao 已提交
1376
StreamWithStateResult* swsResultCreate(FstSlice* data, FstOutput fOut, void* state) {
wafwerar's avatar
wafwerar 已提交
1377
  StreamWithStateResult* result = taosMemoryCalloc(1, sizeof(StreamWithStateResult));
dengyihao's avatar
dengyihao 已提交
1378 1379 1380
  if (result == NULL) {
    return NULL;
  }
1381 1382 1383 1384

  result->data = fstSliceCopy(data, 0, FST_SLICE_LEN(data) - 1);
  result->out = fOut;
  result->state = state;
dengyihao's avatar
dengyihao 已提交
1385 1386
  return result;
}
dengyihao's avatar
dengyihao 已提交
1387
void swsResultDestroy(StreamWithStateResult* result) {
dengyihao's avatar
dengyihao 已提交
1388 1389 1390
  if (NULL == result) {
    return;
  }
1391

dengyihao's avatar
dengyihao 已提交
1392
  fstSliceDestroy(&result->data);
1393
  startWithStateValueDestroy(result->state);
wafwerar's avatar
wafwerar 已提交
1394
  taosMemoryFree(result);
dengyihao's avatar
dengyihao 已提交
1395 1396
}

dengyihao's avatar
dengyihao 已提交
1397
void streamStateDestroy(void* s) {
dengyihao's avatar
dengyihao 已提交
1398 1399 1400
  if (NULL == s) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
1401
  StreamState* ss = (StreamState*)s;
dengyihao's avatar
dengyihao 已提交
1402 1403 1404
  fstNodeDestroy(ss->node);
}

dengyihao's avatar
dengyihao 已提交
1405
FstStreamBuilder* fstStreamBuilderCreate(Fst* fst, AutomationCtx* aut) {
wafwerar's avatar
wafwerar 已提交
1406
  FstStreamBuilder* b = taosMemoryCalloc(1, sizeof(FstStreamBuilder));
dengyihao's avatar
dengyihao 已提交
1407 1408 1409
  if (NULL == b) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
1410 1411 1412 1413

  b->fst = fst;
  b->aut = aut;
  b->min = fstBoundStateCreate(Unbounded, NULL);
1414
  b->max = fstBoundStateCreate(Unbounded, NULL);
dengyihao's avatar
dengyihao 已提交
1415 1416
  return b;
}
dengyihao's avatar
dengyihao 已提交
1417
void fstStreamBuilderDestroy(FstStreamBuilder* b) {
dengyihao's avatar
dengyihao 已提交
1418 1419
  fstSliceDestroy(&b->min->data);
  fstSliceDestroy(&b->max->data);
wafwerar's avatar
wafwerar 已提交
1420 1421 1422
  taosMemoryFreeClear(b->min);
  taosMemoryFreeClear(b->max);
  taosMemoryFree(b);
dengyihao's avatar
dengyihao 已提交
1423
}
dengyihao's avatar
dengyihao 已提交
1424
void fstStreamBuilderSetRange(FstStreamBuilder* b, FstSlice* val, RangeType type) {
dengyihao's avatar
dengyihao 已提交
1425
  if (b == NULL) {
dengyihao's avatar
dengyihao 已提交
1426
    return;
dengyihao's avatar
dengyihao 已提交
1427
  }
dengyihao's avatar
dengyihao 已提交
1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
  if (type == GE) {
    b->min->type = Included;
    fstSliceDestroy(&(b->min->data));
    b->min->data = fstSliceDeepCopy(val, 0, FST_SLICE_LEN(val) - 1);
  } else if (type == GT) {
    b->min->type = Excluded;
    fstSliceDestroy(&(b->min->data));
    b->min->data = fstSliceDeepCopy(val, 0, FST_SLICE_LEN(val) - 1);
  } else if (type == LE) {
    b->max->type = Included;
    fstSliceDestroy(&(b->max->data));
    b->max->data = fstSliceDeepCopy(val, 0, FST_SLICE_LEN(val) - 1);
  } else if (type == LT) {
    b->max->type = Excluded;
    fstSliceDestroy(&(b->max->data));
    b->max->data = fstSliceDeepCopy(val, 0, FST_SLICE_LEN(val) - 1);
  }
}