Line data Source code
1 : /**
2 : * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3 : * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4 : * CANN Open Software License Agreement Version 2.0 (the "License").
5 : * Please refer to the License for details. You may not use this file except in compliance with the License.
6 : * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7 : * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8 : * See LICENSE in the root of the software repository for the full text of the License.
9 : */
10 :
11 : #include "calc_crc.h"
12 : #include <string>
13 : #include <cstdlib>
14 : #include <iostream>
15 : #include <ios>
16 : #include <fstream>
17 : #include <mutex>
18 : #include "hccl_common.h"
19 :
20 : namespace hccl {
21 : constexpr int CRC_TABLE_LENGTH = 256;
22 : constexpr u32 CRC_DEFAULT_VALUE = 0xEDB88320;
23 : constexpr u32 CRC_CALC_8 = 8;
24 : constexpr u32 CRC_CALC_10 = 10;
25 : constexpr s32 STRING_MAX_LENGTH = 40 * 1024 * 1024;
26 : u32 g_crcCalcTable[CRC_TABLE_LENGTH];
27 :
28 241 : HcclResult CalcCrc::HcclCalcCrc(const char *data, u64 length, u32 &crcValue)
29 : {
30 241 : CHK_PTR_NULL(data);
31 :
32 241 : CHK_PRT_RET(length <= 0 || length > STRING_MAX_LENGTH,
33 : HCCL_ERROR("[Calc][StringCrc]String length[%llu] is empty or over than %d bytes.", length, STRING_MAX_LENGTH),
34 : HCCL_E_PARA);
35 241 : HCCL_DEBUG("data[%s], length[%llu]", data, length);
36 :
37 : // 计算并设置CRC值
38 241 : u32 ret = INVALID_UINT;
39 159720 : for (u64 i = 0; i < length; i++) {
40 159479 : ret = g_crcCalcTable[((ret & 0xFF) ^ static_cast<u8>(data[i]))] ^ (ret >> CRC_CALC_8);
41 : }
42 :
43 241 : crcValue = ~ret;
44 241 : return HCCL_SUCCESS;
45 : }
46 :
47 43 : __attribute__((constructor)) void InitTable()
48 : {
49 11051 : for (u32 i = 0; i < CRC_TABLE_LENGTH; i++) {
50 11008 : u32 crc = i;
51 99072 : for (u32 j = 0; j < CRC_CALC_8; j++) {
52 88064 : if ((crc & 1) != 0) {
53 44032 : crc = (crc >> 1) ^ CRC_DEFAULT_VALUE;
54 : } else {
55 44032 : crc = crc >> 1;
56 : }
57 : }
58 11008 : g_crcCalcTable[i] = crc;
59 : }
60 43 : }
61 : } // namespace hccl
|