indexFst.c 44.1 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;
  }
dengyihao's avatar
dengyihao 已提交
102
  int32_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

dengyihao's avatar
dengyihao 已提交
133
  int32_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 (int32_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

dengyihao's avatar
dengyihao 已提交
150 151
  int32_t lsz = (size_t)(s->end - s->start + 1);  // data len
  int32_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) {
dengyihao's avatar
dengyihao 已提交
248
  int32_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 (int32_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 (int32_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) {
dengyihao's avatar
dengyihao 已提交
645 646 647
  if (node == NULL) {
    return;
  }
648
  fstSliceDestroy(&node->data);
wafwerar's avatar
wafwerar 已提交
649
  taosMemoryFree(node);
dengyihao's avatar
dengyihao 已提交
650
}
dengyihao's avatar
dengyihao 已提交
651
FstTransitions* fstNodeTransitions(FstNode* node) {
wafwerar's avatar
wafwerar 已提交
652
  FstTransitions* t = taosMemoryMalloc(sizeof(FstTransitions));
dengyihao's avatar
dengyihao 已提交
653 654 655
  if (NULL == t) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
656 657
  FstRange range = {.start = 0, .end = FST_NODE_LEN(node)};
  t->range = range;
658 659 660
  t->node = node;
  return t;
}
dengyihao's avatar
dengyihao 已提交
661

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

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

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

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

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

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

766 767 768 769 770 771
  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 已提交
772

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

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

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

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

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

dengyihao's avatar
dengyihao 已提交
808 809
void fstBuilderInsertOutput(FstBuilder* b, FstSlice bs, Output in) {
  FstSlice* s = &bs;
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
  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 已提交
837

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

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

dengyihao's avatar
dengyihao 已提交
876
CompiledAddr fstBuilderCompile(FstBuilder* b, FstBuilderNode* bn) {
877 878
  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 已提交
879
  }
dengyihao's avatar
dengyihao 已提交
880
  FstRegistryEntry* entry = fstRegistryGetEntry(b->registry, bn);
881
  if (entry->state == FOUND) {
dengyihao's avatar
dengyihao 已提交
882
    CompiledAddr ret = entry->addr;
dengyihao's avatar
dengyihao 已提交
883
    fstRegistryEntryDestroy(entry);
dengyihao's avatar
dengyihao 已提交
884
    return ret;
885
  }
dengyihao's avatar
dengyihao 已提交
886 887
  CompiledAddr startAddr = (CompiledAddr)(FST_WRITER_COUNT(b->wrt));

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

  return b->lastAddr;
dengyihao's avatar
dengyihao 已提交
896 897
}

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

904 905
  char buf64[8] = {0};

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

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

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

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

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

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

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

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

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

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

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

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

  uint64_t type;
  taosDecodeFixedU64(buf + skip, &type);
991
  skip += sizeof(type);
dengyihao's avatar
dengyihao 已提交
992 993 994

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

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

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

1019 1020 1021 1022
  fst->meta->version = version;
  fst->meta->rootAddr = rootAddr;
  fst->meta->ty = type;
  fst->meta->len = fstLen;
dengyihao's avatar
dengyihao 已提交
1023
  fst->meta->checkSum = checkSum;
dengyihao's avatar
dengyihao 已提交
1024

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

wafwerar's avatar
wafwerar 已提交
1029
  taosThreadMutexInit(&fst->mtx, NULL);
dengyihao's avatar
dengyihao 已提交
1030 1031
  return fst;

1032
FST_CREAT_FAILED:
wafwerar's avatar
wafwerar 已提交
1033 1034
  taosMemoryFree(fst->meta);
  taosMemoryFree(fst);
1035 1036

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

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

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

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

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

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

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

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

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

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

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

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

1154
  return b;
dengyihao's avatar
dengyihao 已提交
1155 1156
}

dengyihao's avatar
dengyihao 已提交
1157
bool fstBoundWithDataExceededBy(FstBoundWithData* bound, FstSlice* slice) {
dengyihao's avatar
dengyihao 已提交
1158 1159 1160 1161 1162 1163
  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 已提交
1164
    return false;
dengyihao's avatar
dengyihao 已提交
1165 1166
  }
}
dengyihao's avatar
dengyihao 已提交
1167
bool fstBoundWithDataIsEmpty(FstBoundWithData* bound) {
dengyihao's avatar
dengyihao 已提交
1168 1169
  if (bound->type == Unbounded) {
    return true;
1170 1171 1172
  } else {
    return fstSliceIsEmpty(&bound->data);
  }
dengyihao's avatar
dengyihao 已提交
1173 1174
}

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

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

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

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

dengyihao's avatar
dengyihao 已提交
1190
  sws->emptyOutput.null = true;
1191
  sws->emptyOutput.out = 0;
dengyihao's avatar
dengyihao 已提交
1192

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

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

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

wafwerar's avatar
wafwerar 已提交
1207
  taosMemoryFree(sws);
dengyihao's avatar
dengyihao 已提交
1208 1209
}

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

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

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

1240
  int32_t  len;
dengyihao's avatar
dengyihao 已提交
1241
  uint8_t* data = fstSliceData(key, &len);
dengyihao's avatar
dengyihao 已提交
1242
  for (uint32_t i = 0; i < len; i++) {
1243
    uint8_t  b = data[i];
dengyihao's avatar
dengyihao 已提交
1244
    uint64_t res = 0;
dengyihao's avatar
dengyihao 已提交
1245 1246
    bool     find = fstNodeFindInput(node, b, &res);
    if (find == true) {
dengyihao's avatar
dengyihao 已提交
1247
      FstTransition trn;
1248
      fstNodeGetTransitionAt(node, res, &trn);
dengyihao's avatar
dengyihao 已提交
1249
      void* preState = autState;
dengyihao's avatar
dengyihao 已提交
1250 1251
      // autState = sws->aut->accept(preState, b);
      autState = automFuncs[aut->type].accept(aut, preState, b);
dengyihao's avatar
dengyihao 已提交
1252
      taosArrayPush(sws->inp, &b);
dengyihao's avatar
dengyihao 已提交
1253

1254
      StreamState s = {.node = node, .trans = res + 1, .out = {.null = false, .out = out}, .autState = preState};
dengyihao's avatar
dengyihao 已提交
1255 1256
      node = NULL;

dengyihao's avatar
dengyihao 已提交
1257 1258
      taosArrayPush(sws->stack, &s);
      out += trn.out;
1259
      node = fstGetNode(sws->fst, trn.addr);
dengyihao's avatar
dengyihao 已提交
1260 1261 1262 1263 1264
    } 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
1265
      // input byte.
dengyihao's avatar
dengyihao 已提交
1266
      FstTransitions* trans = fstNodeTransitions(node);
1267
      uint64_t        i = 0;
dengyihao's avatar
dengyihao 已提交
1268 1269
      for (i = trans->range.start; i < trans->range.end; i++) {
        FstTransition trn;
dengyihao's avatar
dengyihao 已提交
1270 1271 1272
        if (fstNodeGetTransitionAt(node, i, &trn) && trn.inp > b) {
          break;
        }
dengyihao's avatar
dengyihao 已提交
1273
      }
1274 1275 1276 1277

      StreamState s = {.node = node, .trans = i, .out = {.null = false, .out = out}, .autState = autState};
      taosArrayPush(sws->stack, &s);
      return true;
dengyihao's avatar
dengyihao 已提交
1278 1279
    }
  }
dengyihao's avatar
dengyihao 已提交
1280 1281 1282

  fstNodeDestroy(node);

1283
  uint32_t sz = taosArrayGetSize(sws->stack);
dengyihao's avatar
dengyihao 已提交
1284
  if (sz != 0) {
dengyihao's avatar
dengyihao 已提交
1285
    StreamState* s = taosArrayGet(sws->stack, sz - 1);
dengyihao's avatar
dengyihao 已提交
1286 1287 1288 1289
    if (inclusize) {
      s->trans -= 1;
      taosArrayPop(sws->inp);
    } else {
dengyihao's avatar
dengyihao 已提交
1290
      FstNode*      n = s->node;
1291 1292
      uint64_t      trans = s->trans;
      FstTransition trn;
dengyihao's avatar
dengyihao 已提交
1293
      fstNodeGetTransitionAt(n, trans - 1, &trn);
dengyihao's avatar
dengyihao 已提交
1294 1295
      StreamState s = {
          .node = fstGetNode(sws->fst, trn.addr), .trans = 0, .out = {.null = false, .out = out}, .autState = autState};
dengyihao's avatar
dengyihao 已提交
1296
      taosArrayPush(sws->stack, &s);
1297 1298 1299 1300
      return true;
    }
    return false;
  }
1301 1302

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

    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 已提交
1338
    FstNode* nextNode = fstGetNode(sws->fst, trn.addr);
1339 1340
    taosArrayPush(nodes, &nextNode);
    taosArrayPush(sws->inp, &(trn.inp));
dengyihao's avatar
dengyihao 已提交
1341 1342

    if (FST_NODE_IS_FINAL(nextNode)) {
1343
      // void *eofState = sws->aut->acceptEof(nextState);
dengyihao's avatar
dengyihao 已提交
1344
      void* eofState = automFuncs[aut->type].acceptEof(aut, nextState);
dengyihao's avatar
dengyihao 已提交
1345 1346 1347
      if (eofState != NULL) {
        isMatch = automFuncs[aut->type].isMatch(aut, eofState);
      }
1348 1349
    }
    StreamState s1 = {.node = p->node, .trans = p->trans + 1, .out = p->out, .autState = p->autState};
dengyihao's avatar
dengyihao 已提交
1350 1351 1352 1353
    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 已提交
1354

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

dengyihao's avatar
dengyihao 已提交
1385
StreamWithStateResult* swsResultCreate(FstSlice* data, FstOutput fOut, void* state) {
wafwerar's avatar
wafwerar 已提交
1386
  StreamWithStateResult* result = taosMemoryCalloc(1, sizeof(StreamWithStateResult));
dengyihao's avatar
dengyihao 已提交
1387 1388 1389
  if (result == NULL) {
    return NULL;
  }
1390 1391 1392 1393

  result->data = fstSliceCopy(data, 0, FST_SLICE_LEN(data) - 1);
  result->out = fOut;
  result->state = state;
dengyihao's avatar
dengyihao 已提交
1394 1395
  return result;
}
dengyihao's avatar
dengyihao 已提交
1396
void swsResultDestroy(StreamWithStateResult* result) {
dengyihao's avatar
dengyihao 已提交
1397 1398 1399
  if (NULL == result) {
    return;
  }
1400

dengyihao's avatar
dengyihao 已提交
1401
  fstSliceDestroy(&result->data);
1402
  startWithStateValueDestroy(result->state);
wafwerar's avatar
wafwerar 已提交
1403
  taosMemoryFree(result);
dengyihao's avatar
dengyihao 已提交
1404 1405
}

dengyihao's avatar
dengyihao 已提交
1406
void streamStateDestroy(void* s) {
dengyihao's avatar
dengyihao 已提交
1407 1408 1409
  if (NULL == s) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
1410
  StreamState* ss = (StreamState*)s;
dengyihao's avatar
dengyihao 已提交
1411 1412 1413
  fstNodeDestroy(ss->node);
}

dengyihao's avatar
dengyihao 已提交
1414
FstStreamBuilder* fstStreamBuilderCreate(Fst* fst, AutomationCtx* aut) {
wafwerar's avatar
wafwerar 已提交
1415
  FstStreamBuilder* b = taosMemoryCalloc(1, sizeof(FstStreamBuilder));
dengyihao's avatar
dengyihao 已提交
1416 1417 1418
  if (NULL == b) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
1419 1420 1421 1422

  b->fst = fst;
  b->aut = aut;
  b->min = fstBoundStateCreate(Unbounded, NULL);
1423
  b->max = fstBoundStateCreate(Unbounded, NULL);
dengyihao's avatar
dengyihao 已提交
1424 1425
  return b;
}
dengyihao's avatar
dengyihao 已提交
1426
void fstStreamBuilderDestroy(FstStreamBuilder* b) {
dengyihao's avatar
dengyihao 已提交
1427 1428
  fstSliceDestroy(&b->min->data);
  fstSliceDestroy(&b->max->data);
wafwerar's avatar
wafwerar 已提交
1429 1430 1431
  taosMemoryFreeClear(b->min);
  taosMemoryFreeClear(b->max);
  taosMemoryFree(b);
dengyihao's avatar
dengyihao 已提交
1432
}
dengyihao's avatar
dengyihao 已提交
1433
void fstStreamBuilderSetRange(FstStreamBuilder* b, FstSlice* val, RangeType type) {
dengyihao's avatar
dengyihao 已提交
1434
  if (b == NULL) {
dengyihao's avatar
dengyihao 已提交
1435
    return;
dengyihao's avatar
dengyihao 已提交
1436
  }
dengyihao's avatar
dengyihao 已提交
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
  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);
  }
}