1 /*
2 * Copyright 2023 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "host/commands/casimir_control_server/crc.h"
18
19 #include "common/libs/utils/result.h"
20
21 namespace cuttlefish {
22
23 namespace {
Crc16(const std::vector<uint8_t> & data,uint16_t initial,bool invert)24 static std::vector<uint8_t> Crc16(const std::vector<uint8_t>& data,
25 uint16_t initial, bool invert) {
26 uint16_t w_crc = initial;
27
28 for (uint8_t byte : data) {
29 byte ^= (w_crc & 0x00FF);
30 byte ^= (byte << 4) & 0xFF;
31 w_crc = (w_crc >> 8) ^ ((byte << 8) & 0xFFFF) ^ ((byte << 3) & 0xFFFF) ^
32 ((byte >> 4) & 0xFFFF);
33 }
34
35 if (invert) {
36 w_crc = ~w_crc;
37 }
38
39 return {static_cast<uint8_t>(w_crc & 0xFF),
40 static_cast<uint8_t>((w_crc >> 8) & 0xFF)};
41 }
42
Crc16A(const std::vector<uint8_t> & data)43 static std::vector<uint8_t> Crc16A(const std::vector<uint8_t>& data) {
44 return Crc16(data, 0x6363, false);
45 }
46
Crc16B(const std::vector<uint8_t> & data)47 static std::vector<uint8_t> Crc16B(const std::vector<uint8_t>& data) {
48 return Crc16(data, 0xFFFF, true);
49 }
50 } // namespace
51
WithCrc16A(const std::vector<uint8_t> & data)52 Result<std::vector<uint8_t>> WithCrc16A(const std::vector<uint8_t>& data) {
53 std::vector<uint8_t> newData = data;
54 std::vector<uint8_t> crc = Crc16A(newData);
55 newData.insert(newData.end(), crc.begin(), crc.end());
56 return newData;
57 }
58
WithCrc16B(const std::vector<uint8_t> & data)59 Result<std::vector<uint8_t>> WithCrc16B(const std::vector<uint8_t>& data) {
60 std::vector<uint8_t> newData = data;
61 std::vector<uint8_t> crc = Crc16B(newData);
62 newData.insert(newData.end(), crc.begin(), crc.end());
63 return newData;
64 }
65
66 } // namespace cuttlefish
67