• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2 * Copyright (c) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #include "document_key.h"
16 
17 #include <ctime>
18 #include <cstdio>
19 #include <cinttypes>
20 
21 #include "doc_errno.h"
22 #include "rd_log_print.h"
23 #include "securec.h"
24 
25 namespace DocumentDB {
26 static uint16_t g_oIdIncNum = 0;
27 constexpr uint16_t MAX_NUMBER_OF_AUTOINCREMENTS = 65535;
28 constexpr uint16_t UINT_ZERO = 0;
InitDocIdFromOid(DocKey & docKey)29 static int InitDocIdFromOid(DocKey &docKey)
30 {
31     time_t nowTime = time(nullptr);
32     if (nowTime < 0) {
33         return -E_INNER_ERROR;
34     }
35     uint64_t nowTemp = static_cast<uint64_t>(nowTime);
36     if (nowTemp > UINT32_MAX) {
37         GLOGE("Time overflows 32-bit range. nowTemp = %" PRIu64, nowTemp);
38         return -E_INNER_ERROR;
39     }
40     uint32_t now = static_cast<uint32_t>(nowTemp);
41     uint16_t iv = g_oIdIncNum;
42     // The maximum number of autoincrements is 65535, and if it is exceeded, it becomes 0.
43     if (g_oIdIncNum == MAX_NUMBER_OF_AUTOINCREMENTS) {
44         g_oIdIncNum = UINT_ZERO;
45     } else {
46         g_oIdIncNum++;
47     }
48     char *idTemp = new char[GRD_DOC_OID_HEX_SIZE + 1];
49     if (sprintf_s(idTemp, GRD_DOC_OID_HEX_SIZE + 1, "%08x%04x", now, iv) < 0) {
50         delete[] idTemp;
51         GLOGE("get oid error");
52         return -E_INNER_ERROR;
53     }
54     docKey.key = idTemp;
55     delete[] idTemp;
56     return E_OK;
57 }
58 
GetOidDocKey(DocKey & key)59 int DocumentKey::GetOidDocKey(DocKey &key)
60 {
61     int ret = InitDocIdFromOid(key);
62     return ret;
63 }
64 } // namespace DocumentDB