1 /*
2 * Copyright (C) 2017 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 <sstream>
18
19 #include "netdutils/Slice.h"
20
21 namespace android {
22 namespace netdutils {
23 namespace {
24
25 // Convert one byte to a two character hexadecimal string
toHex(uint8_t byte)26 const std::string toHex(uint8_t byte) {
27 const std::array<char, 16> kLookup = {
28 {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}};
29 return {kLookup[byte >> 4], kLookup[byte & 0xf]};
30 }
31
32 } // namespace
33
toString(const Slice s)34 std::string toString(const Slice s) {
35 return std::string(reinterpret_cast<char*>(s.base()), s.size());
36 }
37
toHex(const Slice s,int wrap)38 std::string toHex(const Slice s, int wrap) {
39 Slice tail = s;
40 int count = 0;
41 std::stringstream ss;
42 while (!tail.empty()) {
43 uint8_t byte = 0;
44 extract(tail, byte);
45 ss << toHex(byte);
46 if ((++count % wrap) == 0) {
47 ss << "\n";
48 }
49 tail = drop(tail, 1);
50 }
51 return ss.str();
52 }
53
operator <<(std::ostream & os,const Slice & slice)54 std::ostream& operator<<(std::ostream& os, const Slice& slice) {
55 return os << std::hex << "Slice[base: " << reinterpret_cast<void*>(slice.base())
56 << ", limit: " << reinterpret_cast<void*>(slice.limit()) << ", size: 0x"
57 << slice.size() << "]" << std::dec;
58 }
59
60 } // namespace netdutils
61 } // namespace android
62