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