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) {
S
Shengliang Guan 已提交
23 24
    char    uid[65] = {0};
    int32_t code = taosGetSystemUUID(uid, sizeof(uid));
L
Liu Jicong 已提交
25 26 27
    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) {
S
Shengliang Guan 已提交
42 43
    char    uid[65] = {0};
    int32_t code = taosGetSystemUUID(uid, 64);
L
Liu Jicong 已提交
44 45 46
    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
    }
  }

D
dapan 已提交
51
  int64_t id;
dengyihao's avatar
dengyihao 已提交
52

D
dapan 已提交
53
  while (true) {
54
    int64_t  ts = taosGetTimestampMs() >> 8;
D
dapan 已提交
55 56 57
    uint64_t pid = taosGetPId();
    int32_t  val = atomic_add_fetch_32(&tUUIDSerialNo, 1);

58
    id = ((tUUIDHashId & 0x07FF) << 52) | ((pid & 0x0F) << 48) | ((ts & 0x3FFFFFF) << 20) | (val & 0xFFFFF);
D
dapan 已提交
59 60 61 62
    if (id) {
      break;
    }
  }
L
Liu Jicong 已提交
63 64 65

  return id;
}