tcompression.c 43.2 KB
Newer Older
H
hzcheng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/*
 * 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/>.
 */

/* README.md   TAOS compression
 *
 * INTEGER Compression Algorithm:
S
Shengliang Guan 已提交
19
 *   To compress integers (including char, short, int32_t, int64_t), the difference
H
hzcheng 已提交
20 21
 *   between two integers is calculated at first. Then the difference is
 *   transformed to positive by zig-zag encoding method
22
 *   (https://gist.github.com/mfuerstenau/ba870a29e16536fdbaba). Then the value is
H
hzcheng 已提交
23 24 25
 *   encoded using simple 8B method. For more information about simple 8B,
 *   refer to https://en.wikipedia.org/wiki/8b/10b_encoding.
 *
26
 *   NOTE : For bigint, only 59 bits can be used, which means data from -(2**59) to (2**59)-1
H
hzcheng 已提交
27 28 29
 *   are allowed.
 *
 * BOOLEAN Compression Algorithm:
30
 *   We provide two methods for compress boolean types. Because boolean types in C
31
 *   code are char bytes with 0 and 1 values only, only one bit can used to discriminate
H
hzcheng 已提交
32
 *   the values.
33
 *   1. The first method is using only 1 bit to represent the boolean value with 1 for
H
hzcheng 已提交
34
 *   true and 0 for false. Then the compression rate is 1/8.
35
 *   2. The second method is using run length encoding (RLE) methods. This method works
H
hzcheng 已提交
36 37 38 39 40 41
 *   better when there are a lot of consecutive true values or false values.
 *
 * STRING Compression Algorithm:
 *   We us LZ4 method to compress the string type.
 *
 * FLOAT Compression Algorithm:
42 43 44 45 46
 *   We use the same method with Akumuli to compress float and double types. The compression
 *   algorithm assumes the float/double values change slightly. So we take the XOR between two
 *   adjacent values. Then compare the number of leading zeros and trailing zeros. If the number
 *   of leading zeros are larger than the trailing zeros, then record the last serveral bytes
 *   of the XORed value with informations. If not, record the first corresponding bytes.
H
hzcheng 已提交
47 48 49
 *
 */

S
Shengliang Guan 已提交
50
#define _DEFAULT_SOURCE
H
Haojun Liao 已提交
51
#include "tcompression.h"
S
Shengliang Guan 已提交
52
#include "lz4.h"
H
Hongze Cheng 已提交
53
#include "tRealloc.h"
S
log  
Shengliang Guan 已提交
54
#include "tlog.h"
H
hzcheng 已提交
55

S
Shengliang Guan 已提交
56 57 58 59 60 61
#ifdef TD_TSZ
#include "td_sz.h"
#endif

static const int32_t TEST_NUMBER = 1;
#define is_bigendian()     ((*(char *)&TEST_NUMBER) == 0)
H
Hongze Cheng 已提交
62
#define SIMPLE8B_MAX_INT64 ((uint64_t)1152921504606846974LL)
H
hzcheng 已提交
63

S
Shengliang Guan 已提交
64
#define safeInt64Add(a, b)  (((a >= 0) && (b <= INT64_MAX - a)) || ((a < 0) && (b >= INT64_MIN - a)))
H
Hongze Cheng 已提交
65 66
#define ZIGZAG_ENCODE(T, v) ((u##T)((v) >> (sizeof(T) * 8 - 1))) ^ (((u##T)(v)) << 1)  // zigzag encode
#define ZIGZAG_DECODE(T, v) ((v) >> 1) ^ -((T)((v)&1))                                 // zigzag decode
H
hzcheng 已提交
67

T
tickduan 已提交
68
#ifdef TD_TSZ
S
Shengliang Guan 已提交
69
bool lossyFloat = false;
T
tickduan 已提交
70 71 72
bool lossyDouble = false;

// init call
S
Shengliang Guan 已提交
73 74 75
int32_t tsCompressInit() {
  // config
  if (lossyColumns[0] == 0) {
T
tickduan 已提交
76 77 78 79 80
    lossyFloat = false;
    lossyDouble = false;
    return 0;
  }

S
Shengliang Guan 已提交
81
  lossyFloat = strstr(lossyColumns, "float") != NULL;
T
tickduan 已提交
82 83
  lossyDouble = strstr(lossyColumns, "double") != NULL;

S
Shengliang Guan 已提交
84 85
  if (lossyFloat == false && lossyDouble == false) return 0;

T
tickduan 已提交
86
  tdszInit(fPrecision, dPrecision, maxRange, curRange, Compressor);
87 88
  if (lossyFloat) uTrace("lossy compression float  is opened. ");
  if (lossyDouble) uTrace("lossy compression double is opened. ");
T
tickduan 已提交
89 90 91
  return 1;
}
// exit call
S
Shengliang Guan 已提交
92
void tsCompressExit() { tdszExit(); }
T
tickduan 已提交
93

94
#endif
T
tickduan 已提交
95

H
hzcheng 已提交
96 97 98
/*
 * Compress Integer (Simple8B).
 */
S
Shengliang Guan 已提交
99
int32_t tsCompressINTImp(const char *const input, const int32_t nelements, char *const output, const char type) {
H
hzcheng 已提交
100 101
  // Selector value:              0    1   2   3   4   5   6   7   8  9  10  11
  // 12  13  14  15
S
Shengliang Guan 已提交
102 103 104
  char    bit_per_integer[] = {0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 15, 20, 30, 60};
  int32_t selector_to_elems[] = {240, 120, 60, 30, 20, 15, 12, 10, 8, 7, 6, 5, 4, 3, 2, 1};
  char    bit_to_selector[] = {0,  2,  3,  4,  5,  6,  7,  8,  9,  10, 10, 11, 11, 12, 12, 12, 13, 13, 13, 13, 13,
H
Hongze Cheng 已提交
105 106
                               14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
                               15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15};
H
hzcheng 已提交
107 108

  // get the byte limit.
S
Shengliang Guan 已提交
109
  int32_t word_length = 0;
H
hzcheng 已提交
110 111 112 113 114 115 116 117 118 119 120 121 122 123
  switch (type) {
    case TSDB_DATA_TYPE_BIGINT:
      word_length = LONG_BYTES;
      break;
    case TSDB_DATA_TYPE_INT:
      word_length = INT_BYTES;
      break;
    case TSDB_DATA_TYPE_SMALLINT:
      word_length = SHORT_BYTES;
      break;
    case TSDB_DATA_TYPE_TINYINT:
      word_length = CHAR_BYTES;
      break;
    default:
124
      uError("Invalid compress integer type:%d", type);
H
Hongze Cheng 已提交
125
      return -1;
H
hzcheng 已提交
126 127
  }

S
Shengliang Guan 已提交
128 129
  int32_t byte_limit = nelements * word_length + 1;
  int32_t opos = 1;
H
hzcheng 已提交
130 131
  int64_t prev_value = 0;

S
Shengliang Guan 已提交
132
  for (int32_t i = 0; i < nelements;) {
H
hzcheng 已提交
133 134
    char    selector = 0;
    char    bit = 0;
S
Shengliang Guan 已提交
135
    int32_t elems = 0;
H
hzcheng 已提交
136 137
    int64_t prev_value_tmp = prev_value;

S
Shengliang Guan 已提交
138
    for (int32_t j = i; j < nelements; j++) {
H
hzcheng 已提交
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
      // Read data from the input stream and convert it to INT64 type.
      int64_t curr_value = 0;
      switch (type) {
        case TSDB_DATA_TYPE_TINYINT:
          curr_value = (int64_t)(*((int8_t *)input + j));
          break;
        case TSDB_DATA_TYPE_SMALLINT:
          curr_value = (int64_t)(*((int16_t *)input + j));
          break;
        case TSDB_DATA_TYPE_INT:
          curr_value = (int64_t)(*((int32_t *)input + j));
          break;
        case TSDB_DATA_TYPE_BIGINT:
          curr_value = (int64_t)(*((int64_t *)input + j));
          break;
      }
      // Get difference.
Y
yihaoDeng 已提交
156
      if (!safeInt64Add(curr_value, -prev_value_tmp)) goto _copy_and_exit;
H
hzcheng 已提交
157 158 159

      int64_t diff = curr_value - prev_value_tmp;
      // Zigzag encode the value.
H
Hongze Cheng 已提交
160
      uint64_t zigzag_value = ZIGZAG_ENCODE(int64_t, diff);
H
hzcheng 已提交
161 162 163

      if (zigzag_value >= SIMPLE8B_MAX_INT64) goto _copy_and_exit;

S
TD-1037  
Shengliang Guan 已提交
164
      int64_t tmp_bit;
H
hzcheng 已提交
165 166 167 168
      if (zigzag_value == 0) {
        // Take care here, __builtin_clzl give wrong anser for value 0;
        tmp_bit = 0;
      } else {
169
        tmp_bit = (LONG_BYTES * BITS_PER_BYTE) - BUILDIN_CLZL(zigzag_value);
H
hzcheng 已提交
170 171
      }

S
Shengliang Guan 已提交
172 173
      if (elems + 1 <= selector_to_elems[(int32_t)selector] &&
          elems + 1 <= selector_to_elems[(int32_t)(bit_to_selector[(int32_t)tmp_bit])]) {
H
hzcheng 已提交
174
        // If can hold another one.
S
Shengliang Guan 已提交
175
        selector = selector > bit_to_selector[(int32_t)tmp_bit] ? selector : bit_to_selector[(int32_t)tmp_bit];
H
hzcheng 已提交
176
        elems++;
S
Shengliang Guan 已提交
177
        bit = bit_per_integer[(int32_t)selector];
H
hzcheng 已提交
178 179
      } else {
        // if cannot hold another one.
S
Shengliang Guan 已提交
180 181 182
        while (elems < selector_to_elems[(int32_t)selector]) selector++;
        elems = selector_to_elems[(int32_t)selector];
        bit = bit_per_integer[(int32_t)selector];
H
hzcheng 已提交
183 184 185 186 187 188 189
        break;
      }
      prev_value_tmp = curr_value;
    }

    uint64_t buffer = 0;
    buffer |= (uint64_t)selector;
S
Shengliang Guan 已提交
190
    for (int32_t k = 0; k < elems; k++) {
H
hzcheng 已提交
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
      int64_t curr_value = 0; /* get current values */
      switch (type) {
        case TSDB_DATA_TYPE_TINYINT:
          curr_value = (int64_t)(*((int8_t *)input + i));
          break;
        case TSDB_DATA_TYPE_SMALLINT:
          curr_value = (int64_t)(*((int16_t *)input + i));
          break;
        case TSDB_DATA_TYPE_INT:
          curr_value = (int64_t)(*((int32_t *)input + i));
          break;
        case TSDB_DATA_TYPE_BIGINT:
          curr_value = (int64_t)(*((int64_t *)input + i));
          break;
      }
      int64_t  diff = curr_value - prev_value;
H
Hongze Cheng 已提交
207
      uint64_t zigzag_value = ZIGZAG_ENCODE(int64_t, diff);
H
hzcheng 已提交
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
      buffer |= ((zigzag_value & INT64MASK(bit)) << (bit * k + 4));
      i++;
      prev_value = curr_value;
    }

    // Output the encoded value to the output.
    if (opos + sizeof(buffer) <= byte_limit) {
      memcpy(output + opos, &buffer, sizeof(buffer));
      opos += sizeof(buffer);
    } else {
    _copy_and_exit:
      output[0] = 1;
      memcpy(output + 1, input, byte_limit - 1);
      return byte_limit;
    }
  }

  // set the indicator.
  output[0] = 0;
  return opos;
}

S
Shengliang Guan 已提交
230 231
int32_t tsDecompressINTImp(const char *const input, const int32_t nelements, char *const output, const char type) {
  int32_t word_length = 0;
H
hzcheng 已提交
232 233 234 235 236 237 238 239 240 241 242 243 244 245
  switch (type) {
    case TSDB_DATA_TYPE_BIGINT:
      word_length = LONG_BYTES;
      break;
    case TSDB_DATA_TYPE_INT:
      word_length = INT_BYTES;
      break;
    case TSDB_DATA_TYPE_SMALLINT:
      word_length = SHORT_BYTES;
      break;
    case TSDB_DATA_TYPE_TINYINT:
      word_length = CHAR_BYTES;
      break;
    default:
246
      uError("Invalid decompress integer type:%d", type);
H
Hongze Cheng 已提交
247
      return -1;
H
hzcheng 已提交
248 249 250 251 252 253 254 255 256 257
  }

  // If not compressed.
  if (input[0] == 1) {
    memcpy(output, input + 1, nelements * word_length);
    return nelements * word_length;
  }

  // Selector value:              0    1   2   3   4   5   6   7   8  9  10  11
  // 12  13  14  15
S
Shengliang Guan 已提交
258 259
  char    bit_per_integer[] = {0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 15, 20, 30, 60};
  int32_t selector_to_elems[] = {240, 120, 60, 30, 20, 15, 12, 10, 8, 7, 6, 5, 4, 3, 2, 1};
H
hzcheng 已提交
260 261

  const char *ip = input + 1;
S
Shengliang Guan 已提交
262 263
  int32_t     count = 0;
  int32_t     _pos = 0;
H
hzcheng 已提交
264 265 266 267 268 269 270 271
  int64_t     prev_value = 0;

  while (1) {
    if (count == nelements) break;

    uint64_t w = 0;
    memcpy(&w, ip, LONG_BYTES);

S
Shengliang Guan 已提交
272 273 274
    char    selector = (char)(w & INT64MASK(4));       // selector = 4
    char    bit = bit_per_integer[(int32_t)selector];  // bit = 3
    int32_t elems = selector_to_elems[(int32_t)selector];
H
hzcheng 已提交
275

S
Shengliang Guan 已提交
276
    for (int32_t i = 0; i < elems; i++) {
H
hzcheng 已提交
277 278 279 280 281 282 283
      uint64_t zigzag_value;

      if (selector == 0 || selector == 1) {
        zigzag_value = 0;
      } else {
        zigzag_value = ((w >> (4 + bit * i)) & INT64MASK(bit));
      }
H
Hongze Cheng 已提交
284
      int64_t diff = ZIGZAG_DECODE(int64_t, zigzag_value);
H
hzcheng 已提交
285 286 287 288 289
      int64_t curr_value = diff + prev_value;
      prev_value = curr_value;

      switch (type) {
        case TSDB_DATA_TYPE_BIGINT:
H
Hongze Cheng 已提交
290
          *((int64_t *)output + _pos) = (int64_t)curr_value;
H
hzcheng 已提交
291 292 293
          _pos++;
          break;
        case TSDB_DATA_TYPE_INT:
H
Hongze Cheng 已提交
294
          *((int32_t *)output + _pos) = (int32_t)curr_value;
H
hzcheng 已提交
295 296 297
          _pos++;
          break;
        case TSDB_DATA_TYPE_SMALLINT:
H
Hongze Cheng 已提交
298
          *((int16_t *)output + _pos) = (int16_t)curr_value;
H
hzcheng 已提交
299 300 301
          _pos++;
          break;
        case TSDB_DATA_TYPE_TINYINT:
H
Hongze Cheng 已提交
302
          *((int8_t *)output + _pos) = (int8_t)curr_value;
H
hzcheng 已提交
303 304 305 306
          _pos++;
          break;
        default:
          perror("Wrong integer types.\n");
H
Hongze Cheng 已提交
307
          return -1;
H
hzcheng 已提交
308 309 310 311 312 313 314 315 316 317 318 319 320
      }
      count++;
      if (count == nelements) break;
    }
    ip += LONG_BYTES;
  }

  return nelements * word_length;
}

/* ----------------------------------------------Bool Compression
 * ---------------------------------------------- */
// TODO: You can also implement it using RLE method.
S
Shengliang Guan 已提交
321 322 323
int32_t tsCompressBoolImp(const char *const input, const int32_t nelements, char *const output) {
  int32_t pos = -1;
  int32_t ele_per_byte = BITS_PER_BYTE / 2;
H
hzcheng 已提交
324

S
Shengliang Guan 已提交
325
  for (int32_t i = 0; i < nelements; i++) {
H
hzcheng 已提交
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
    if (i % ele_per_byte == 0) {
      pos++;
      output[pos] = 0;
    }

    uint8_t t = 0;
    if (input[i] == 1) {
      t = (((uint8_t)1) << (2 * (i % ele_per_byte)));
      output[pos] |= t;
    } else if (input[i] == 0) {
      t = ((uint8_t)1 << (2 * (i % ele_per_byte))) - 1;
      /* t = (~((( uint8_t)1) << (7-i%BITS_PER_BYTE))); */
      output[pos] &= t;
    } else if (input[i] == TSDB_DATA_BOOL_NULL) {
      t = ((uint8_t)2 << (2 * (i % ele_per_byte)));
      /* t = (~((( uint8_t)1) << (7-i%BITS_PER_BYTE))); */
      output[pos] |= t;
    } else {
344
      uError("Invalid compress bool value:%d", output[pos]);
H
Hongze Cheng 已提交
345
      return -1;
H
hzcheng 已提交
346 347 348 349 350 351
    }
  }

  return pos + 1;
}

S
Shengliang Guan 已提交
352 353 354
int32_t tsDecompressBoolImp(const char *const input, const int32_t nelements, char *const output) {
  int32_t ipos = -1, opos = 0;
  int32_t ele_per_byte = BITS_PER_BYTE / 2;
H
hzcheng 已提交
355

S
Shengliang Guan 已提交
356
  for (int32_t i = 0; i < nelements; i++) {
H
hzcheng 已提交
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
    if (i % ele_per_byte == 0) {
      ipos++;
    }

    uint8_t ele = (input[ipos] >> (2 * (i % ele_per_byte))) & INT8MASK(2);
    if (ele == 1) {
      output[opos++] = 1;
    } else if (ele == 2) {
      output[opos++] = TSDB_DATA_BOOL_NULL;
    } else {
      output[opos++] = 0;
    }
  }

  return nelements;
}

/* Run Length Encoding(RLE) Method */
S
Shengliang Guan 已提交
375 376
int32_t tsCompressBoolRLEImp(const char *const input, const int32_t nelements, char *const output) {
  int32_t _pos = 0;
H
hzcheng 已提交
377

S
Shengliang Guan 已提交
378
  for (int32_t i = 0; i < nelements;) {
H
hzcheng 已提交
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
    unsigned char counter = 1;
    char          num = input[i];

    for (++i; i < nelements; i++) {
      if (input[i] == num) {
        counter++;
        if (counter == INT8MASK(7)) {
          i++;
          break;
        }
      } else {
        break;
      }
    }

    // Encode the data.
    if (num == 1) {
      output[_pos++] = INT8MASK(1) | (counter << 1);
    } else if (num == 0) {
      output[_pos++] = (counter << 1) | INT8MASK(0);
    } else {
400
      uError("Invalid compress bool value:%d", output[_pos]);
H
Hongze Cheng 已提交
401
      return -1;
H
hzcheng 已提交
402 403 404 405 406 407
    }
  }

  return _pos;
}

S
Shengliang Guan 已提交
408 409
int32_t tsDecompressBoolRLEImp(const char *const input, const int32_t nelements, char *const output) {
  int32_t ipos = 0, opos = 0;
H
hzcheng 已提交
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
  while (1) {
    char     encode = input[ipos++];
    unsigned counter = (encode >> 1) & INT8MASK(7);
    char     value = encode & INT8MASK(1);

    memset(output + opos, value, counter);
    opos += counter;
    if (opos >= nelements) {
      return nelements;
    }
  }
}

/* ----------------------------------------------String Compression
 * ---------------------------------------------- */
// Note: the size of the output must be larger than input_size + 1 and
// LZ4_compressBound(size) + 1;
// >= max(input_size, LZ4_compressBound(input_size)) + 1;
S
Shengliang Guan 已提交
428
int32_t tsCompressStringImp(const char *const input, int32_t inputSize, char *const output, int32_t outputSize) {
H
hzcheng 已提交
429
  // Try to compress using LZ4 algorithm.
S
Shengliang Guan 已提交
430
  const int32_t compressed_data_size = LZ4_compress_default(input, output + 1, inputSize, outputSize - 1);
H
hzcheng 已提交
431 432 433 434 435 436 437 438 439 440 441 442 443

  // If cannot compress or after compression, data becomes larger.
  if (compressed_data_size <= 0 || compressed_data_size > inputSize) {
    /* First byte is for indicator */
    output[0] = 0;
    memcpy(output + 1, input, inputSize);
    return inputSize + 1;
  }

  output[0] = 1;
  return compressed_data_size + 1;
}

S
Shengliang Guan 已提交
444
int32_t tsDecompressStringImp(const char *const input, int32_t compressedSize, char *const output, int32_t outputSize) {
H
hzcheng 已提交
445
  // compressedSize is the size of data after compression.
S
Shengliang Guan 已提交
446

H
hzcheng 已提交
447 448
  if (input[0] == 1) {
    /* It is compressed by LZ4 algorithm */
S
Shengliang Guan 已提交
449
    const int32_t decompressed_size = LZ4_decompress_safe(input + 1, output, compressedSize - 1, outputSize);
H
hzcheng 已提交
450
    if (decompressed_size < 0) {
451
      uError("Failed to decompress string with LZ4 algorithm, decompressed size:%d", decompressed_size);
H
Hongze Cheng 已提交
452
      return -1;
H
hzcheng 已提交
453 454 455 456 457 458 459 460
    }

    return decompressed_size;
  } else if (input[0] == 0) {
    /* It is not compressed by LZ4 algorithm */
    memcpy(output, input + 1, compressedSize - 1);
    return compressedSize - 1;
  } else {
461
    uError("Invalid decompress string indicator:%d", input[0]);
H
Hongze Cheng 已提交
462
    return -1;
H
hzcheng 已提交
463 464 465 466 467 468
  }
}

/* --------------------------------------------Timestamp Compression
 * ---------------------------------------------- */
// TODO: Take care here, we assumes little endian encoding.
S
Shengliang Guan 已提交
469 470
int32_t tsCompressTimestampImp(const char *const input, const int32_t nelements, char *const output) {
  int32_t _pos = 1;
H
hzcheng 已提交
471 472 473 474 475 476
  assert(nelements >= 0);

  if (nelements == 0) return 0;

  int64_t *istream = (int64_t *)input;

S
Shengliang Guan 已提交
477 478 479 480
  int64_t prev_value = istream[0];
  if (prev_value >= 0x8000000000000000) {
    uWarn("compression timestamp is over signed long long range. ts = 0x%" PRIx64 " \n", prev_value);
    goto _exit_over;
T
tickduan 已提交
481
  }
H
hzcheng 已提交
482 483 484 485
  int64_t  prev_delta = -prev_value;
  uint8_t  flags = 0, flag1 = 0, flag2 = 0;
  uint64_t dd1 = 0, dd2 = 0;

S
Shengliang Guan 已提交
486
  for (int32_t i = 0; i < nelements; i++) {
H
hzcheng 已提交
487 488 489 490 491 492
    int64_t curr_value = istream[i];
    if (!safeInt64Add(curr_value, -prev_value)) goto _exit_over;
    int64_t curr_delta = curr_value - prev_value;
    if (!safeInt64Add(curr_delta, -prev_delta)) goto _exit_over;
    int64_t delta_of_delta = curr_delta - prev_delta;
    // zigzag encode the value.
H
Hongze Cheng 已提交
493
    uint64_t zigzag_value = ZIGZAG_ENCODE(int64_t, delta_of_delta);
H
hzcheng 已提交
494 495 496 497 498 499
    if (i % 2 == 0) {
      flags = 0;
      dd1 = zigzag_value;
      if (dd1 == 0) {
        flag1 = 0;
      } else {
H
Hongze Cheng 已提交
500
        flag1 = (uint8_t)(LONG_BYTES - BUILDIN_CLZL(dd1) / BITS_PER_BYTE);
H
hzcheng 已提交
501 502 503 504 505 506
      }
    } else {
      dd2 = zigzag_value;
      if (dd2 == 0) {
        flag2 = 0;
      } else {
H
Hongze Cheng 已提交
507
        flag2 = (uint8_t)(LONG_BYTES - BUILDIN_CLZL(dd2) / BITS_PER_BYTE);
H
hzcheng 已提交
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
      }
      flags = flag1 | (flag2 << 4);
      // Encode the flag.
      if ((_pos + CHAR_BYTES - 1) >= nelements * LONG_BYTES) goto _exit_over;
      memcpy(output + _pos, &flags, CHAR_BYTES);
      _pos += CHAR_BYTES;
      /* Here, we assume it is little endian encoding method. */
      // Encode dd1
      if (is_bigendian()) {
        if ((_pos + flag1 - 1) >= nelements * LONG_BYTES) goto _exit_over;
        memcpy(output + _pos, (char *)(&dd1) + LONG_BYTES - flag1, flag1);
      } else {
        if ((_pos + flag1 - 1) >= nelements * LONG_BYTES) goto _exit_over;
        memcpy(output + _pos, (char *)(&dd1), flag1);
      }
      _pos += flag1;
      // Encode dd2;
      if (is_bigendian()) {
        if ((_pos + flag2 - 1) >= nelements * LONG_BYTES) goto _exit_over;
        memcpy(output + _pos, (char *)(&dd2) + LONG_BYTES - flag2, flag2);
      } else {
        if ((_pos + flag2 - 1) >= nelements * LONG_BYTES) goto _exit_over;
        memcpy(output + _pos, (char *)(&dd2), flag2);
      }
      _pos += flag2;
    }
    prev_value = curr_value;
    prev_delta = curr_delta;
  }

  if (nelements % 2 == 1) {
    flag2 = 0;
    flags = flag1 | (flag2 << 4);
    // Encode the flag.
    if ((_pos + CHAR_BYTES - 1) >= nelements * LONG_BYTES) goto _exit_over;
    memcpy(output + _pos, &flags, CHAR_BYTES);
    _pos += CHAR_BYTES;
    // Encode dd1;
    if (is_bigendian()) {
      if ((_pos + flag1 - 1) >= nelements * LONG_BYTES) goto _exit_over;
      memcpy(output + _pos, (char *)(&dd1) + LONG_BYTES - flag1, flag1);
    } else {
      if ((_pos + flag1 - 1) >= nelements * LONG_BYTES) goto _exit_over;
      memcpy(output + _pos, (char *)(&dd1), flag1);
    }
    _pos += flag1;
  }

  output[0] = 1;  // Means the string is compressed
  return _pos;

_exit_over:
  output[0] = 0;  // Means the string is not compressed
  memcpy(output + 1, input, nelements * LONG_BYTES);
  return nelements * LONG_BYTES + 1;
}

S
Shengliang Guan 已提交
565
int32_t tsDecompressTimestampImp(const char *const input, const int32_t nelements, char *const output) {
H
hzcheng 已提交
566 567 568 569 570 571 572 573 574
  assert(nelements >= 0);
  if (nelements == 0) return 0;

  if (input[0] == 0) {
    memcpy(output, input + 1, nelements * LONG_BYTES);
    return nelements * LONG_BYTES;
  } else if (input[0] == 1) {  // Decompress
    int64_t *ostream = (int64_t *)output;

S
Shengliang Guan 已提交
575
    int32_t ipos = 1, opos = 0;
H
hzcheng 已提交
576 577 578 579 580 581 582 583 584 585 586 587 588 589
    int8_t  nbytes = 0;
    int64_t prev_value = 0;
    int64_t prev_delta = 0;
    int64_t delta_of_delta = 0;

    while (1) {
      uint8_t flags = input[ipos++];
      // Decode dd1
      uint64_t dd1 = 0;
      nbytes = flags & INT8MASK(4);
      if (nbytes == 0) {
        delta_of_delta = 0;
      } else {
        if (is_bigendian()) {
H
Hui Li 已提交
590
          memcpy(((char *)(&dd1)) + LONG_BYTES - nbytes, input + ipos, nbytes);
H
hzcheng 已提交
591 592 593
        } else {
          memcpy(&dd1, input + ipos, nbytes);
        }
H
Hongze Cheng 已提交
594
        delta_of_delta = ZIGZAG_DECODE(int64_t, dd1);
H
hzcheng 已提交
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
      }
      ipos += nbytes;
      if (opos == 0) {
        prev_value = delta_of_delta;
        prev_delta = 0;
        ostream[opos++] = delta_of_delta;
      } else {
        prev_delta = delta_of_delta + prev_delta;
        prev_value = prev_value + prev_delta;
        ostream[opos++] = prev_value;
      }
      if (opos == nelements) return nelements * LONG_BYTES;

      // Decode dd2
      uint64_t dd2 = 0;
      nbytes = (flags >> 4) & INT8MASK(4);
      if (nbytes == 0) {
        delta_of_delta = 0;
      } else {
        if (is_bigendian()) {
H
Hui Li 已提交
615
          memcpy(((char *)(&dd2)) + LONG_BYTES - nbytes, input + ipos, nbytes);
H
hzcheng 已提交
616 617 618 619
        } else {
          memcpy(&dd2, input + ipos, nbytes);
        }
        // zigzag_decoding
H
Hongze Cheng 已提交
620
        delta_of_delta = ZIGZAG_DECODE(int64_t, dd2);
H
hzcheng 已提交
621 622 623 624 625 626 627 628 629 630
      }
      ipos += nbytes;
      prev_delta = delta_of_delta + prev_delta;
      prev_value = prev_value + prev_delta;
      ostream[opos++] = prev_value;
      if (opos == nelements) return nelements * LONG_BYTES;
    }

  } else {
    assert(0);
S
TD-1057  
Shengliang Guan 已提交
631
    return -1;
H
hzcheng 已提交
632 633 634 635
  }
}
/* --------------------------------------------Double Compression
 * ---------------------------------------------- */
S
Shengliang Guan 已提交
636
void encodeDoubleValue(uint64_t diff, uint8_t flag, char *const output, int32_t *const pos) {
H
hzcheng 已提交
637
  uint8_t nbytes = (flag & INT8MASK(3)) + 1;
S
Shengliang Guan 已提交
638
  int32_t nshift = (LONG_BYTES * BITS_PER_BYTE - nbytes * BITS_PER_BYTE) * (flag >> 3);
H
hzcheng 已提交
639 640 641 642 643 644 645 646 647
  diff >>= nshift;

  while (nbytes) {
    output[(*pos)++] = (int8_t)(diff & INT64MASK(8));
    diff >>= BITS_PER_BYTE;
    nbytes--;
  }
}

S
Shengliang Guan 已提交
648 649 650
int32_t tsCompressDoubleImp(const char *const input, const int32_t nelements, char *const output) {
  int32_t byte_limit = nelements * DOUBLE_BYTES + 1;
  int32_t opos = 1;
H
hzcheng 已提交
651 652 653 654 655 656 657 658

  uint64_t prev_value = 0;
  uint64_t prev_diff = 0;
  uint8_t  prev_flag = 0;

  double *istream = (double *)input;

  // Main loop
S
Shengliang Guan 已提交
659
  for (int32_t i = 0; i < nelements; i++) {
H
hzcheng 已提交
660 661 662 663 664 665 666 667 668 669 670
    union {
      double   real;
      uint64_t bits;
    } curr;

    curr.real = istream[i];

    // Here we assume the next value is the same as previous one.
    uint64_t predicted = prev_value;
    uint64_t diff = curr.bits ^ predicted;

S
Shengliang Guan 已提交
671 672
    int32_t leading_zeros = LONG_BYTES * BITS_PER_BYTE;
    int32_t trailing_zeros = leading_zeros;
H
hzcheng 已提交
673 674

    if (diff) {
675 676
      trailing_zeros = BUILDIN_CTZL(diff);
      leading_zeros = BUILDIN_CLZL(diff);
H
hzcheng 已提交
677 678 679 680 681 682
    }

    uint8_t nbytes = 0;
    uint8_t flag;

    if (trailing_zeros > leading_zeros) {
H
Hongze Cheng 已提交
683
      nbytes = (uint8_t)(LONG_BYTES - trailing_zeros / BITS_PER_BYTE);
H
hzcheng 已提交
684 685 686 687

      if (nbytes > 0) nbytes--;
      flag = ((uint8_t)1 << 3) | nbytes;
    } else {
H
Hongze Cheng 已提交
688
      nbytes = (uint8_t)(LONG_BYTES - leading_zeros / BITS_PER_BYTE);
H
hzcheng 已提交
689 690 691 692 693 694 695 696
      if (nbytes > 0) nbytes--;
      flag = nbytes;
    }

    if (i % 2 == 0) {
      prev_diff = diff;
      prev_flag = flag;
    } else {
S
Shengliang Guan 已提交
697 698
      int32_t nbyte1 = (prev_flag & INT8MASK(3)) + 1;
      int32_t nbyte2 = (flag & INT8MASK(3)) + 1;
H
hzcheng 已提交
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
      if (opos + 1 + nbyte1 + nbyte2 <= byte_limit) {
        uint8_t flags = prev_flag | (flag << 4);
        output[opos++] = flags;
        encodeDoubleValue(prev_diff, prev_flag, output, &opos);
        encodeDoubleValue(diff, flag, output, &opos);
      } else {
        output[0] = 1;
        memcpy(output + 1, input, byte_limit - 1);
        return byte_limit;
      }
    }
    prev_value = curr.bits;
  }

  if (nelements % 2) {
S
Shengliang Guan 已提交
714 715
    int32_t nbyte1 = (prev_flag & INT8MASK(3)) + 1;
    int32_t nbyte2 = 1;
H
hzcheng 已提交
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
    if (opos + 1 + nbyte1 + nbyte2 <= byte_limit) {
      uint8_t flags = prev_flag;
      output[opos++] = flags;
      encodeDoubleValue(prev_diff, prev_flag, output, &opos);
      encodeDoubleValue(0ul, 0, output, &opos);
    } else {
      output[0] = 1;
      memcpy(output + 1, input, byte_limit - 1);
      return byte_limit;
    }
  }

  output[0] = 0;
  return opos;
}

S
Shengliang Guan 已提交
732
uint64_t decodeDoubleValue(const char *const input, int32_t *const ipos, uint8_t flag) {
H
hzcheng 已提交
733
  uint64_t diff = 0ul;
S
Shengliang Guan 已提交
734 735
  int32_t  nbytes = (flag & INT8MASK(3)) + 1;
  for (int32_t i = 0; i < nbytes; i++) {
H
hzcheng 已提交
736 737
    diff = diff | ((INT64MASK(8) & input[(*ipos)++]) << BITS_PER_BYTE * i);
  }
S
Shengliang Guan 已提交
738
  int32_t shift_width = (LONG_BYTES * BITS_PER_BYTE - nbytes * BITS_PER_BYTE) * (flag >> 3);
H
hzcheng 已提交
739 740 741 742 743
  diff <<= shift_width;

  return diff;
}

S
Shengliang Guan 已提交
744
int32_t tsDecompressDoubleImp(const char *const input, const int32_t nelements, char *const output) {
H
hzcheng 已提交
745 746 747 748 749 750 751 752 753
  // output stream
  double *ostream = (double *)output;

  if (input[0] == 1) {
    memcpy(output, input + 1, nelements * DOUBLE_BYTES);
    return nelements * DOUBLE_BYTES;
  }

  uint8_t  flags = 0;
S
Shengliang Guan 已提交
754 755
  int32_t  ipos = 1;
  int32_t  opos = 0;
H
hzcheng 已提交
756 757
  uint64_t prev_value = 0;

S
Shengliang Guan 已提交
758
  for (int32_t i = 0; i < nelements; i++) {
H
hzcheng 已提交
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
    if (i % 2 == 0) {
      flags = input[ipos++];
    }

    uint8_t flag = flags & INT8MASK(4);
    flags >>= 4;

    uint64_t diff = decodeDoubleValue(input, &ipos, flag);
    union {
      uint64_t bits;
      double   real;
    } curr;

    uint64_t predicted = prev_value;
    curr.bits = predicted ^ diff;
    prev_value = curr.bits;

    ostream[opos++] = curr.real;
  }

  return nelements * DOUBLE_BYTES;
}

/* --------------------------------------------Float Compression
 * ---------------------------------------------- */
S
Shengliang Guan 已提交
784
void encodeFloatValue(uint32_t diff, uint8_t flag, char *const output, int32_t *const pos) {
H
hzcheng 已提交
785
  uint8_t nbytes = (flag & INT8MASK(3)) + 1;
S
Shengliang Guan 已提交
786
  int32_t nshift = (FLOAT_BYTES * BITS_PER_BYTE - nbytes * BITS_PER_BYTE) * (flag >> 3);
H
hzcheng 已提交
787 788 789 790 791 792 793 794 795
  diff >>= nshift;

  while (nbytes) {
    output[(*pos)++] = (int8_t)(diff & INT32MASK(8));
    diff >>= BITS_PER_BYTE;
    nbytes--;
  }
}

S
Shengliang Guan 已提交
796 797 798 799
int32_t tsCompressFloatImp(const char *const input, const int32_t nelements, char *const output) {
  float  *istream = (float *)input;
  int32_t byte_limit = nelements * FLOAT_BYTES + 1;
  int32_t opos = 1;
H
hzcheng 已提交
800 801 802 803 804 805

  uint32_t prev_value = 0;
  uint32_t prev_diff = 0;
  uint8_t  prev_flag = 0;

  // Main loop
S
Shengliang Guan 已提交
806
  for (int32_t i = 0; i < nelements; i++) {
H
hzcheng 已提交
807 808 809 810 811 812 813 814 815 816 817
    union {
      float    real;
      uint32_t bits;
    } curr;

    curr.real = istream[i];

    // Here we assume the next value is the same as previous one.
    uint32_t predicted = prev_value;
    uint32_t diff = curr.bits ^ predicted;

S
Shengliang Guan 已提交
818 819
    int32_t leading_zeros = FLOAT_BYTES * BITS_PER_BYTE;
    int32_t trailing_zeros = leading_zeros;
H
hzcheng 已提交
820 821

    if (diff) {
822 823
      trailing_zeros = BUILDIN_CTZ(diff);
      leading_zeros = BUILDIN_CLZ(diff);
H
hzcheng 已提交
824 825 826 827 828 829
    }

    uint8_t nbytes = 0;
    uint8_t flag;

    if (trailing_zeros > leading_zeros) {
H
Hongze Cheng 已提交
830
      nbytes = (uint8_t)(FLOAT_BYTES - trailing_zeros / BITS_PER_BYTE);
H
hzcheng 已提交
831 832 833 834

      if (nbytes > 0) nbytes--;
      flag = ((uint8_t)1 << 3) | nbytes;
    } else {
H
Hongze Cheng 已提交
835
      nbytes = (uint8_t)(FLOAT_BYTES - leading_zeros / BITS_PER_BYTE);
H
hzcheng 已提交
836 837 838 839 840 841 842 843
      if (nbytes > 0) nbytes--;
      flag = nbytes;
    }

    if (i % 2 == 0) {
      prev_diff = diff;
      prev_flag = flag;
    } else {
S
Shengliang Guan 已提交
844 845
      int32_t nbyte1 = (prev_flag & INT8MASK(3)) + 1;
      int32_t nbyte2 = (flag & INT8MASK(3)) + 1;
H
hzcheng 已提交
846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
      if (opos + 1 + nbyte1 + nbyte2 <= byte_limit) {
        uint8_t flags = prev_flag | (flag << 4);
        output[opos++] = flags;
        encodeFloatValue(prev_diff, prev_flag, output, &opos);
        encodeFloatValue(diff, flag, output, &opos);
      } else {
        output[0] = 1;
        memcpy(output + 1, input, byte_limit - 1);
        return byte_limit;
      }
    }
    prev_value = curr.bits;
  }

  if (nelements % 2) {
S
Shengliang Guan 已提交
861 862
    int32_t nbyte1 = (prev_flag & INT8MASK(3)) + 1;
    int32_t nbyte2 = 1;
H
hzcheng 已提交
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
    if (opos + 1 + nbyte1 + nbyte2 <= byte_limit) {
      uint8_t flags = prev_flag;
      output[opos++] = flags;
      encodeFloatValue(prev_diff, prev_flag, output, &opos);
      encodeFloatValue(0, 0, output, &opos);
    } else {
      output[0] = 1;
      memcpy(output + 1, input, byte_limit - 1);
      return byte_limit;
    }
  }

  output[0] = 0;
  return opos;
}

S
Shengliang Guan 已提交
879
uint32_t decodeFloatValue(const char *const input, int32_t *const ipos, uint8_t flag) {
H
hzcheng 已提交
880
  uint32_t diff = 0ul;
S
Shengliang Guan 已提交
881 882
  int32_t  nbytes = (flag & INT8MASK(3)) + 1;
  for (int32_t i = 0; i < nbytes; i++) {
H
hzcheng 已提交
883 884
    diff = diff | ((INT32MASK(8) & input[(*ipos)++]) << BITS_PER_BYTE * i);
  }
S
Shengliang Guan 已提交
885
  int32_t shift_width = (FLOAT_BYTES * BITS_PER_BYTE - nbytes * BITS_PER_BYTE) * (flag >> 3);
H
hzcheng 已提交
886 887 888 889 890
  diff <<= shift_width;

  return diff;
}

S
Shengliang Guan 已提交
891
int32_t tsDecompressFloatImp(const char *const input, const int32_t nelements, char *const output) {
H
hzcheng 已提交
892 893 894 895 896 897 898 899
  float *ostream = (float *)output;

  if (input[0] == 1) {
    memcpy(output, input + 1, nelements * FLOAT_BYTES);
    return nelements * FLOAT_BYTES;
  }

  uint8_t  flags = 0;
S
Shengliang Guan 已提交
900 901
  int32_t  ipos = 1;
  int32_t  opos = 0;
H
hzcheng 已提交
902 903
  uint32_t prev_value = 0;

S
Shengliang Guan 已提交
904
  for (int32_t i = 0; i < nelements; i++) {
H
hzcheng 已提交
905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
    if (i % 2 == 0) {
      flags = input[ipos++];
    }

    uint8_t flag = flags & INT8MASK(4);
    flags >>= 4;

    uint32_t diff = decodeFloatValue(input, &ipos, flag);
    union {
      uint32_t bits;
      float    real;
    } curr;

    uint32_t predicted = prev_value;
    curr.bits = predicted ^ diff;
    prev_value = curr.bits;

    ostream[opos++] = curr.real;
  }

  return nelements * FLOAT_BYTES;
}
T
tickduan 已提交
927

S
Shengliang Guan 已提交
928
#ifdef TD_TSZ
T
tickduan 已提交
929 930 931
//
//   ----------  float double lossy  -----------
//
S
Shengliang Guan 已提交
932 933 934
int32_t tsCompressFloatLossyImp(const char *input, const int32_t nelements, char *const output) {
  // compress with sz
  int32_t       compressedSize = tdszCompress(SZ_FLOAT, input, nelements, output + 1);
T
tickduan 已提交
935
  unsigned char algo = ALGO_SZ_LOSSY << 1;
S
Shengliang Guan 已提交
936
  if (compressedSize == 0 || compressedSize >= nelements * sizeof(float)) {
T
tickduan 已提交
937 938 939 940 941 942 943 944 945 946 947
    // compressed error or large than original
    output[0] = MODE_NOCOMPRESS | algo;
    memcpy(output + 1, input, nelements * sizeof(float));
    compressedSize = 1 + nelements * sizeof(float);
  } else {
    // compressed successfully
    output[0] = MODE_COMPRESS | algo;
    compressedSize += 1;
  }

  return compressedSize;
T
tickduan 已提交
948 949
}

S
Shengliang Guan 已提交
950 951 952 953
int32_t tsDecompressFloatLossyImp(const char *input, int32_t compressedSize, const int32_t nelements,
                                  char *const output) {
  int32_t decompressedSize = 0;
  if (HEAD_MODE(input[0]) == MODE_NOCOMPRESS) {
T
tickduan 已提交
954 955 956 957 958
    // orginal so memcpy directly
    decompressedSize = nelements * sizeof(float);
    memcpy(output, input + 1, decompressedSize);

    return decompressedSize;
S
Shengliang Guan 已提交
959
  }
T
tickduan 已提交
960 961 962

  // decompressed with sz
  return tdszDecompress(SZ_FLOAT, input + 1, compressedSize - 1, nelements, output);
T
tickduan 已提交
963 964
}

S
Shengliang Guan 已提交
965 966 967
int32_t tsCompressDoubleLossyImp(const char *input, const int32_t nelements, char *const output) {
  // compress with sz
  int32_t       compressedSize = tdszCompress(SZ_DOUBLE, input, nelements, output + 1);
T
tickduan 已提交
968
  unsigned char algo = ALGO_SZ_LOSSY << 1;
S
Shengliang Guan 已提交
969
  if (compressedSize == 0 || compressedSize >= nelements * sizeof(double)) {
T
tickduan 已提交
970 971 972 973 974 975 976 977 978 979
    // compressed error or large than original
    output[0] = MODE_NOCOMPRESS | algo;
    memcpy(output + 1, input, nelements * sizeof(double));
    compressedSize = 1 + nelements * sizeof(double);
  } else {
    // compressed successfully
    output[0] = MODE_COMPRESS | algo;
    compressedSize += 1;
  }

S
Shengliang Guan 已提交
980
  return compressedSize;
T
tickduan 已提交
981 982
}

S
Shengliang Guan 已提交
983 984 985 986
int32_t tsDecompressDoubleLossyImp(const char *input, int32_t compressedSize, const int32_t nelements,
                                   char *const output) {
  int32_t decompressedSize = 0;
  if (HEAD_MODE(input[0]) == MODE_NOCOMPRESS) {
T
tickduan 已提交
987 988 989 990 991
    // orginal so memcpy directly
    decompressedSize = nelements * sizeof(double);
    memcpy(output, input + 1, decompressedSize);

    return decompressedSize;
S
Shengliang Guan 已提交
992
  }
T
tickduan 已提交
993 994 995

  // decompressed with sz
  return tdszDecompress(SZ_DOUBLE, input + 1, compressedSize - 1, nelements, output);
996
}
Y
yihaoDeng 已提交
997
#endif
H
Hongze Cheng 已提交
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493

/*************************************************************************
 *                  STREAM COMPRESSION
 *************************************************************************/
#define I64_SAFE_ADD(a, b) (((a) >= 0 && (b) <= INT64_MAX - (b)) || ((a) < 0 && (b) >= INT64_MIN - (a)))

typedef struct {
  int8_t   type;
  int8_t   cmprAlg;
  uint8_t *aBuf[2];
  int64_t  nBuf[2];
  union {
    // Timestamp ----
    struct {
      int8_t   ts_copy;
      int32_t  ts_n;
      int64_t  ts_prev_val;
      int64_t  ts_prev_delta;
      uint8_t *ts_flag_p;
    };
    // Integer ----
    struct {
      int8_t  i_copy;
      int32_t i_n;
      int64_t i_prev;
      int32_t i_selector;
      int32_t i_nele;
    };
    // Float ----
    struct {
      int32_t  f_n;
      uint32_t f_prev;
      uint8_t *f_flag_p;
    };
    // Double ----
    struct {
      int32_t  d_n;
      uint64_t d_prev;
      uint8_t *d_flag_p;
    };
    // Bool ----
    struct {
      int32_t bool_n;
    };
    // Binary ----
    struct {
      int32_t b_n;
    };
  };
} SCompressor;

// Timestamp =====================================================
static int32_t tCompSetCopyMode(SCompressor *pCmprsor) {
  int32_t code = 0;

  if (pCmprsor->ts_n) {
    code = tRealloc(&pCmprsor->aBuf[1], sizeof(int64_t) * (pCmprsor->ts_n + 1));
    if (code) return code;
    pCmprsor->nBuf[1] = 1;

    int64_t  n = 1;
    int64_t  valPrev;
    int64_t  delPrev;
    uint64_t vZigzag;
    while (n < pCmprsor->nBuf[0]) {
      uint8_t n1 = pCmprsor->aBuf[0][0] & 0xf;
      uint8_t n2 = pCmprsor->aBuf[0][0] >> 4;

      n++;

      vZigzag = 0;
      for (uint8_t i = 0; i < n1; i++) {
        vZigzag |= (((uint64_t)pCmprsor->aBuf[0][n]) << (sizeof(int64_t) * i));
        n++;
      }
      int64_t delta_of_delta = ZIGZAG_DECODE(int64_t, vZigzag);
      if (n == 2) {
        delPrev = 0;
        valPrev = delta_of_delta;
      } else {
        delPrev = delta_of_delta + delPrev;
        valPrev = delPrev + valPrev;
      }

      memcpy(pCmprsor->aBuf[1] + pCmprsor->nBuf[1], &valPrev, sizeof(int64_t));
      pCmprsor->nBuf[1] += sizeof(int64_t);

      if (n >= pCmprsor->nBuf[0]) break;

      vZigzag = 0;
      for (uint8_t i = 0; i < n2; i++) {
        vZigzag |= (((uint64_t)pCmprsor->aBuf[0][n]) << (sizeof(int64_t) * i));
        n++;
      }
      delta_of_delta = ZIGZAG_DECODE(int64_t, vZigzag);
      delPrev = delta_of_delta + delPrev;
      valPrev = delPrev + valPrev;
    }

    uint8_t *pBuf = pCmprsor->aBuf[0];
    pCmprsor->aBuf[0] = pCmprsor->aBuf[1];
    pCmprsor->aBuf[1] = pBuf;
    pCmprsor->nBuf[0] = pCmprsor->nBuf[1];
  } else {
    // TODO
  }

  pCmprsor->aBuf[0][0] = 0;
  pCmprsor->ts_copy = 1;

  return code;
}
static int32_t tCompTimestamp(SCompressor *pCmprsor, TSKEY ts) {
  int32_t code = 0;

  if (pCmprsor->ts_n == 0) {
    pCmprsor->ts_prev_val = ts;
    pCmprsor->ts_prev_delta = -ts;
  }

  if (pCmprsor->ts_copy) goto _copy_exit;

  if (!I64_SAFE_ADD(ts, -pCmprsor->ts_prev_val)) {
    code = tCompSetCopyMode(pCmprsor);
    if (code) return code;
    goto _copy_exit;
  }

  int64_t delta = ts - pCmprsor->ts_prev_val;

  if (!I64_SAFE_ADD(delta, -pCmprsor->ts_prev_delta)) {
    code = tCompSetCopyMode(pCmprsor);
    if (code) return code;
    goto _copy_exit;
  }

  int64_t  delta_of_delta = delta - pCmprsor->ts_prev_delta;
  uint64_t zigzag_value = ZIGZAG_ENCODE(int64_t, delta_of_delta);

  pCmprsor->ts_prev_val = ts;
  pCmprsor->ts_prev_delta = delta;

  if (pCmprsor->ts_n & 0x1 == 0) {
    code = tRealloc(&pCmprsor->aBuf[0], pCmprsor->nBuf[0] + 17 /*sizeof(int64_t) * 2 + 1*/);
    if (code) return code;

    pCmprsor->ts_flag_p = &pCmprsor->aBuf[0][pCmprsor->nBuf[0]];
    pCmprsor->nBuf[0]++;
    pCmprsor->ts_flag_p[0] = 0;

    while (zigzag_value) {
      pCmprsor->aBuf[0][pCmprsor->nBuf[0]] = (zigzag_value & 0xff);
      pCmprsor->nBuf[0]++;
      pCmprsor->ts_flag_p[0]++;
    }
  } else {
    while (zigzag_value) {
      pCmprsor->aBuf[0][pCmprsor->nBuf[0]] = (zigzag_value & 0xff);
      pCmprsor->nBuf[0]++;
      pCmprsor->ts_flag_p += (uint8_t)0x10;
    }
  }

  pCmprsor->ts_n++;
  return code;

_copy_exit:
  code = tRealloc(&pCmprsor->aBuf[0], pCmprsor->nBuf[0] + sizeof(int64_t));
  if (code) return code;

  memcpy(pCmprsor->aBuf[0] + pCmprsor->nBuf[0], &ts, sizeof(ts));
  pCmprsor->nBuf[0] += sizeof(ts);

  pCmprsor->ts_n++;
  return code;
}

// Integer =====================================================
#define SIMPLE8B_MAX ((uint64_t)1152921504606846974LL)
static const char    bit_per_integer[] = {0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 15, 20, 30, 60};
static const int32_t selector_to_elems[] = {240, 120, 60, 30, 20, 15, 12, 10, 8, 7, 6, 5, 4, 3, 2, 1};
static const char    bit_to_selector[] = {0,  2,  3,  4,  5,  6,  7,  8,  9,  10, 10, 11, 11, 12, 12, 12,
                                          13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15,
                                          15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
                                          15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15};

static int32_t tCompI64(SCompressor *pCmprsor, int64_t val) {
  int32_t code = 0;

  if (pCmprsor->i_copy == 1) goto _copy_cmpr;

  if (!I64_SAFE_ADD(val, pCmprsor->i_prev)) {
    // TODO
    goto _copy_cmpr;
  }

  int64_t  diff = val - pCmprsor->i_prev;
  uint64_t vZigzag = ZIGZAG_ENCODE(int64_t, diff);

  if (vZigzag >= SIMPLE8B_MAX) {
    // TODO
    goto _copy_cmpr;
  }

  int64_t nBit;
  if (vZigzag) {
    nBit = 64 - BUILDIN_CLZL(vZigzag);
  } else {
    nBit = 0;
  }

  if (pCmprsor->i_nele + 1 <= selector_to_elems[pCmprsor->i_selector] &&
      pCmprsor->i_nele + 1 <= selector_to_elems[bit_to_selector[nBit]]) {
    if (pCmprsor->i_selector < bit_to_selector[nBit]) {
      pCmprsor->i_selector = bit_to_selector[nBit];
    }
    pCmprsor->i_nele++;
  } else {
    while (pCmprsor->i_nele < selector_to_elems[pCmprsor->i_selector]) {
      pCmprsor->i_selector++;
    }
    pCmprsor->i_nele = selector_to_elems[pCmprsor->i_selector];

    code = tRealloc(&pCmprsor->aBuf[0], pCmprsor->nBuf[0] + sizeof(uint64_t));
    if (code) return code;

    uint64_t *bp = (uint64_t *)(pCmprsor->aBuf[0] + pCmprsor->nBuf[0]);
    pCmprsor->nBuf[0] += sizeof(uint64_t);
    bp[0] = pCmprsor->i_selector;
    for (int32_t iVal = 0; iVal < pCmprsor->i_nele; iVal++) {
      /* code */
    }

    // reset and continue
  }

  return code;

_copy_cmpr:
  code = tRealloc(&pCmprsor->aBuf[0], pCmprsor->nBuf[0] + 0 /*tDataTypes[pCmprsor->type].bytes (todo)*/);
  if (code) return code;

  // memcpy(pCmprsor->aBuf[0] + pCmprsor->nBuf[0], NULL /* todo */, 0 /*tDataTypes[pCmprsor->type].bytes (todo)*/);
  // pCmprsor->nBuf[0] += tDataTypes[pCmprsor->type].bytes;

  return code;
}

// Float =====================================================
static int32_t tCompFloat(SCompressor *pCmprsor, float f) {
  int32_t code = 0;

  union {
    float    f;
    uint32_t u;
  } val = {.f = f};

  uint32_t diff = val.u ^ pCmprsor->f_prev;
  pCmprsor->f_prev = val.u;

  int32_t clz, ctz;
  if (diff) {
    clz = BUILDIN_CLZ(diff);
    ctz = BUILDIN_CTZ(diff);
  } else {
    clz = sizeof(uint32_t);
    ctz = sizeof(uint32_t);
  }

  if (pCmprsor->f_n & 0x1 == 0) {
    code = tRealloc(&pCmprsor->aBuf[0], pCmprsor->nBuf[0] + 9 /* sizeof(float) * 2 + 1 */);
    if (code) return code;

    pCmprsor->f_flag_p = &pCmprsor->aBuf[0][pCmprsor->nBuf[0]];
    pCmprsor->nBuf[0]++;

    if (clz < ctz) {
      uint8_t nBytes = sizeof(uint32_t) - ctz / BITS_PER_BYTE;
      pCmprsor->f_flag_p[0] = (0x08 | (nBytes - 1));
      diff >>= (32 - nBytes * BITS_PER_BYTE);
    } else {
      uint8_t nBytes = sizeof(uint32_t) - clz / BITS_PER_BYTE;
      pCmprsor->f_flag_p[0] = nBytes - 1;
    }
  } else {
    if (clz < ctz) {
      uint8_t nBytes = sizeof(uint32_t) - ctz / BITS_PER_BYTE;
      pCmprsor->f_flag_p[0] |= ((0x08 | (nBytes - 1)) << 4);
      diff >>= (32 - nBytes * BITS_PER_BYTE);
    } else {
      uint8_t nBytes = sizeof(uint32_t) - clz / BITS_PER_BYTE;
      pCmprsor->f_flag_p[0] |= ((nBytes - 1) << 4);
    }
  }

  while (diff) {
    pCmprsor->aBuf[0][pCmprsor->nBuf[0]] = (diff & 0xff);
    pCmprsor->nBuf[0]++;
    diff >>= BITS_PER_BYTE;
  }

  pCmprsor->f_n++;
  return code;
}

// Double =====================================================
static int32_t tCompDouble(SCompressor *pCmprsor, double d) {
  int32_t code = 0;

  union {
    double   d;
    uint64_t u;
  } val = {.d = d};

  uint64_t diff = val.u ^ pCmprsor->d_prev;
  pCmprsor->d_prev = val.u;

  int32_t clz, ctz;
  if (diff) {
    clz = BUILDIN_CLZL(diff);
    ctz = BUILDIN_CTZL(diff);
  } else {
    clz = sizeof(uint64_t);
    ctz = sizeof(uint64_t);
  }

  if (pCmprsor->d_n & 0x1 == 0) {
    code = tRealloc(&pCmprsor->aBuf[0], pCmprsor->nBuf[0] + 17 /* sizeof(double) * 2 + 1 */);
    if (code) return code;

    pCmprsor->d_flag_p = &pCmprsor->aBuf[0][pCmprsor->nBuf[0]];
    pCmprsor->nBuf[0]++;

    if (clz < ctz) {
      uint8_t nBytes = sizeof(uint64_t) - ctz / BITS_PER_BYTE;
      pCmprsor->d_flag_p[0] = (0x08 | (nBytes - 1));
      diff >>= (64 - nBytes * BITS_PER_BYTE);
    } else {
      uint8_t nBytes = sizeof(uint64_t) - clz / BITS_PER_BYTE;
      pCmprsor->d_flag_p[0] = nBytes - 1;
    }
  } else {
    if (clz < ctz) {
      uint8_t nBytes = sizeof(uint64_t) - ctz / BITS_PER_BYTE;
      pCmprsor->d_flag_p[0] |= ((0x08 | (nBytes - 1)) << 4);
      diff >>= (64 - nBytes * BITS_PER_BYTE);
    } else {
      uint8_t nBytes = sizeof(uint64_t) - clz / BITS_PER_BYTE;
      pCmprsor->d_flag_p[0] |= ((nBytes - 1) << 4);
    }
  }

  while (diff) {
    pCmprsor->aBuf[0][pCmprsor->nBuf[0]] = (diff & 0xff);
    pCmprsor->nBuf[0]++;
    diff >>= BITS_PER_BYTE;
  }

  pCmprsor->d_n++;
  return code;
}

// Binary =====================================================
static int32_t tCompBinary(SCompressor *pCmprsor, const uint8_t *pData, int32_t nData) {
  int32_t code = 0;

  if (nData) {
    code = tRealloc(&pCmprsor->aBuf[0], pCmprsor->nBuf[0] + nData);
    if (code) return code;

    memcpy(pCmprsor->aBuf[0] + pCmprsor->nBuf[0], pData, nData);
    pCmprsor->nBuf[0] += nData;
  }
  pCmprsor->b_n++;

  return code;
}

// Bool =====================================================
static const uint8_t BOOL_CMPR_TABLE[] = {0b01, 0b0100, 0b010000, 0b01000000};

static int32_t tCompBool(SCompressor *pCmprsor, bool vBool) {
  int32_t code = 0;

  int32_t mod4 = pCmprsor->bool_n & 3;
  if (vBool) {
    pCmprsor->aBuf[0][pCmprsor->nBuf[0]] |= BOOL_CMPR_TABLE[mod4];
  }
  pCmprsor->bool_n++;
  if (mod4 == 3) {
    pCmprsor->nBuf[0]++;
    pCmprsor->aBuf[0][pCmprsor->nBuf[0]] = 0;

    code = tRealloc(&pCmprsor->aBuf[0], pCmprsor->nBuf[0]);
    if (code) goto _exit;
  }

_exit:
  return code;
}

// SCompressor =====================================================
int32_t tCompressorCreate(SCompressor **ppCmprsor) {
  int32_t code = 0;

  *ppCmprsor = (SCompressor *)taosMemoryCalloc(1, sizeof(SCompressor));
  if ((*ppCmprsor) == NULL) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _exit;
  }

  code = tRealloc(&(*ppCmprsor)->aBuf[0], 1024);
  if (code) {
    taosMemoryFree(*ppCmprsor);
    *ppCmprsor = NULL;
    goto _exit;
  }

_exit:
  return code;
}

int32_t tCompressorDestroy(SCompressor *pCmprsor) {
  int32_t code = 0;

  if (pCmprsor) {
    int32_t nBuf = sizeof(pCmprsor->aBuf) / sizeof(pCmprsor->aBuf[0]);
    for (int32_t iBuf = 0; iBuf < nBuf; iBuf++) {
      tFree(pCmprsor->aBuf[iBuf]);
    }

    taosMemoryFree(pCmprsor);
  }

  return code;
}

int32_t tCompressorReset(SCompressor *pCmprsor, int8_t type, int8_t cmprAlg) {
  int32_t code = 0;

  pCmprsor->type = type;
  pCmprsor->cmprAlg = cmprAlg;
  pCmprsor->nBuf[0] = 0;  // (todo) may or may not +/- 1

  switch (type) {
    case TSDB_DATA_TYPE_TIMESTAMP:
      pCmprsor->ts_copy = 0;
      pCmprsor->ts_n = 0;
      break;
    case TSDB_DATA_TYPE_BOOL:
      pCmprsor->bool_n = 0;
      pCmprsor->aBuf[0][0] = 0;
      break;
    case TSDB_DATA_TYPE_BINARY:
      pCmprsor->b_n = 0;
      break;
    default:
      break;
  }

  return code;
}

int32_t tCompGen(SCompressor *pCmprsor, const uint8_t **ppData, int64_t *nData) {
  int32_t code = 0;

  if (pCmprsor->cmprAlg == TWO_STAGE_COMP /*|| IS_VAR_DATA_TYPE(pCmprsor->type)*/) {
    code = tRealloc(&pCmprsor->aBuf[1], pCmprsor->nBuf[0] + 1);
    if (code) goto _exit;

    int64_t ret = LZ4_compress_default(pCmprsor->aBuf[0], pCmprsor->aBuf[1] + 1, pCmprsor->nBuf[0], pCmprsor->nBuf[0]);
    if (ret) {
      pCmprsor->aBuf[1][0] = 0;
      pCmprsor->nBuf[1] = ret + 1;
    } else {
      pCmprsor->aBuf[1][0] = 1;
      memcpy(pCmprsor->aBuf[1] + 1, pCmprsor->aBuf[0], pCmprsor->nBuf[0]);
      pCmprsor->nBuf[1] = pCmprsor->nBuf[0] + 1;
    }

    *ppData = pCmprsor->aBuf[1];
    *nData = pCmprsor->nBuf[1];
  } else {
    *ppData = pCmprsor->aBuf[0];
    *nData = pCmprsor->nBuf[0];
  }

_exit:
  return code;
}

int32_t tCompress(SCompressor *pCmprsor, void *pData, int64_t nData) {
  int32_t code = 0;
  // TODO
  return code;
}