1 /*
2  * Copyright (C) 2021 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 "HidUtils.h"
18 #include <gtest/gtest.h>
19 
20 using HidUtil::copyBits;
21 
TEST(CopyBitsTest,CopyBits)22 TEST(CopyBitsTest, CopyBits) {
23     const struct {
24         uint32_t src;
25         uint32_t dst;
26         int src_bit_offset;
27         int dst_bit_offset;
28         int bit_count;
29         uint32_t expected_dst;
30     } kTestVectorList[] = {
31         { 0x00000005, 0x00000000,  0,  0,  8, 0x00000005 },
32         { 0x00000005, 0x00000000,  0,  4,  8, 0x00000050 },
33         { 0x0000000C, 0x00000020,  0,  4,  8, 0x000000C0 },
34         { 0x00000005, 0x0000F02F,  0,  4,  8, 0x0000F05F },
35         { 0x12345678, 0x87654321,  5, 11, 17, 0x8D159B21 },
36         { 0x12345678, 0x87654321, 11,  5, 17, 0x8748D141 },
37     };
38 
39     for (auto test_vector : kTestVectorList) {
40         uint32_t dst = test_vector.dst;
41         copyBits(&(test_vector.src), &dst, sizeof(dst),
42                  test_vector.src_bit_offset, test_vector.dst_bit_offset,
43                  test_vector.bit_count);
44         EXPECT_EQ(test_vector.expected_dst, dst);
45     }
46 }
47 
TEST(CopyBitsTest,Overflow)48 TEST(CopyBitsTest, Overflow) {
49     const struct {
50         uint32_t src;
51         uint32_t dst;
52         unsigned int src_bit_offset;
53         unsigned int dst_bit_offset;
54         unsigned int bit_count;
55         uint32_t expected_dst;
56     } kTestVectorList[] = {
57         { 0x000000FF, 0x00000000,  0,        0,        8, 0x000000FF },
58         { 0x000000FF, 0x00000000,  0,       24,        8, 0xFF000000 },
59         { 0x000000FF, 0x00000000,  0,       25,        8, 0x00000000 },
60         { 0x000000FF, 0x00000000,  0,       32,        8, 0x00000000 },
61         { 0x000000FF, 0x00000000,  0, UINT_MAX,        8, 0x00000000 },
62         { 0x000000FF, 0x00000000,  0,        8, UINT_MAX, 0x00000000 },
63     };
64 
65     for (auto test_vector : kTestVectorList) {
66         uint32_t dst = test_vector.dst;
67         copyBits(&(test_vector.src), &dst, sizeof(dst),
68                  test_vector.src_bit_offset, test_vector.dst_bit_offset,
69                  test_vector.bit_count);
70         EXPECT_EQ(test_vector.expected_dst, dst);
71     }
72 }
73 
74