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 242 : HcclResult CalcCrc::HcclCalcCrc(const char* data, u64 length, u32& crcValue)
29 : {
30 242 : CHK_PTR_NULL(data);
31 :
32 242 : CHK_PRT_RET(
33 : length <= 0 || length > STRING_MAX_LENGTH,
34 : HCCL_ERROR("[Calc][StringCrc]String length[%llu] is empty or over than %d bytes.", length, STRING_MAX_LENGTH),
35 : HCCL_E_PARA);
36 242 : HCCL_DEBUG("data[%s], length[%llu]", data, length);
37 :
38 : // 计算并设置CRC值
39 242 : u32 ret = INVALID_UINT;
40 160228 : for (u64 i = 0; i < length; i++) {
41 159986 : ret = g_crcCalcTable[((ret & 0xFF) ^ static_cast<u8>(data[i]))] ^ (ret >> CRC_CALC_8);
42 : }
43 :
44 242 : crcValue = ~ret;
45 242 : return HCCL_SUCCESS;
46 : }
47 :
48 47 : __attribute__((constructor)) void InitTable()
49 : {
50 12079 : for (u32 i = 0; i < CRC_TABLE_LENGTH; i++) {
51 12032 : u32 crc = i;
52 108288 : for (u32 j = 0; j < CRC_CALC_8; j++) {
53 96256 : if ((crc & 1) != 0) {
54 48128 : crc = (crc >> 1) ^ CRC_DEFAULT_VALUE;
55 : } else {
56 48128 : crc = crc >> 1;
57 : }
58 : }
59 12032 : g_crcCalcTable[i] = crc;
60 : }
61 47 : }
62 : } // namespace hccl
|