1 /**
2  * Copyright (c) 2021-2022 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 
16 #ifndef LIBPANDABASE_UTILS_BIT_MEMORY_REGION_INL_H
17 #define LIBPANDABASE_UTILS_BIT_MEMORY_REGION_INL_H
18 
19 #include "bit_memory_region.h"
20 
21 #include <iomanip>
22 
23 namespace panda {
24 
25 template <typename Base>
Dump(std::ostream &os) const26 void BitMemoryRegion<Base>::Dump(std::ostream &os) const
27 {
28     static constexpr size_t BITS_PER_HEX_DIGIT = 4;
29     os << "0x";
30     static constexpr size_t BITS_PER_WORD = sizeof(size_t) * BITS_PER_BYTE;
31     if (Size() >= BITS_PER_WORD) {
32         bool is_zero = true;
33         size_t width = BITS_PER_WORD - (BITS_PER_HEX_DIGIT - Size() % BITS_PER_HEX_DIGIT);
34         for (ssize_t i = Size() - width; i >= 0; i -= width) {
35             auto val = Read(i, width);
36             if (val != 0 || !is_zero) {
37                 if (!is_zero) {
38                     os << std::setw(static_cast<int>(width / BITS_PER_HEX_DIGIT)) << std::setfill('0');
39                 }
40                 os << std::hex << val;
41                 is_zero = false;
42             }
43             if (i == 0) {
44                 break;
45             }
46             width = std::min<size_t>(i, BITS_PER_WORD);
47         }
48         if (is_zero) {
49             os << '0';
50         }
51     } else {
52         os << std::hex << ReadAll();
53     }
54     os << std::dec;
55 }
56 
57 template <typename T>
operator <<(std::ostream &os, const BitMemoryRegion<T> &region)58 inline std::ostream &operator<<(std::ostream &os, const BitMemoryRegion<T> &region)
59 {
60     region.Dump(os);
61     return os;
62 }
63 
64 }  // namespace panda
65 
66 #endif  // LIBPANDABASE_UTILS_BIT_MEMORY_REGION_INL_H
67