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

#include "index_fst.h"
17
#include "indexInt.h"
dengyihao's avatar
dengyihao 已提交
18
#include "index_fst_automation.h"
19 20
#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 33
FstUnFinishedNodes* fstUnFinishedNodesCreate() {
  FstUnFinishedNodes* nodes = malloc(sizeof(FstUnFinishedNodes));
dengyihao's avatar
dengyihao 已提交
34
  if (nodes == NULL) { return NULL; }
dengyihao's avatar
dengyihao 已提交
35

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

49
  taosArrayDestroyEx(nodes->stack, unFinishedNodeDestroyElem);
dengyihao's avatar
dengyihao 已提交
50 51 52
  free(nodes);
}

dengyihao's avatar
dengyihao 已提交
53 54
void fstUnFinishedNodesPushEmpty(FstUnFinishedNodes* nodes, bool isFinal) {
  FstBuilderNode* node = malloc(sizeof(FstBuilderNode));
55
  node->isFinal = isFinal;
dengyihao's avatar
dengyihao 已提交
56
  node->finalOutput = 0;
57
  node->trans = taosArrayInit(16, sizeof(FstTransition));
dengyihao's avatar
dengyihao 已提交
58

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

dengyihao's avatar
dengyihao 已提交
65
  FstBuilderNodeUnfinished* un = taosArrayPop(nodes->stack);
66 67
  assert(un->last == NULL);
  return un->node;
dengyihao's avatar
dengyihao 已提交
68 69
}

dengyihao's avatar
dengyihao 已提交
70 71
FstBuilderNode* fstUnFinishedNodesPopFreeze(FstUnFinishedNodes* nodes, CompiledAddr addr) {
  FstBuilderNodeUnfinished* un = taosArrayPop(nodes->stack);
dengyihao's avatar
dengyihao 已提交
72
  fstBuilderNodeUnfinishedLastCompiled(un, addr);
73 74 75
  // free(un->last); // TODO add func FstLastTransitionFree()
  // un->last = NULL;
  return un->node;
dengyihao's avatar
dengyihao 已提交
76 77
}

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

100 101 102 103
  // FstLastTransition *trn = malloc(sizeof(FstLastTransition));
  // trn->inp = s->data[s->start];
  // trn->out = out;
  int32_t  len = 0;
dengyihao's avatar
dengyihao 已提交
104
  uint8_t* data = fstSliceData(s, &len);
105
  un->last = fstLastTransitionCreate(data[0], out);
dengyihao's avatar
dengyihao 已提交
106

dengyihao's avatar
dengyihao 已提交
107
  for (uint64_t i = 1; i < len; i++) {
dengyihao's avatar
dengyihao 已提交
108
    FstBuilderNode* n = malloc(sizeof(FstBuilderNode));
109
    n->isFinal = false;
dengyihao's avatar
dengyihao 已提交
110
    n->finalOutput = 0;
111 112 113 114 115
    n->trans = taosArrayInit(16, sizeof(FstTransition));

    // FstLastTransition *trn = malloc(sizeof(FstLastTransition));
    // trn->inp = s->data[i];
    // trn->out = out;
dengyihao's avatar
dengyihao 已提交
116
    FstLastTransition* trn = fstLastTransitionCreate(data[i], 0);
dengyihao's avatar
dengyihao 已提交
117

118 119
    FstBuilderNodeUnfinished un = {.node = n, .last = trn};
    taosArrayPush(nodes->stack, &un);
dengyihao's avatar
dengyihao 已提交
120
  }
121
  fstUnFinishedNodesPushEmpty(nodes, true);
dengyihao's avatar
dengyihao 已提交
122 123
}

dengyihao's avatar
dengyihao 已提交
124 125
uint64_t fstUnFinishedNodesFindCommPrefix(FstUnFinishedNodes* node, FstSlice bs) {
  FstSlice* s = &bs;
dengyihao's avatar
dengyihao 已提交
126

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

144 145
  size_t lsz = (size_t)(s->end - s->start + 1);  // data len
  size_t ssz = taosArrayGetSize(node->stack);    // stack size
dengyihao's avatar
dengyihao 已提交
146
  *out = in;
dengyihao's avatar
dengyihao 已提交
147 148
  uint64_t i = 0;
  for (i = 0; i < lsz && i < ssz; i++) {
dengyihao's avatar
dengyihao 已提交
149
    FstBuilderNodeUnfinished* un = taosArrayGet(node->stack, i);
dengyihao's avatar
dengyihao 已提交
150

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

dengyihao's avatar
dengyihao 已提交
173
FstState fstStateCreateFrom(FstSlice* slice, CompiledAddr addr) {
dengyihao's avatar
dengyihao 已提交
174
  FstState fs = {.state = EmptyFinal, .val = 0};
dengyihao's avatar
dengyihao 已提交
175
  if (addr == EMPTY_ADDRESS) { return fs; }
176

dengyihao's avatar
dengyihao 已提交
177
  uint8_t* data = fstSliceData(slice, NULL);
178 179
  uint8_t  v = data[addr];
  uint8_t  t = (v & 0b11000000) >> 6;
dengyihao's avatar
dengyihao 已提交
180 181 182
  if (t == 0b11) {
    fs.state = OneTransNext;
  } else if (t == 0b10) {
183
    fs.state = OneTrans;
dengyihao's avatar
dengyihao 已提交
184
  } else {
185
    fs.state = AnyTrans;
dengyihao's avatar
dengyihao 已提交
186
  }
dengyihao's avatar
dengyihao 已提交
187
  fs.val = v;
dengyihao's avatar
dengyihao 已提交
188 189
  return fs;
}
dengyihao's avatar
dengyihao 已提交
190

dengyihao's avatar
dengyihao 已提交
191 192 193 194
static FstState fstStateDict[] = {{.state = OneTransNext, .val = 0b11000000},
                                  {.state = OneTrans, .val = 0b10000000},
                                  {.state = AnyTrans, .val = 0b00000000},
                                  {.state = EmptyFinal, .val = 0b00000000}};
195
// debug
dengyihao's avatar
dengyihao 已提交
196
static const char* fstStateStr[] = {"ONE_TRANS_NEXT", "ONE_TRANS", "ANY_TRANS", "EMPTY_FINAL"};
dengyihao's avatar
dengyihao 已提交
197

198
FstState fstStateCreate(State state) {
dengyihao's avatar
dengyihao 已提交
199
  uint8_t idx = (uint8_t)state;
dengyihao's avatar
dengyihao 已提交
200
  return fstStateDict[idx];
dengyihao's avatar
dengyihao 已提交
201
}
202
// compile
dengyihao's avatar
dengyihao 已提交
203
void fstStateCompileForOneTransNext(FstCountingWriter* w, CompiledAddr addr, uint8_t inp) {
204
  FstState s = fstStateCreate(OneTransNext);
dengyihao's avatar
dengyihao 已提交
205 206
  fstStateSetCommInput(&s, inp);

207
  bool    null = false;
dengyihao's avatar
dengyihao 已提交
208 209 210
  uint8_t v = fstStateCommInput(&s, &null);
  if (null) {
    // w->write_all(&[inp])
dengyihao's avatar
dengyihao 已提交
211
    fstCountingWriterWrite(w, &inp, 1);
212
  }
dengyihao's avatar
dengyihao 已提交
213
  fstCountingWriterWrite(w, &(s.val), 1);
dengyihao's avatar
dengyihao 已提交
214
  // w->write_all(&[s.val])
dengyihao's avatar
dengyihao 已提交
215
  return;
dengyihao's avatar
dengyihao 已提交
216
}
dengyihao's avatar
dengyihao 已提交
217
void fstStateCompileForOneTrans(FstCountingWriter* w, CompiledAddr addr, FstTransition* trn) {
218 219 220
  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 已提交
221 222 223 224
  PackSizes packSizes = 0;

  FST_SET_OUTPUT_PACK_SIZE(packSizes, outPackSize);
  FST_SET_TRANSITION_PACK_SIZE(packSizes, transPackSize);
dengyihao's avatar
dengyihao 已提交
225
  fstCountingWriterWrite(w, (char*)&packSizes, sizeof(packSizes));
226 227

  FstState st = fstStateCreate(OneTrans);
dengyihao's avatar
dengyihao 已提交
228 229

  fstStateSetCommInput(&st, trn->inp);
230 231
  bool    null = false;
  uint8_t inp = fstStateCommInput(&st, &null);
dengyihao's avatar
dengyihao 已提交
232 233
  if (null == true) { fstCountingWriterWrite(w, (char*)&trn->inp, sizeof(trn->inp)); }
  fstCountingWriterWrite(w, (char*)(&(st.val)), sizeof(st.val));
234
  return;
dengyihao's avatar
dengyihao 已提交
235
}
dengyihao's avatar
dengyihao 已提交
236
void fstStateCompileForAnyTrans(FstCountingWriter* w, CompiledAddr addr, FstBuilderNode* node) {
237
  size_t sz = taosArrayGetSize(node->trans);
dengyihao's avatar
dengyihao 已提交
238 239 240
  assert(sz <= 256);

  uint8_t tSize = 0;
241 242
  uint8_t oSize = packSize(node->finalOutput);

dengyihao's avatar
dengyihao 已提交
243
  // finalOutput.is_zero()
244
  bool anyOuts = (node->finalOutput != 0);
dengyihao's avatar
dengyihao 已提交
245
  for (size_t i = 0; i < sz; i++) {
dengyihao's avatar
dengyihao 已提交
246
    FstTransition* t = taosArrayGet(node->trans, i);
247
    tSize = MAX(tSize, packDeltaSize(addr, t->addr));
dengyihao's avatar
dengyihao 已提交
248
    oSize = MAX(oSize, packSize(t->out));
249
    anyOuts = anyOuts || (t->out != 0);
dengyihao's avatar
dengyihao 已提交
250 251
  }

252 253 254 255 256 257
  PackSizes packSizes = 0;
  if (anyOuts) {
    FST_SET_OUTPUT_PACK_SIZE(packSizes, oSize);
  } else {
    FST_SET_OUTPUT_PACK_SIZE(packSizes, 0);
  }
dengyihao's avatar
dengyihao 已提交
258 259

  FST_SET_TRANSITION_PACK_SIZE(packSizes, tSize);
260

dengyihao's avatar
dengyihao 已提交
261
  FstState st = fstStateCreate(AnyTrans);
262
  fstStateSetFinalState(&st, node->isFinal);
dengyihao's avatar
dengyihao 已提交
263
  fstStateSetStateNtrans(&st, (uint8_t)sz);
264

dengyihao's avatar
dengyihao 已提交
265
  if (anyOuts) {
dengyihao's avatar
dengyihao 已提交
266
    if (FST_BUILDER_NODE_IS_FINAL(node)) { fstCountingWriterPackUintIn(w, node->finalOutput, oSize); }
dengyihao's avatar
dengyihao 已提交
267
    for (int32_t i = sz - 1; i >= 0; i--) {
dengyihao's avatar
dengyihao 已提交
268
      FstTransition* t = taosArrayGet(node->trans, i);
dengyihao's avatar
dengyihao 已提交
269 270
      fstCountingWriterPackUintIn(w, t->out, oSize);
    }
271
  }
dengyihao's avatar
dengyihao 已提交
272
  for (int32_t i = sz - 1; i >= 0; i--) {
dengyihao's avatar
dengyihao 已提交
273
    FstTransition* t = taosArrayGet(node->trans, i);
274
    fstPackDeltaIn(w, addr, t->addr, tSize);
dengyihao's avatar
dengyihao 已提交
275
  }
dengyihao's avatar
dengyihao 已提交
276
  for (int32_t i = sz - 1; i >= 0; i--) {
dengyihao's avatar
dengyihao 已提交
277 278
    FstTransition* t = taosArrayGet(node->trans, i);
    fstCountingWriterWrite(w, (char*)&t->inp, 1);
279
    // fstPackDeltaIn(w, addr, t->addr, tSize);
dengyihao's avatar
dengyihao 已提交
280 281 282 283 284 285
  }
  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.
dengyihao's avatar
dengyihao 已提交
286
    uint8_t* index = (uint8_t*)malloc(sizeof(uint8_t) * 256);
dengyihao's avatar
dengyihao 已提交
287
    memset(index, 255, sizeof(uint8_t) * 256);
288
    /// for (uint8_t i = 0; i < 256; i++) {
dengyihao's avatar
dengyihao 已提交
289 290
    //  index[i] = 255;
    ///}
dengyihao's avatar
dengyihao 已提交
291
    for (size_t i = 0; i < sz; i++) {
dengyihao's avatar
dengyihao 已提交
292
      FstTransition* t = taosArrayGet(node->trans, i);
dengyihao's avatar
dengyihao 已提交
293
      index[t->inp] = i;
294
      // fstPackDeltaIn(w, addr, t->addr, tSize);
dengyihao's avatar
dengyihao 已提交
295
    }
dengyihao's avatar
dengyihao 已提交
296
    fstCountingWriterWrite(w, (char*)index, 256);
dengyihao's avatar
dengyihao 已提交
297
    free(index);
dengyihao's avatar
dengyihao 已提交
298
  }
dengyihao's avatar
dengyihao 已提交
299
  fstCountingWriterWrite(w, (char*)&packSizes, 1);
dengyihao's avatar
dengyihao 已提交
300 301 302
  bool null = false;
  fstStateStateNtrans(&st, &null);
  if (null == true) {
303 304 305
    // 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 已提交
306
    uint8_t v = 1;
307
    if (sz == 256) {
dengyihao's avatar
dengyihao 已提交
308
      fstCountingWriterWrite(w, (char*)&v, 1);
309
    } else {
dengyihao's avatar
dengyihao 已提交
310
      fstCountingWriterWrite(w, (char*)&sz, 1);
311
    }
dengyihao's avatar
dengyihao 已提交
312
  }
dengyihao's avatar
dengyihao 已提交
313
  fstCountingWriterWrite(w, (char*)(&(st.val)), 1);
dengyihao's avatar
dengyihao 已提交
314 315 316 317
  return;
}

// set_comm_input
dengyihao's avatar
dengyihao 已提交
318
void fstStateSetCommInput(FstState* s, uint8_t inp) {
dengyihao's avatar
dengyihao 已提交
319 320 321
  assert(s->state == OneTransNext || s->state == OneTrans);

  uint8_t val;
dengyihao's avatar
dengyihao 已提交
322
  COMMON_INDEX(inp, 0b111111, val);
323
  s->val = (s->val & fstStateDict[s->state].val) | val;
dengyihao's avatar
dengyihao 已提交
324 325 326
}

// comm_input
dengyihao's avatar
dengyihao 已提交
327
uint8_t fstStateCommInput(FstState* s, bool* null) {
dengyihao's avatar
dengyihao 已提交
328 329
  assert(s->state == OneTransNext || s->state == OneTrans);
  uint8_t v = s->val & 0b00111111;
330 331
  if (v == 0) {
    *null = true;
dengyihao's avatar
dengyihao 已提交
332
    return v;
333 334 335
  }
  // v = 0 indicate that common_input is None
  return v == 0 ? 0 : COMMON_INPUT(v);
dengyihao's avatar
dengyihao 已提交
336 337 338 339
}

// input_len

dengyihao's avatar
dengyihao 已提交
340
uint64_t fstStateInputLen(FstState* s) {
dengyihao's avatar
dengyihao 已提交
341
  assert(s->state == OneTransNext || s->state == OneTrans);
dengyihao's avatar
dengyihao 已提交
342
  bool null = false;
343 344 345 346 347
  fstStateCommInput(s, &null);
  return null ? 1 : 0;
}

// end_addr
dengyihao's avatar
dengyihao 已提交
348
uint64_t fstStateEndAddrForOneTransNext(FstState* s, FstSlice* data) {
dengyihao's avatar
dengyihao 已提交
349
  assert(s->state == OneTransNext);
dengyihao's avatar
dengyihao 已提交
350 351
  return FST_SLICE_LEN(data) - 1 - fstStateInputLen(s);
}
dengyihao's avatar
dengyihao 已提交
352
uint64_t fstStateEndAddrForOneTrans(FstState* s, FstSlice* data, PackSizes sizes) {
dengyihao's avatar
dengyihao 已提交
353
  assert(s->state == OneTrans);
354 355 356
  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 已提交
357 358
uint64_t fstStateEndAddrForAnyTrans(FstState* state, uint64_t version, FstSlice* date, PackSizes sizes,
                                    uint64_t nTrans) {
359 360 361 362 363 364 365
  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 已提交
366
uint8_t fstStateInput(FstState* s, FstNode* node) {
dengyihao's avatar
dengyihao 已提交
367
  assert(s->state == OneTransNext || s->state == OneTrans);
dengyihao's avatar
dengyihao 已提交
368
  FstSlice* slice = &node->data;
369 370
  bool      null = false;
  uint8_t   inp = fstStateCommInput(s, &null);
dengyihao's avatar
dengyihao 已提交
371
  uint8_t*  data = fstSliceData(slice, NULL);
dengyihao's avatar
dengyihao 已提交
372
  return null == false ? inp : data[node->start - 1];
dengyihao's avatar
dengyihao 已提交
373
}
dengyihao's avatar
dengyihao 已提交
374
uint8_t fstStateInputForAnyTrans(FstState* s, FstNode* node, uint64_t i) {
dengyihao's avatar
dengyihao 已提交
375
  assert(s->state == AnyTrans);
dengyihao's avatar
dengyihao 已提交
376
  FstSlice* slice = &node->data;
dengyihao's avatar
dengyihao 已提交
377

378 379
  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 已提交
380

dengyihao's avatar
dengyihao 已提交
381
  uint8_t* data = fstSliceData(slice, NULL);
dengyihao's avatar
dengyihao 已提交
382
  return data[at];
dengyihao's avatar
dengyihao 已提交
383 384 385
}

// trans_addr
dengyihao's avatar
dengyihao 已提交
386
CompiledAddr fstStateTransAddr(FstState* s, FstNode* node) {
dengyihao's avatar
dengyihao 已提交
387
  assert(s->state == OneTransNext || s->state == OneTrans);
dengyihao's avatar
dengyihao 已提交
388
  FstSlice* slice = &node->data;
dengyihao's avatar
dengyihao 已提交
389
  if (s->state == OneTransNext) {
390
    return (CompiledAddr)(node->end) - 1;
dengyihao's avatar
dengyihao 已提交
391
  } else {
392 393 394 395 396 397
    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 已提交
398
    uint8_t* data = fstSliceData(slice, NULL);
399 400
    return unpackDelta(data + i, tSizes, node->end);
  }
dengyihao's avatar
dengyihao 已提交
401
}
dengyihao's avatar
dengyihao 已提交
402
CompiledAddr fstStateTransAddrForAnyTrans(FstState* s, FstNode* node, uint64_t i) {
dengyihao's avatar
dengyihao 已提交
403 404
  assert(s->state == AnyTrans);

dengyihao's avatar
dengyihao 已提交
405
  FstSlice* slice = &node->data;
406
  uint8_t   tSizes = FST_GET_TRANSITION_PACK_SIZE(node->sizes);
dengyihao's avatar
dengyihao 已提交
407 408
  uint64_t  at = node->start - fstStateNtransLen(s) - 1 - fstStateTransIndexSize(s, node->version, node->nTrans) -
                node->nTrans - (i * tSizes) - tSizes;
dengyihao's avatar
dengyihao 已提交
409
  uint8_t* data = fstSliceData(slice, NULL);
410
  return unpackDelta(data + at, tSizes, node->end);
dengyihao's avatar
dengyihao 已提交
411 412
}

413
// sizes
dengyihao's avatar
dengyihao 已提交
414
PackSizes fstStateSizes(FstState* s, FstSlice* slice) {
415 416
  assert(s->state == OneTrans || s->state == AnyTrans);
  uint64_t i;
dengyihao's avatar
dengyihao 已提交
417
  if (s->state == OneTrans) {
418
    i = FST_SLICE_LEN(slice) - 1 - fstStateInputLen(s) - 1;
dengyihao's avatar
dengyihao 已提交
419 420 421 422
  } else {
    i = FST_SLICE_LEN(slice) - 1 - fstStateNtransLen(s) - 1;
  }

dengyihao's avatar
dengyihao 已提交
423
  uint8_t* data = fstSliceData(slice, NULL);
424
  return (PackSizes)(*(data + i));
dengyihao's avatar
dengyihao 已提交
425
}
426
// Output
dengyihao's avatar
dengyihao 已提交
427
Output fstStateOutput(FstState* s, FstNode* node) {
428 429
  assert(s->state == OneTrans);

dengyihao's avatar
dengyihao 已提交
430
  uint8_t oSizes = FST_GET_OUTPUT_PACK_SIZE(node->sizes);
dengyihao's avatar
dengyihao 已提交
431
  if (oSizes == 0) { return 0; }
dengyihao's avatar
dengyihao 已提交
432
  FstSlice* slice = &node->data;
433 434 435
  uint8_t   tSizes = FST_GET_TRANSITION_PACK_SIZE(node->sizes);

  uint64_t i = node->start - fstStateInputLen(s) - 1 - tSizes - oSizes;
dengyihao's avatar
dengyihao 已提交
436
  uint8_t* data = fstSliceData(slice, NULL);
dengyihao's avatar
dengyihao 已提交
437
  return unpackUint64(data + i, oSizes);
dengyihao's avatar
dengyihao 已提交
438
}
dengyihao's avatar
dengyihao 已提交
439
Output fstStateOutputForAnyTrans(FstState* s, FstNode* node, uint64_t i) {
dengyihao's avatar
dengyihao 已提交
440 441
  assert(s->state == AnyTrans);

442
  uint8_t oSizes = FST_GET_OUTPUT_PACK_SIZE(node->sizes);
dengyihao's avatar
dengyihao 已提交
443
  if (oSizes == 0) { return 0; }
dengyihao's avatar
dengyihao 已提交
444 445
  FstSlice* slice = &node->data;
  uint8_t*  data = fstSliceData(slice, NULL);
446 447
  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 已提交
448 449

  return unpackUint64(data + at, oSizes);
dengyihao's avatar
dengyihao 已提交
450 451 452 453
}

// anyTrans specify function

dengyihao's avatar
dengyihao 已提交
454
void fstStateSetFinalState(FstState* s, bool yes) {
455
  assert(s->state == AnyTrans);
dengyihao's avatar
dengyihao 已提交
456
  if (yes) { s->val |= 0b01000000; }
dengyihao's avatar
dengyihao 已提交
457 458
  return;
}
dengyihao's avatar
dengyihao 已提交
459
bool fstStateIsFinalState(FstState* s) {
460 461 462
  assert(s->state == AnyTrans);
  return (s->val & 0b01000000) == 0b01000000;
}
dengyihao's avatar
dengyihao 已提交
463

dengyihao's avatar
dengyihao 已提交
464
void fstStateSetStateNtrans(FstState* s, uint8_t n) {
465
  assert(s->state == AnyTrans);
dengyihao's avatar
dengyihao 已提交
466
  if (n <= 0b00111111) { s->val = (s->val & 0b11000000) | n; }
dengyihao's avatar
dengyihao 已提交
467 468 469
  return;
}
// state_ntrans
dengyihao's avatar
dengyihao 已提交
470
uint8_t fstStateStateNtrans(FstState* s, bool* null) {
471
  assert(s->state == AnyTrans);
dengyihao's avatar
dengyihao 已提交
472
  *null = false;
473
  uint8_t n = s->val & 0b00111111;
dengyihao's avatar
dengyihao 已提交
474 475

  if (n == 0) {
476 477
    *null = true;  // None
  }
dengyihao's avatar
dengyihao 已提交
478
  return n;
dengyihao's avatar
dengyihao 已提交
479
}
dengyihao's avatar
dengyihao 已提交
480
uint64_t fstStateTotalTransSize(FstState* s, uint64_t version, PackSizes sizes, uint64_t nTrans) {
481 482
  assert(s->state == AnyTrans);
  uint64_t idxSize = fstStateTransIndexSize(s, version, nTrans);
dengyihao's avatar
dengyihao 已提交
483
  return nTrans + (nTrans * FST_GET_TRANSITION_PACK_SIZE(sizes)) + idxSize;
dengyihao's avatar
dengyihao 已提交
484
}
dengyihao's avatar
dengyihao 已提交
485
uint64_t fstStateTransIndexSize(FstState* s, uint64_t version, uint64_t nTrans) {
486 487
  assert(s->state == AnyTrans);
  return (version >= 2 && nTrans > TRANS_INDEX_THRESHOLD) ? 256 : 0;
dengyihao's avatar
dengyihao 已提交
488
}
dengyihao's avatar
dengyihao 已提交
489
uint64_t fstStateNtransLen(FstState* s) {
dengyihao's avatar
dengyihao 已提交
490 491 492
  assert(s->state == AnyTrans);
  bool null = false;
  fstStateStateNtrans(s, &null);
493
  return null == true ? 1 : 0;
dengyihao's avatar
dengyihao 已提交
494
}
dengyihao's avatar
dengyihao 已提交
495
uint64_t fstStateNtrans(FstState* s, FstSlice* slice) {
496
  bool    null = false;
dengyihao's avatar
dengyihao 已提交
497
  uint8_t n = fstStateStateNtrans(s, &null);
dengyihao's avatar
dengyihao 已提交
498
  if (null != true) { return n; }
499
  int32_t  len;
dengyihao's avatar
dengyihao 已提交
500
  uint8_t* data = fstSliceData(slice, &len);
dengyihao's avatar
dengyihao 已提交
501
  n = data[len - 2];
502 503 504 505
  // 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 已提交
506
Output fstStateFinalOutput(FstState* s, uint64_t version, FstSlice* slice, PackSizes sizes, uint64_t nTrans) {
507
  uint8_t oSizes = FST_GET_OUTPUT_PACK_SIZE(sizes);
dengyihao's avatar
dengyihao 已提交
508
  if (oSizes == 0 || !fstStateIsFinalState(s)) { return 0; }
dengyihao's avatar
dengyihao 已提交
509

510 511
  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 已提交
512
  uint8_t* data = fstSliceData(slice, NULL);
513
  return unpackUint64(data + at, (uint8_t)oSizes);
dengyihao's avatar
dengyihao 已提交
514
}
dengyihao's avatar
dengyihao 已提交
515
uint64_t fstStateFindInput(FstState* s, FstNode* node, uint8_t b, bool* null) {
dengyihao's avatar
dengyihao 已提交
516
  assert(s->state == AnyTrans);
dengyihao's avatar
dengyihao 已提交
517
  FstSlice* slice = &node->data;
dengyihao's avatar
dengyihao 已提交
518
  if (node->version >= 2 && node->nTrans > TRANS_INDEX_THRESHOLD) {
519
    uint64_t at = node->start - fstStateNtransLen(s) - 1  // pack size
dengyihao's avatar
dengyihao 已提交
520
                  - fstStateTransIndexSize(s, node->version, node->nTrans);
521
    int32_t  dlen = 0;
dengyihao's avatar
dengyihao 已提交
522
    uint8_t* data = fstSliceData(slice, &dlen);
dengyihao's avatar
dengyihao 已提交
523
    uint64_t i = data[at + b];
524
    // uint64_t i = slice->data[slice->start + at + b];
dengyihao's avatar
dengyihao 已提交
525
    if (i >= node->nTrans) { *null = true; }
dengyihao's avatar
dengyihao 已提交
526 527
    return i;
  } else {
528 529 530
    uint64_t start = node->start - fstStateNtransLen(s) - 1  // pack size
                     - node->nTrans;
    uint64_t end = start + node->nTrans;
dengyihao's avatar
dengyihao 已提交
531
    FstSlice t = fstSliceCopy(slice, start, end - 1);
532
    int32_t  len = 0;
dengyihao's avatar
dengyihao 已提交
533
    uint8_t* data = fstSliceData(&t, &len);
534 535 536
    int      i = 0;
    for (; i < len; i++) {
      uint8_t v = data[i];
dengyihao's avatar
dengyihao 已提交
537
      if (v == b) {
dengyihao's avatar
dengyihao 已提交
538
        fstSliceDestroy(&t);
539
        return node->nTrans - i - 1;  // bug
dengyihao's avatar
dengyihao 已提交
540
      }
541
    }
dengyihao's avatar
dengyihao 已提交
542
    if (i == len) { *null = true; }
dengyihao's avatar
dengyihao 已提交
543
    fstSliceDestroy(&t);
544
  }
dengyihao's avatar
dengyihao 已提交
545 546
}

547
// fst node function
dengyihao's avatar
dengyihao 已提交
548

dengyihao's avatar
dengyihao 已提交
549 550
FstNode* fstNodeCreate(int64_t version, CompiledAddr addr, FstSlice* slice) {
  FstNode* n = (FstNode*)malloc(sizeof(FstNode));
dengyihao's avatar
dengyihao 已提交
551
  if (n == NULL) { return NULL; }
dengyihao's avatar
dengyihao 已提交
552

553
  FstState st = fstStateCreateFrom(slice, addr);
dengyihao's avatar
dengyihao 已提交
554 555

  if (st.state == EmptyFinal) {
556 557 558 559 560 561 562 563 564
    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 已提交
565
  } else if (st.state == OneTransNext) {
566 567 568 569 570 571 572 573 574
    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 已提交
575
  } else if (st.state == OneTrans) {
576 577 578 579 580 581 582 583 584 585 586
    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 已提交
587
  } else {
588 589 590 591 592 593 594 595 596 597 598
    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 已提交
599 600
    n->finalOutput =
        fstStateFinalOutput(&st, version, &data, sz, nTrans);  // s.final_output(version, data, sz, ntrans);
601 602
  }
  return n;
dengyihao's avatar
dengyihao 已提交
603
}
dengyihao's avatar
dengyihao 已提交
604 605

// debug state transition
dengyihao's avatar
dengyihao 已提交
606 607
static const char* fstNodeState(FstNode* node) {
  FstState* st = &node->state;
608
  return fstStateStr[st->state];
dengyihao's avatar
dengyihao 已提交
609 610
}

dengyihao's avatar
dengyihao 已提交
611
void fstNodeDestroy(FstNode* node) {
612
  fstSliceDestroy(&node->data);
dengyihao's avatar
dengyihao 已提交
613 614
  free(node);
}
dengyihao's avatar
dengyihao 已提交
615 616
FstTransitions* fstNodeTransitions(FstNode* node) {
  FstTransitions* t = malloc(sizeof(FstTransitions));
dengyihao's avatar
dengyihao 已提交
617
  if (NULL == t) { return NULL; }
dengyihao's avatar
dengyihao 已提交
618 619
  FstRange range = {.start = 0, .end = FST_NODE_LEN(node)};
  t->range = range;
620 621 622
  t->node = node;
  return t;
}
dengyihao's avatar
dengyihao 已提交
623

624
// Returns the transition at index `i`.
dengyihao's avatar
dengyihao 已提交
625
bool fstNodeGetTransitionAt(FstNode* node, uint64_t i, FstTransition* trn) {
626
  bool      s = true;
dengyihao's avatar
dengyihao 已提交
627
  FstState* st = &node->state;
dengyihao's avatar
dengyihao 已提交
628
  if (st->state == OneTransNext) {
629 630 631
    trn->inp = fstStateInput(st, node);
    trn->out = 0;
    trn->addr = fstStateTransAddr(st, node);
dengyihao's avatar
dengyihao 已提交
632
  } else if (st->state == OneTrans) {
633 634 635
    trn->inp = fstStateInput(st, node);
    trn->out = fstStateOutput(st, node);
    trn->addr = fstStateTransAddr(st, node);
dengyihao's avatar
dengyihao 已提交
636
  } else if (st->state == AnyTrans) {
637 638 639
    trn->inp = fstStateInputForAnyTrans(st, node, i);
    trn->out = fstStateOutputForAnyTrans(st, node, i);
    trn->addr = fstStateTransAddrForAnyTrans(st, node, i);
dengyihao's avatar
dengyihao 已提交
640 641 642 643
  } else {
    s = false;
  }
  return s;
644
}
dengyihao's avatar
dengyihao 已提交
645

dengyihao's avatar
dengyihao 已提交
646
// Returns the transition address of the `i`th transition
dengyihao's avatar
dengyihao 已提交
647
bool fstNodeGetTransitionAddrAt(FstNode* node, uint64_t i, CompiledAddr* res) {
648
  bool      s = true;
dengyihao's avatar
dengyihao 已提交
649
  FstState* st = &node->state;
dengyihao's avatar
dengyihao 已提交
650 651 652 653
  if (st->state == OneTransNext) {
    assert(i == 0);
    fstStateTransAddr(st, node);
  } else if (st->state == OneTrans) {
654
    assert(i == 0);
dengyihao's avatar
dengyihao 已提交
655 656 657
    fstStateTransAddr(st, node);
  } else if (st->state == AnyTrans) {
    fstStateTransAddrForAnyTrans(st, node, i);
658
  } else if (FST_STATE_EMPTY_FINAL(node)) {
dengyihao's avatar
dengyihao 已提交
659
    s = false;
dengyihao's avatar
dengyihao 已提交
660 661
  } else {
    assert(0);
dengyihao's avatar
dengyihao 已提交
662 663
  }
  return s;
dengyihao's avatar
dengyihao 已提交
664 665
}

dengyihao's avatar
dengyihao 已提交
666
//  Finds the `i`th transition corresponding to the given input byte.
667
//  If no transition for this byte exists, then `false` is returned.
dengyihao's avatar
dengyihao 已提交
668
bool fstNodeFindInput(FstNode* node, uint8_t b, uint64_t* res) {
669
  bool      s = true;
dengyihao's avatar
dengyihao 已提交
670
  FstState* st = &node->state;
dengyihao's avatar
dengyihao 已提交
671
  if (st->state == OneTransNext) {
672 673 674 675 676 677 678 679 680 681 682
    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 已提交
683
  } else if (st->state == AnyTrans) {
684 685 686 687 688 689 690
    bool     null = false;
    uint64_t out = fstStateFindInput(st, node, b, &null);
    if (null == false) {
      *res = out;
    } else {
      s = false;
    }
dengyihao's avatar
dengyihao 已提交
691
  }
dengyihao's avatar
dengyihao 已提交
692
  return s;
693
}
dengyihao's avatar
dengyihao 已提交
694

dengyihao's avatar
dengyihao 已提交
695
bool fstNodeCompile(FstNode* node, void* w, CompiledAddr lastAddr, CompiledAddr addr, FstBuilderNode* builderNode) {
696
  size_t sz = taosArrayGetSize(builderNode->trans);
dengyihao's avatar
dengyihao 已提交
697 698
  assert(sz < 256);
  if (sz == 0 && builderNode->isFinal && builderNode->finalOutput == 0) {
699
    return true;
dengyihao's avatar
dengyihao 已提交
700
  } else if (sz != 1 || builderNode->isFinal) {
701
    fstStateCompileForAnyTrans(w, addr, builderNode);
dengyihao's avatar
dengyihao 已提交
702 703
    // AnyTrans->Compile(w, addr, node);
  } else {
dengyihao's avatar
dengyihao 已提交
704
    FstTransition* tran = taosArrayGet(builderNode->trans, 0);
dengyihao's avatar
dengyihao 已提交
705
    if (tran->addr == lastAddr && tran->out == 0) {
706 707 708
      fstStateCompileForOneTransNext(w, addr, tran->inp);
      // OneTransNext::compile(w, lastAddr, tran->inp);
      return true;
dengyihao's avatar
dengyihao 已提交
709
    } else {
710 711 712 713 714 715 716
      fstStateCompileForOneTrans(w, addr, tran);
      // OneTrans::Compile(w, lastAddr, *tran);
      return true;
    }
  }
  return true;
}
dengyihao's avatar
dengyihao 已提交
717

dengyihao's avatar
dengyihao 已提交
718
bool fstBuilderNodeCompileTo(FstBuilderNode* b, FstCountingWriter* wrt, CompiledAddr lastAddr, CompiledAddr startAddr) {
dengyihao's avatar
dengyihao 已提交
719 720 721
  return fstNodeCompile(NULL, wrt, lastAddr, startAddr, b);
}

dengyihao's avatar
dengyihao 已提交
722 723
FstBuilder* fstBuilderCreate(void* w, FstType ty) {
  FstBuilder* b = malloc(sizeof(FstBuilder));
dengyihao's avatar
dengyihao 已提交
724
  if (NULL == b) { return b; }
dengyihao's avatar
dengyihao 已提交
725

726 727 728 729 730 731
  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 已提交
732

733
  char  buf64[8] = {0};
dengyihao's avatar
dengyihao 已提交
734
  void* pBuf64 = buf64;
735
  taosEncodeFixedU64(&pBuf64, VERSION);
dengyihao's avatar
dengyihao 已提交
736
  fstCountingWriterWrite(b->wrt, buf64, sizeof(buf64));
737 738

  memset(buf64, 0, sizeof(buf64));
dengyihao's avatar
dengyihao 已提交
739
  pBuf64 = buf64;
740
  taosEncodeFixedU64(&pBuf64, ty);
dengyihao's avatar
dengyihao 已提交
741 742
  fstCountingWriterWrite(b->wrt, buf64, sizeof(buf64));

dengyihao's avatar
dengyihao 已提交
743 744
  return b;
}
dengyihao's avatar
dengyihao 已提交
745
void fstBuilderDestroy(FstBuilder* b) {
dengyihao's avatar
dengyihao 已提交
746
  if (b == NULL) { return; }
dengyihao's avatar
dengyihao 已提交
747

748 749
  fstCountingWriterDestroy(b->wrt);
  fstUnFinishedNodesDestroy(b->unfinished);
dengyihao's avatar
dengyihao 已提交
750
  fstRegistryDestroy(b->registry);
dengyihao's avatar
dengyihao 已提交
751
  fstSliceDestroy(&b->last);
dengyihao's avatar
dengyihao 已提交
752 753
  free(b);
}
dengyihao's avatar
dengyihao 已提交
754

dengyihao's avatar
dengyihao 已提交
755
bool fstBuilderInsert(FstBuilder* b, FstSlice bs, Output in) {
756
  OrderType t = fstBuilderCheckLastKey(b, bs, true);
dengyihao's avatar
dengyihao 已提交
757 758
  if (t == Ordered) {
    // add log info
759 760 761
    fstBuilderInsertOutput(b, bs, in);
    return true;
  }
dengyihao's avatar
dengyihao 已提交
762
  indexInfo("fst write key must be ordered");
dengyihao's avatar
dengyihao 已提交
763 764 765
  return false;
}

dengyihao's avatar
dengyihao 已提交
766 767
void fstBuilderInsertOutput(FstBuilder* b, FstSlice bs, Output in) {
  FstSlice* s = &bs;
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
  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 已提交
795

dengyihao's avatar
dengyihao 已提交
796 797
OrderType fstBuilderCheckLastKey(FstBuilder* b, FstSlice bs, bool ckDup) {
  FstSlice* input = &bs;
dengyihao's avatar
dengyihao 已提交
798
  if (fstSliceIsEmpty(&b->last)) {
dengyihao's avatar
dengyihao 已提交
799
    fstSliceDestroy(&b->last);
dengyihao's avatar
dengyihao 已提交
800
    // deep copy or not
dengyihao's avatar
dengyihao 已提交
801
    b->last = fstSliceDeepCopy(&bs, input->start, input->end);
dengyihao's avatar
dengyihao 已提交
802 803 804
  } else {
    int comp = fstSliceCompare(&b->last, &bs);
    if (comp == 0 && ckDup) {
805
      return DuplicateKey;
dengyihao's avatar
dengyihao 已提交
806 807 808 809
    } else if (comp == 1) {
      return OutOfOrdered;
    }
    // deep copy or not
dengyihao's avatar
dengyihao 已提交
810
    fstSliceDestroy(&b->last);
811 812
    b->last = fstSliceDeepCopy(&bs, input->start, input->end);
  }
dengyihao's avatar
dengyihao 已提交
813
  return Ordered;
814
}
dengyihao's avatar
dengyihao 已提交
815
void fstBuilderCompileFrom(FstBuilder* b, uint64_t istate) {
dengyihao's avatar
dengyihao 已提交
816 817
  CompiledAddr addr = NONE_ADDRESS;
  while (istate + 1 < FST_UNFINISHED_NODES_LEN(b->unfinished)) {
dengyihao's avatar
dengyihao 已提交
818
    FstBuilderNode* bn = NULL;
dengyihao's avatar
dengyihao 已提交
819
    if (addr == NONE_ADDRESS) {
dengyihao's avatar
dengyihao 已提交
820
      bn = fstUnFinishedNodesPopEmpty(b->unfinished);
dengyihao's avatar
dengyihao 已提交
821
    } else {
dengyihao's avatar
dengyihao 已提交
822
      bn = fstUnFinishedNodesPopFreeze(b->unfinished, addr);
dengyihao's avatar
dengyihao 已提交
823
    }
dengyihao's avatar
dengyihao 已提交
824 825 826
    addr = fstBuilderCompile(b, bn);

    fstBuilderNodeDestroy(bn);
827 828
    assert(addr != NONE_ADDRESS);
    // fstBuilderNodeDestroy(n);
dengyihao's avatar
dengyihao 已提交
829 830
  }
  fstUnFinishedNodesTopLastFreeze(b->unfinished, addr);
831
  return;
dengyihao's avatar
dengyihao 已提交
832
}
dengyihao's avatar
dengyihao 已提交
833
CompiledAddr fstBuilderCompile(FstBuilder* b, FstBuilderNode* bn) {
834 835
  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 已提交
836
  }
dengyihao's avatar
dengyihao 已提交
837
  FstRegistryEntry* entry = fstRegistryGetEntry(b->registry, bn);
838
  if (entry->state == FOUND) {
dengyihao's avatar
dengyihao 已提交
839
    CompiledAddr ret = entry->addr;
dengyihao's avatar
dengyihao 已提交
840
    fstRegistryEntryDestroy(entry);
dengyihao's avatar
dengyihao 已提交
841
    return ret;
842
  }
dengyihao's avatar
dengyihao 已提交
843 844
  CompiledAddr startAddr = (CompiledAddr)(FST_WRITER_COUNT(b->wrt));

845 846
  fstBuilderNodeCompileTo(bn, b->wrt, b->lastAddr, startAddr);
  b->lastAddr = (CompiledAddr)(FST_WRITER_COUNT(b->wrt) - 1);
dengyihao's avatar
dengyihao 已提交
847
  if (entry->state == NOTFOUND) { FST_REGISTRY_CELL_INSERT(entry->cell, b->lastAddr); }
dengyihao's avatar
dengyihao 已提交
848
  fstRegistryEntryDestroy(entry);
849 850

  return b->lastAddr;
dengyihao's avatar
dengyihao 已提交
851 852
}

dengyihao's avatar
dengyihao 已提交
853
void* fstBuilderInsertInner(FstBuilder* b) {
854
  fstBuilderCompileFrom(b, 0);
dengyihao's avatar
dengyihao 已提交
855
  FstBuilderNode* rootNode = fstUnFinishedNodesPopRoot(b->unfinished);
856
  CompiledAddr    rootAddr = fstBuilderCompile(b, rootNode);
dengyihao's avatar
dengyihao 已提交
857
  fstBuilderNodeDestroy(rootNode);
dengyihao's avatar
dengyihao 已提交
858

859 860
  char buf64[8] = {0};

dengyihao's avatar
dengyihao 已提交
861
  void* pBuf64 = buf64;
862 863
  taosEncodeFixedU64(&pBuf64, b->len);
  fstCountingWriterWrite(b->wrt, buf64, sizeof(buf64));
dengyihao's avatar
dengyihao 已提交
864

dengyihao's avatar
dengyihao 已提交
865
  pBuf64 = buf64;
866 867
  taosEncodeFixedU64(&pBuf64, rootAddr);
  fstCountingWriterWrite(b->wrt, buf64, sizeof(buf64));
dengyihao's avatar
dengyihao 已提交
868

869
  char     buf32[4] = {0};
dengyihao's avatar
dengyihao 已提交
870
  void*    pBuf32 = buf32;
dengyihao's avatar
dengyihao 已提交
871
  uint32_t sum = fstCountingWriterMaskedCheckSum(b->wrt);
872 873 874
  taosEncodeFixedU32(&pBuf32, sum);
  fstCountingWriterWrite(b->wrt, buf32, sizeof(buf32));

dengyihao's avatar
dengyihao 已提交
875
  fstCountingWriterFlush(b->wrt);
876 877
  // fstCountingWriterDestroy(b->wrt);
  // b->wrt = NULL;
dengyihao's avatar
dengyihao 已提交
878 879
  return b->wrt;
}
dengyihao's avatar
dengyihao 已提交
880
void fstBuilderFinish(FstBuilder* b) { fstBuilderInsertInner(b); }
dengyihao's avatar
dengyihao 已提交
881

dengyihao's avatar
dengyihao 已提交
882 883
FstSlice fstNodeAsSlice(FstNode* node) {
  FstSlice* slice = &node->data;
884 885
  FstSlice  s = fstSliceCopy(slice, slice->end, FST_SLICE_LEN(slice) - 1);
  return s;
dengyihao's avatar
dengyihao 已提交
886
}
dengyihao's avatar
dengyihao 已提交
887

dengyihao's avatar
dengyihao 已提交
888 889
FstLastTransition* fstLastTransitionCreate(uint8_t inp, Output out) {
  FstLastTransition* trn = malloc(sizeof(FstLastTransition));
dengyihao's avatar
dengyihao 已提交
890
  if (trn == NULL) { return NULL; }
dengyihao's avatar
dengyihao 已提交
891 892 893 894 895 896

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

dengyihao's avatar
dengyihao 已提交
897
void fstLastTransitionDestroy(FstLastTransition* trn) { free(trn); }
dengyihao's avatar
dengyihao 已提交
898 899
void fstBuilderNodeUnfinishedLastCompiled(FstBuilderNodeUnfinished* unNode, CompiledAddr addr) {
  FstLastTransition* trn = unNode->last;
dengyihao's avatar
dengyihao 已提交
900
  if (trn == NULL) { return; }
901 902 903
  FstTransition t = {.inp = trn->inp, .out = trn->out, .addr = addr};
  taosArrayPush(unNode->node->trans, &t);
  fstLastTransitionDestroy(trn);
dengyihao's avatar
dengyihao 已提交
904
  unNode->last = NULL;
dengyihao's avatar
dengyihao 已提交
905 906 907
  return;
}

dengyihao's avatar
dengyihao 已提交
908
void fstBuilderNodeUnfinishedAddOutputPrefix(FstBuilderNodeUnfinished* unNode, Output out) {
dengyihao's avatar
dengyihao 已提交
909
  if (FST_BUILDER_NODE_IS_FINAL(unNode->node)) { unNode->node->finalOutput += out; }
dengyihao's avatar
dengyihao 已提交
910 911
  size_t sz = taosArrayGetSize(unNode->node->trans);
  for (size_t i = 0; i < sz; i++) {
dengyihao's avatar
dengyihao 已提交
912
    FstTransition* trn = taosArrayGet(unNode->node->trans, i);
dengyihao's avatar
dengyihao 已提交
913 914
    trn->out += out;
  }
dengyihao's avatar
dengyihao 已提交
915
  if (unNode->last) { unNode->last->out += out; }
dengyihao's avatar
dengyihao 已提交
916 917 918
  return;
}

dengyihao's avatar
dengyihao 已提交
919
Fst* fstCreate(FstSlice* slice) {
dengyihao's avatar
dengyihao 已提交
920
  int32_t slen;
dengyihao's avatar
dengyihao 已提交
921
  char*   buf = fstSliceData(slice, &slen);
dengyihao's avatar
dengyihao 已提交
922
  if (slen < 36) { return NULL; }
dengyihao's avatar
dengyihao 已提交
923
  uint64_t len = slen;
924
  uint64_t skip = 0;
dengyihao's avatar
dengyihao 已提交
925

926 927 928
  uint64_t version;
  taosDecodeFixedU64(buf, &version);
  skip += sizeof(version);
dengyihao's avatar
dengyihao 已提交
929
  if (version == 0 || version > VERSION) { return NULL; }
dengyihao's avatar
dengyihao 已提交
930 931 932

  uint64_t type;
  taosDecodeFixedU64(buf + skip, &type);
933
  skip += sizeof(type);
dengyihao's avatar
dengyihao 已提交
934 935 936

  uint32_t checkSum = 0;
  len -= sizeof(checkSum);
937
  taosDecodeFixedU32(buf + len, &checkSum);
dengyihao's avatar
dengyihao 已提交
938 939

  CompiledAddr rootAddr;
940 941
  len -= sizeof(rootAddr);
  taosDecodeFixedU64(buf + len, &rootAddr);
dengyihao's avatar
dengyihao 已提交
942

943 944
  uint64_t fstLen;
  len -= sizeof(fstLen);
dengyihao's avatar
dengyihao 已提交
945
  taosDecodeFixedU64(buf + len, &fstLen);
946
  // TODO(validate root addr)
dengyihao's avatar
dengyihao 已提交
947
  Fst* fst = (Fst*)calloc(1, sizeof(Fst));
dengyihao's avatar
dengyihao 已提交
948
  if (fst == NULL) { return NULL; }
949

dengyihao's avatar
dengyihao 已提交
950
  fst->meta = (FstMeta*)malloc(sizeof(FstMeta));
dengyihao's avatar
dengyihao 已提交
951
  if (NULL == fst->meta) { goto FST_CREAT_FAILED; }
dengyihao's avatar
dengyihao 已提交
952

953 954 955 956
  fst->meta->version = version;
  fst->meta->rootAddr = rootAddr;
  fst->meta->ty = type;
  fst->meta->len = fstLen;
dengyihao's avatar
dengyihao 已提交
957
  fst->meta->checkSum = checkSum;
dengyihao's avatar
dengyihao 已提交
958

dengyihao's avatar
dengyihao 已提交
959
  FstSlice* s = calloc(1, sizeof(FstSlice));
dengyihao's avatar
dengyihao 已提交
960
  *s = fstSliceCopy(slice, 0, FST_SLICE_LEN(slice) - 1);
961 962
  fst->data = s;

dengyihao's avatar
dengyihao 已提交
963
  pthread_mutex_init(&fst->mtx, NULL);
dengyihao's avatar
dengyihao 已提交
964 965
  return fst;

966 967
FST_CREAT_FAILED:
  free(fst->meta);
dengyihao's avatar
dengyihao 已提交
968 969
  free(fst);
}
dengyihao's avatar
dengyihao 已提交
970
void fstDestroy(Fst* fst) {
971 972
  if (fst) {
    free(fst->meta);
dengyihao's avatar
dengyihao 已提交
973 974
    fstSliceDestroy(fst->data);
    free(fst->data);
dengyihao's avatar
dengyihao 已提交
975
    pthread_mutex_destroy(&fst->mtx);
976 977
  }
  free(fst);
dengyihao's avatar
dengyihao 已提交
978 979
}

dengyihao's avatar
dengyihao 已提交
980
bool fstGet(Fst* fst, FstSlice* b, Output* out) {
dengyihao's avatar
dengyihao 已提交
981 982
  // dec lock range
  pthread_mutex_lock(&fst->mtx);
dengyihao's avatar
dengyihao 已提交
983
  FstNode* root = fstGetRoot(fst);
984 985
  Output   tOut = 0;
  int32_t  len;
dengyihao's avatar
dengyihao 已提交
986

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

dengyihao's avatar
dengyihao 已提交
989
  SArray* nodes = (SArray*)taosArrayInit(len, sizeof(FstNode*));
dengyihao's avatar
dengyihao 已提交
990
  taosArrayPush(nodes, &root);
dengyihao's avatar
dengyihao 已提交
991 992
  for (uint32_t i = 0; i < len; i++) {
    uint8_t inp = data[i];
dengyihao's avatar
dengyihao 已提交
993
    Output  res = 0;
dengyihao's avatar
dengyihao 已提交
994 995 996 997
    if (false == fstNodeFindInput(root, inp, &res)) {
      pthread_mutex_unlock(&fst->mtx);
      return false;
    }
dengyihao's avatar
dengyihao 已提交
998

999
    FstTransition trn;
dengyihao's avatar
dengyihao 已提交
1000
    fstNodeGetTransitionAt(root, res, &trn);
1001
    tOut += trn.out;
dengyihao's avatar
dengyihao 已提交
1002
    root = fstGetNode(fst, trn.addr);
dengyihao's avatar
dengyihao 已提交
1003
    taosArrayPush(nodes, &root);
dengyihao's avatar
dengyihao 已提交
1004 1005
  }
  if (!FST_NODE_IS_FINAL(root)) {
dengyihao's avatar
dengyihao 已提交
1006
    pthread_mutex_unlock(&fst->mtx);
dengyihao's avatar
dengyihao 已提交
1007 1008
    return false;
  } else {
1009
    tOut = tOut + FST_NODE_FINAL_OUTPUT(root);
dengyihao's avatar
dengyihao 已提交
1010
  }
dengyihao's avatar
dengyihao 已提交
1011

dengyihao's avatar
dengyihao 已提交
1012
  for (size_t i = 0; i < taosArrayGetSize(nodes); i++) {
dengyihao's avatar
dengyihao 已提交
1013
    FstNode** node = (FstNode**)taosArrayGet(nodes, i);
1014
    fstNodeDestroy(*node);
dengyihao's avatar
dengyihao 已提交
1015 1016 1017
  }
  taosArrayDestroy(nodes);
  fst->root = NULL;
dengyihao's avatar
dengyihao 已提交
1018
  pthread_mutex_unlock(&fst->mtx);
dengyihao's avatar
dengyihao 已提交
1019
  *out = tOut;
1020
  return true;
dengyihao's avatar
dengyihao 已提交
1021
}
dengyihao's avatar
dengyihao 已提交
1022
FstStreamBuilder* fstSearch(Fst* fst, AutomationCtx* ctx) {
dengyihao's avatar
dengyihao 已提交
1023
  // refactor later
dengyihao's avatar
dengyihao 已提交
1024 1025 1026
  return fstStreamBuilderCreate(fst, ctx);
}
StreamWithState* streamBuilderIntoStream(FstStreamBuilder* sb) {
dengyihao's avatar
dengyihao 已提交
1027
  if (sb == NULL) { return NULL; }
dengyihao's avatar
dengyihao 已提交
1028 1029
  return streamWithStateCreate(sb->fst, sb->aut, sb->min, sb->max);
}
dengyihao's avatar
dengyihao 已提交
1030
FstStreamWithStateBuilder* fstSearchWithState(Fst* fst, AutomationCtx* ctx) {
dengyihao's avatar
dengyihao 已提交
1031
  // refactor later
dengyihao's avatar
dengyihao 已提交
1032 1033
  return fstStreamBuilderCreate(fst, ctx);
}
dengyihao's avatar
dengyihao 已提交
1034

dengyihao's avatar
dengyihao 已提交
1035
FstNode* fstGetRoot(Fst* fst) {
1036
  CompiledAddr rAddr = fstGetRootAddr(fst);
dengyihao's avatar
dengyihao 已提交
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
  return fstGetNode(fst, rAddr);
  // pthread_mutex_lock(&fst->mtx);
  // if (fst->root != NULL) {
  //  // pthread_mutex_unlock(&fst->mtx);
  //  return fst->root;
  //}
  // CompiledAddr rAddr = fstGetRootAddr(fst);
  // fst->root = fstGetNode(fst, rAddr);
  //// pthread_mutex_unlock(&fst->mtx);
  // return fst->root;
dengyihao's avatar
dengyihao 已提交
1047
}
dengyihao's avatar
dengyihao 已提交
1048

dengyihao's avatar
dengyihao 已提交
1049
FstNode* fstGetNode(Fst* fst, CompiledAddr addr) {
dengyihao's avatar
dengyihao 已提交
1050
  // refactor later
dengyihao's avatar
dengyihao 已提交
1051 1052
  return fstNodeCreate(fst->meta->version, addr, fst->data);
}
dengyihao's avatar
dengyihao 已提交
1053 1054
FstType      fstGetType(Fst* fst) { return fst->meta->ty; }
CompiledAddr fstGetRootAddr(Fst* fst) { return fst->meta->rootAddr; }
dengyihao's avatar
dengyihao 已提交
1055

dengyihao's avatar
dengyihao 已提交
1056
Output fstEmptyFinalOutput(Fst* fst, bool* null) {
1057
  Output   res = 0;
dengyihao's avatar
dengyihao 已提交
1058
  FstNode* node = fstGetRoot(fst);
dengyihao's avatar
dengyihao 已提交
1059 1060
  if (FST_NODE_IS_FINAL(node)) {
    *null = false;
1061
    res = FST_NODE_FINAL_OUTPUT(node);
dengyihao's avatar
dengyihao 已提交
1062 1063 1064 1065 1066 1067
  } else {
    *null = true;
  }
  return res;
}

dengyihao's avatar
dengyihao 已提交
1068
bool fstVerify(Fst* fst) {
dengyihao's avatar
dengyihao 已提交
1069
  uint32_t len, checkSum = fst->meta->checkSum;
dengyihao's avatar
dengyihao 已提交
1070
  uint8_t* data = fstSliceData(fst->data, &len);
1071
  TSCKSUM  initSum = 0;
dengyihao's avatar
dengyihao 已提交
1072
  if (!taosCheckChecksumWhole(data, len)) { return false; }
dengyihao's avatar
dengyihao 已提交
1073
  return true;
dengyihao's avatar
dengyihao 已提交
1074 1075
}

dengyihao's avatar
dengyihao 已提交
1076
// data bound function
dengyihao's avatar
dengyihao 已提交
1077 1078
FstBoundWithData* fstBoundStateCreate(FstBound type, FstSlice* data) {
  FstBoundWithData* b = calloc(1, sizeof(FstBoundWithData));
dengyihao's avatar
dengyihao 已提交
1079
  if (b == NULL) { return NULL; }
dengyihao's avatar
dengyihao 已提交
1080 1081 1082 1083 1084 1085

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

1088
  return b;
dengyihao's avatar
dengyihao 已提交
1089 1090
}

dengyihao's avatar
dengyihao 已提交
1091
bool fstBoundWithDataExceededBy(FstBoundWithData* bound, FstSlice* slice) {
dengyihao's avatar
dengyihao 已提交
1092 1093 1094 1095 1096 1097
  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 已提交
1098
    return false;
dengyihao's avatar
dengyihao 已提交
1099 1100
  }
}
dengyihao's avatar
dengyihao 已提交
1101
bool fstBoundWithDataIsEmpty(FstBoundWithData* bound) {
dengyihao's avatar
dengyihao 已提交
1102 1103
  if (bound->type == Unbounded) {
    return true;
1104 1105 1106
  } else {
    return fstSliceIsEmpty(&bound->data);
  }
dengyihao's avatar
dengyihao 已提交
1107 1108
}

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

dengyihao's avatar
dengyihao 已提交
1111
void fstBoundDestroy(FstBoundWithData* bound) { free(bound); }
dengyihao's avatar
dengyihao 已提交
1112

dengyihao's avatar
dengyihao 已提交
1113 1114
StreamWithState* streamWithStateCreate(Fst* fst, AutomationCtx* automation, FstBoundWithData* min,
                                       FstBoundWithData* max) {
dengyihao's avatar
dengyihao 已提交
1115
  StreamWithState* sws = calloc(1, sizeof(StreamWithState));
dengyihao's avatar
dengyihao 已提交
1116
  if (sws == NULL) { return NULL; }
1117 1118 1119

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

  sws->emptyOutput.null = false;
1123
  sws->emptyOutput.out = 0;
dengyihao's avatar
dengyihao 已提交
1124

dengyihao's avatar
dengyihao 已提交
1125
  sws->stack = (SArray*)taosArrayInit(256, sizeof(StreamState));
1126
  sws->endAt = max;
dengyihao's avatar
dengyihao 已提交
1127 1128 1129 1130
  streamWithStateSeekMin(sws, min);

  return sws;
}
dengyihao's avatar
dengyihao 已提交
1131
void streamWithStateDestroy(StreamWithState* sws) {
dengyihao's avatar
dengyihao 已提交
1132
  if (sws == NULL) { return; }
dengyihao's avatar
dengyihao 已提交
1133 1134

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

1137
  free(sws);
dengyihao's avatar
dengyihao 已提交
1138 1139
}

dengyihao's avatar
dengyihao 已提交
1140 1141
bool streamWithStateSeekMin(StreamWithState* sws, FstBoundWithData* min) {
  AutomationCtx* aut = sws->aut;
dengyihao's avatar
dengyihao 已提交
1142
  if (fstBoundWithDataIsEmpty(min)) {
dengyihao's avatar
dengyihao 已提交
1143 1144 1145
    if (fstBoundWithDataIsIncluded(min)) {
      sws->emptyOutput.out = fstEmptyFinalOutput(sws->fst, &(sws->emptyOutput.null));
    }
1146
    StreamState s = {.node = fstGetRoot(sws->fst),
dengyihao's avatar
dengyihao 已提交
1147 1148 1149
                     .trans = 0,
                     .out = {.null = false, .out = 0},
                     .autState = automFuncs[aut->type].start(aut)};  // auto.start callback
dengyihao's avatar
dengyihao 已提交
1150 1151
    taosArrayPush(sws->stack, &s);
    return true;
1152
  }
dengyihao's avatar
dengyihao 已提交
1153
  FstSlice* key = NULL;
1154
  bool      inclusize = false;
dengyihao's avatar
dengyihao 已提交
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164

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

dengyihao's avatar
dengyihao 已提交
1165
  FstNode* node = fstGetRoot(sws->fst);
1166 1167
  Output   out = 0;
  // void*   autState = sws->aut->start();
dengyihao's avatar
dengyihao 已提交
1168
  void* autState = automFuncs[aut->type].start(aut);
dengyihao's avatar
dengyihao 已提交
1169

1170
  int32_t  len;
dengyihao's avatar
dengyihao 已提交
1171
  uint8_t* data = fstSliceData(key, &len);
dengyihao's avatar
dengyihao 已提交
1172
  for (uint32_t i = 0; i < len; i++) {
1173
    uint8_t  b = data[i];
dengyihao's avatar
dengyihao 已提交
1174
    uint64_t res = 0;
1175
    bool     null = fstNodeFindInput(node, b, &res);
dengyihao's avatar
dengyihao 已提交
1176 1177
    if (null == false) {
      FstTransition trn;
1178
      fstNodeGetTransitionAt(node, res, &trn);
dengyihao's avatar
dengyihao 已提交
1179
      void* preState = autState;
dengyihao's avatar
dengyihao 已提交
1180 1181
      // autState = sws->aut->accept(preState, b);
      autState = automFuncs[aut->type].accept(aut, preState, b);
dengyihao's avatar
dengyihao 已提交
1182
      taosArrayPush(sws->inp, &b);
1183
      StreamState s = {.node = node, .trans = res + 1, .out = {.null = false, .out = out}, .autState = preState};
dengyihao's avatar
dengyihao 已提交
1184 1185
      taosArrayPush(sws->stack, &s);
      out += trn.out;
1186
      node = fstGetNode(sws->fst, trn.addr);
dengyihao's avatar
dengyihao 已提交
1187
      fstNodeDestroy(node);
dengyihao's avatar
dengyihao 已提交
1188 1189 1190 1191 1192
    } 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
1193
      // input byte.
dengyihao's avatar
dengyihao 已提交
1194
      FstTransitions* trans = fstNodeTransitions(node);
1195
      uint64_t        i = 0;
dengyihao's avatar
dengyihao 已提交
1196 1197
      for (i = trans->range.start; i < trans->range.end; i++) {
        FstTransition trn;
dengyihao's avatar
dengyihao 已提交
1198
        if (fstNodeGetTransitionAt(node, i, &trn) && trn.inp > b) { break; }
dengyihao's avatar
dengyihao 已提交
1199
      }
1200 1201 1202 1203

      StreamState s = {.node = node, .trans = i, .out = {.null = false, .out = out}, .autState = autState};
      taosArrayPush(sws->stack, &s);
      return true;
dengyihao's avatar
dengyihao 已提交
1204 1205
    }
  }
1206
  uint32_t sz = taosArrayGetSize(sws->stack);
dengyihao's avatar
dengyihao 已提交
1207
  if (sz != 0) {
dengyihao's avatar
dengyihao 已提交
1208
    StreamState* s = taosArrayGet(sws->stack, sz - 1);
dengyihao's avatar
dengyihao 已提交
1209 1210 1211 1212
    if (inclusize) {
      s->trans -= 1;
      taosArrayPop(sws->inp);
    } else {
dengyihao's avatar
dengyihao 已提交
1213
      FstNode*      n = s->node;
1214 1215
      uint64_t      trans = s->trans;
      FstTransition trn;
dengyihao's avatar
dengyihao 已提交
1216
      fstNodeGetTransitionAt(n, trans - 1, &trn);
dengyihao's avatar
dengyihao 已提交
1217 1218
      StreamState s = {
          .node = fstGetNode(sws->fst, trn.addr), .trans = 0, .out = {.null = false, .out = out}, .autState = autState};
dengyihao's avatar
dengyihao 已提交
1219
      taosArrayPush(sws->stack, &s);
1220 1221 1222 1223 1224
      return true;
    }
    return false;
  }
}
dengyihao's avatar
dengyihao 已提交
1225

dengyihao's avatar
dengyihao 已提交
1226 1227
StreamWithStateResult* streamWithStateNextWith(StreamWithState* sws, StreamCallback callback) {
  AutomationCtx* aut = sws->aut;
1228
  FstOutput      output = sws->emptyOutput;
dengyihao's avatar
dengyihao 已提交
1229
  if (output.null == false) {
1230
    FstSlice emptySlice = fstSliceCreate(NULL, 0);
dengyihao's avatar
dengyihao 已提交
1231 1232
    if (fstBoundWithDataExceededBy(sws->endAt, &emptySlice)) {
      taosArrayDestroyEx(sws->stack, streamStateDestroy);
dengyihao's avatar
dengyihao 已提交
1233
      sws->stack = (SArray*)taosArrayInit(256, sizeof(StreamState));
dengyihao's avatar
dengyihao 已提交
1234 1235
      return NULL;
    }
dengyihao's avatar
dengyihao 已提交
1236
    void* start = automFuncs[aut->type].start(aut);
dengyihao's avatar
dengyihao 已提交
1237
    if (automFuncs[aut->type].isMatch(aut, start)) {
dengyihao's avatar
dengyihao 已提交
1238
      FstSlice s = fstSliceCreate(NULL, 0);
dengyihao's avatar
dengyihao 已提交
1239
      return swsResultCreate(&s, output, callback == NULL ? NULL : callback(start));
dengyihao's avatar
dengyihao 已提交
1240 1241
    }
  }
dengyihao's avatar
dengyihao 已提交
1242
  SArray* nodes = taosArrayInit(8, sizeof(FstNode*));
dengyihao's avatar
dengyihao 已提交
1243
  while (taosArrayGetSize(sws->stack) > 0) {
dengyihao's avatar
dengyihao 已提交
1244
    StreamState* p = (StreamState*)taosArrayPop(sws->stack);
dengyihao's avatar
dengyihao 已提交
1245
    if (p->trans >= FST_NODE_LEN(p->node) || !automFuncs[aut->type].canMatch(aut, p->autState)) {
dengyihao's avatar
dengyihao 已提交
1246
      if (FST_NODE_ADDR(p->node) != fstGetRootAddr(sws->fst)) { taosArrayPop(sws->inp); }
1247
      streamStateDestroy(p);
dengyihao's avatar
dengyihao 已提交
1248 1249
      continue;
    }
1250
    FstTransition trn;
dengyihao's avatar
dengyihao 已提交
1251
    fstNodeGetTransitionAt(p->node, p->trans, &trn);
dengyihao's avatar
dengyihao 已提交
1252 1253 1254 1255 1256 1257

    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 已提交
1258
    FstNode* nextNode = fstGetNode(sws->fst, trn.addr);
1259 1260
    taosArrayPush(nodes, &nextNode);
    taosArrayPush(sws->inp, &(trn.inp));
dengyihao's avatar
dengyihao 已提交
1261 1262

    if (FST_NODE_IS_FINAL(nextNode)) {
1263
      // void *eofState = sws->aut->acceptEof(nextState);
dengyihao's avatar
dengyihao 已提交
1264
      void* eofState = automFuncs[aut->type].acceptEof(aut, nextState);
dengyihao's avatar
dengyihao 已提交
1265
      if (eofState != NULL) { isMatch = automFuncs[aut->type].isMatch(aut, eofState); }
1266 1267
    }
    StreamState s1 = {.node = p->node, .trans = p->trans + 1, .out = p->out, .autState = p->autState};
dengyihao's avatar
dengyihao 已提交
1268 1269 1270 1271
    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 已提交
1272

1273
    size_t   isz = taosArrayGetSize(sws->inp);
dengyihao's avatar
dengyihao 已提交
1274
    uint8_t* buf = (uint8_t*)malloc(isz * sizeof(uint8_t));
dengyihao's avatar
dengyihao 已提交
1275
    for (uint32_t i = 0; i < isz; i++) { buf[i] = *(uint8_t*)taosArrayGet(sws->inp, i); }
dengyihao's avatar
dengyihao 已提交
1276 1277 1278
    FstSlice slice = fstSliceCreate(buf, taosArrayGetSize(sws->inp));
    if (fstBoundWithDataExceededBy(sws->endAt, &slice)) {
      taosArrayDestroyEx(sws->stack, streamStateDestroy);
dengyihao's avatar
dengyihao 已提交
1279
      sws->stack = (SArray*)taosArrayInit(256, sizeof(StreamState));
dengyihao's avatar
dengyihao 已提交
1280
      free(buf);
dengyihao's avatar
dengyihao 已提交
1281
      fstSliceDestroy(&slice);
dengyihao's avatar
dengyihao 已提交
1282 1283 1284
      return NULL;
    }
    if (FST_NODE_IS_FINAL(nextNode) && isMatch) {
1285
      FstOutput              fOutput = {.null = false, .out = out + FST_NODE_FINAL_OUTPUT(nextNode)};
dengyihao's avatar
dengyihao 已提交
1286
      StreamWithStateResult* result = swsResultCreate(&slice, fOutput, tState);
dengyihao's avatar
dengyihao 已提交
1287
      free(buf);
dengyihao's avatar
dengyihao 已提交
1288
      fstSliceDestroy(&slice);
1289
      return result;
dengyihao's avatar
dengyihao 已提交
1290
    }
dengyihao's avatar
dengyihao 已提交
1291
    free(buf);
dengyihao's avatar
dengyihao 已提交
1292
    fstSliceDestroy(&slice);
dengyihao's avatar
dengyihao 已提交
1293
  }
dengyihao's avatar
dengyihao 已提交
1294
  for (size_t i = 0; i < taosArrayGetSize(nodes); i++) {
dengyihao's avatar
dengyihao 已提交
1295
    FstNode** node = (FstNode**)taosArrayGet(nodes, i);
dengyihao's avatar
dengyihao 已提交
1296 1297 1298
    fstNodeDestroy(*node);
  }
  taosArrayDestroy(nodes);
1299
  return NULL;
dengyihao's avatar
dengyihao 已提交
1300 1301
}

dengyihao's avatar
dengyihao 已提交
1302 1303
StreamWithStateResult* swsResultCreate(FstSlice* data, FstOutput fOut, void* state) {
  StreamWithStateResult* result = calloc(1, sizeof(StreamWithStateResult));
dengyihao's avatar
dengyihao 已提交
1304
  if (result == NULL) { return NULL; }
1305 1306 1307 1308

  result->data = fstSliceCopy(data, 0, FST_SLICE_LEN(data) - 1);
  result->out = fOut;
  result->state = state;
dengyihao's avatar
dengyihao 已提交
1309 1310 1311

  return result;
}
dengyihao's avatar
dengyihao 已提交
1312
void swsResultDestroy(StreamWithStateResult* result) {
dengyihao's avatar
dengyihao 已提交
1313
  if (NULL == result) { return; }
1314

dengyihao's avatar
dengyihao 已提交
1315
  fstSliceDestroy(&result->data);
1316
  startWithStateValueDestroy(result->state);
dengyihao's avatar
dengyihao 已提交
1317 1318 1319
  free(result);
}

dengyihao's avatar
dengyihao 已提交
1320
void streamStateDestroy(void* s) {
dengyihao's avatar
dengyihao 已提交
1321
  if (NULL == s) { return; }
dengyihao's avatar
dengyihao 已提交
1322
  StreamState* ss = (StreamState*)s;
dengyihao's avatar
dengyihao 已提交
1323 1324

  fstNodeDestroy(ss->node);
1325
  // free(s->autoState);
dengyihao's avatar
dengyihao 已提交
1326 1327
}

dengyihao's avatar
dengyihao 已提交
1328 1329
FstStreamBuilder* fstStreamBuilderCreate(Fst* fst, AutomationCtx* aut) {
  FstStreamBuilder* b = calloc(1, sizeof(FstStreamBuilder));
dengyihao's avatar
dengyihao 已提交
1330
  if (NULL == b) { return NULL; }
dengyihao's avatar
dengyihao 已提交
1331 1332 1333 1334

  b->fst = fst;
  b->aut = aut;
  b->min = fstBoundStateCreate(Unbounded, NULL);
1335
  b->max = fstBoundStateCreate(Unbounded, NULL);
dengyihao's avatar
dengyihao 已提交
1336 1337
  return b;
}
dengyihao's avatar
dengyihao 已提交
1338
void fstStreamBuilderDestroy(FstStreamBuilder* b) {
dengyihao's avatar
dengyihao 已提交
1339 1340
  fstSliceDestroy(&b->min->data);
  fstSliceDestroy(&b->max->data);
dengyihao's avatar
dengyihao 已提交
1341
  tfree(b->min);
dengyihao's avatar
dengyihao 已提交
1342
  tfree(b->max);
dengyihao's avatar
dengyihao 已提交
1343 1344
  free(b);
}
dengyihao's avatar
dengyihao 已提交
1345
FstStreamBuilder* fstStreamBuilderRange(FstStreamBuilder* b, FstSlice* val, RangeType type) {
dengyihao's avatar
dengyihao 已提交
1346
  if (b == NULL) { return NULL; }
dengyihao's avatar
dengyihao 已提交
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366

  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);
  }
  return b;
}