A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
tap-encode-decode.cc
Go to the documentation of this file.
1/*
2 * Copyright (c) 2009 University of Washington
3 *
4 * SPDX-License-Identifier: GPL-2.0-only
5 */
6
7#include <iomanip>
8#include <iostream>
9#include <sstream>
10#include <stdint.h>
11#include <string>
12
13namespace ns3
14{
15
16/**
17 * \brief Convert a byte buffer to a string containing a hex representation
18 * of the buffer. Make the string pretty by adding a colon (':') between
19 * the hex.
20 *
21 * \param buffer The input buffer to be converted.
22 * \param len The length of the input buffer.
23 * \returns A string containing a hex representation of the data in buffer.
24 */
25std::string
26TapBufferToString(uint8_t* buffer, uint32_t len)
27{
28 std::ostringstream oss;
29 //
30 // Tell the stream to make hex characters, zero-filled
31 //
32 oss.setf(std::ios::hex, std::ios::basefield);
33 oss.fill('0');
34
35 //
36 // Loop through the buffer, separating the two-digit-wide hex bytes
37 // with a colon.
38 //
39 for (uint32_t i = 0; i < len; i++)
40 {
41 oss << ":" << std::setw(2) << (uint32_t)buffer[i];
42 }
43 return oss.str();
44}
45
46/**
47 * \brief Convert string encoded by the inverse function (TapBufferToString)
48 * back into a byte buffer.
49 *
50 * \param s The input string.
51 * \param buffer The buffer to initialize with the converted bits.
52 * \param len The length of the data that is valid in the buffer.
53 * \returns True indicates a successful conversion.
54 */
55bool
56TapStringToBuffer(std::string s, uint8_t* buffer, uint32_t* len)
57{
58 //
59 // If the string was made by our inverse function, the string length must
60 // be a multiple of three characters in length. Use this fact to do a
61 // quick reasonableness test.
62 //
63 if ((s.length() % 3) != 0)
64 {
65 return false;
66 }
67
68 std::istringstream iss;
69 iss.str(s);
70
71 uint8_t n = 0;
72
73 while (iss.good())
74 {
75 //
76 // The first character in the "triplet" we're working on is always the
77 // the ':' separator. Read that into a char and make sure we're skipping
78 // what we think we're skipping.
79 //
80 char c;
81 iss.read(&c, 1);
82 if (c != ':')
83 {
84 return false;
85 }
86
87 //
88 // And then read in the real bits and convert them.
89 //
90 uint32_t tmp;
91 iss >> std::hex >> tmp;
92 buffer[n] = tmp;
93 n++;
94 }
95
96 *len = n;
97 return true;
98}
99
100} // namespace ns3
Every class exported by the ns3 library is enclosed in the ns3 namespace.
bool TapStringToBuffer(std::string s, uint8_t *buffer, uint32_t *len)
Convert string encoded by the inverse function (TapBufferToString) back into a byte buffer.
std::string TapBufferToString(uint8_t *buffer, uint32_t len)
Convert a byte buffer to a string containing a hex representation of the buffer.