tuuid.c 1.8 KB
Newer Older
L
Liu Jicong 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * 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 "tuuid.h"

L
rename  
Liu Jicong 已提交
18 19
static int64_t tUUIDHashId = 0;
static int32_t tUUIDSerialNo = 0;
L
Liu Jicong 已提交
20 21

int32_t tGenIdPI32(void) {
L
rename  
Liu Jicong 已提交
22
  if (tUUIDHashId == 0) {
L
Liu Jicong 已提交
23 24 25 26 27
    char    uid[64];
    int32_t code = taosGetSystemUUID(uid, tListLen(uid));
    if (code != TSDB_CODE_SUCCESS) {
      terrno = TAOS_SYSTEM_ERROR(errno);
    } else {
L
rename  
Liu Jicong 已提交
28
      tUUIDHashId = MurmurHash3_32(uid, strlen(uid));
L
Liu Jicong 已提交
29 30 31 32 33
    }
  }

  int64_t  ts = taosGetTimestampMs();
  uint64_t pid = taosGetPId();
L
rename  
Liu Jicong 已提交
34
  int32_t  val = atomic_add_fetch_32(&tUUIDSerialNo, 1);
L
Liu Jicong 已提交
35

L
rename  
Liu Jicong 已提交
36
  int32_t id = ((tUUIDHashId & 0x1F) << 26) | ((pid & 0x3F) << 20) | ((ts & 0xFFF) << 8) | (val & 0xFF);
L
Liu Jicong 已提交
37 38 39 40
  return id;
}

int64_t tGenIdPI64(void) {
L
rename  
Liu Jicong 已提交
41
  if (tUUIDHashId == 0) {
L
Liu Jicong 已提交
42 43 44 45 46
    char    uid[64];
    int32_t code = taosGetSystemUUID(uid, tListLen(uid));
    if (code != TSDB_CODE_SUCCESS) {
      terrno = TAOS_SYSTEM_ERROR(errno);
    } else {
L
rename  
Liu Jicong 已提交
47
      tUUIDHashId = MurmurHash3_32(uid, strlen(uid));
L
Liu Jicong 已提交
48 49 50 51 52
    }
  }

  int64_t  ts = taosGetTimestampMs();
  uint64_t pid = taosGetPId();
L
rename  
Liu Jicong 已提交
53
  int32_t  val = atomic_add_fetch_32(&tUUIDSerialNo, 1);
L
Liu Jicong 已提交
54

L
rename  
Liu Jicong 已提交
55
  int64_t id = ((tUUIDHashId & 0x07FF) << 52) | ((pid & 0x0FFF) << 40) | ((ts & 0xFFFFFF) << 16) | (val & 0xFFFF);
L
Liu Jicong 已提交
56 57
  return id;
}