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 
20 #include "doc_errno.h"
21 #include "rd_log_print.h"
22 #include "securec.h"
23 
24 namespace DocumentDB {
25 static uint16_t g_oIdIncNum = 0;
26 constexpr uint16_t MAX_NUMBER_OF_AUTOINCREMENTS = 65535;
27 constexpr uint16_t UINT_ZERO = 0;
InitDocIdFromOid(DocKey & docKey)28 static int InitDocIdFromOid(DocKey &docKey)
29 {
30     time_t nowTime = time(nullptr);
31     if (nowTime < 0) {
32         return -E_INNER_ERROR;
33     }
34     uint32_t now = (uint32_t)nowTime;
35     uint16_t iv = g_oIdIncNum++;
36     // The maximum number of autoincrements is 65535, and if it is exceeded, it becomes 0.
37     if (g_oIdIncNum > MAX_NUMBER_OF_AUTOINCREMENTS) {
38         g_oIdIncNum = UINT_ZERO;
39     }
40     char *idTemp = new char[GRD_DOC_OID_HEX_SIZE + 1];
41     if (sprintf_s(idTemp, GRD_DOC_OID_HEX_SIZE + 1, "%08x%04x", now, iv) < 0) {
42         delete[] idTemp;
43         GLOGE("get oid error");
44         return -E_INNER_ERROR;
45     }
46     docKey.key = idTemp;
47     delete[] idTemp;
48     return E_OK;
49 }
50 
GetOidDocKey(DocKey & key)51 int DocumentKey::GetOidDocKey(DocKey &key)
52 {
53     int ret = InitDocIdFromOid(key);
54     return ret;
55 }
56 } // namespace DocumentDB