blob: 9976e0f6b0b1be0c13e25fc2e95dc759ba83dbe6 [file] [log] [blame]
Paul Stewart3ecfa2b2011-07-15 10:47:42 -07001// Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "shill/byte_string.h"
6
7#include <netinet/in.h>
8
Darin Petkove3e1cfa2011-08-11 13:41:17 -07009#include <base/string_number_conversions.h>
10
11using std::string;
12
Paul Stewart3ecfa2b2011-07-15 10:47:42 -070013namespace shill {
14
15// static
16ByteString ByteString::CreateFromCPUUInt32(uint32 val) {
17 return ByteString(reinterpret_cast<unsigned char *>(&val), sizeof(val));
18}
19
20// static
21ByteString ByteString::CreateFromNetUInt32(uint32 val) {
22 return CreateFromCPUUInt32(htonl(val));
23}
24
25bool ByteString::ConvertToCPUUInt32(uint32 *val) const {
26 if (val == NULL || data_.size() != sizeof(*val)) {
27 return false;
28 }
29 memcpy(val, GetConstData(), sizeof(*val));
30
31 return true;
32}
33
34bool ByteString::ConvertToNetUInt32(uint32 *val) const {
35 if (!ConvertToCPUUInt32(val)) {
36 return false;
37 }
38 *val = ntohl(*val);
39 return true;
40}
41
42bool ByteString::IsZero() const {
43 for (std::vector<unsigned char>::const_iterator i = data_.begin();
44 i != data_.end(); ++i) {
45 if (*i != 0) {
46 return false;
47 }
48 }
49 return true;
50}
51
52bool ByteString::Equals(const ByteString &b) const {
53 return data_ == b.data_;
54}
55
Paul Stewartdd7df792011-07-15 11:09:50 -070056void ByteString::Append(const ByteString &b) {
57 data_.insert(data_.end(), b.data_.begin(), b.data_.end());
58}
59
Darin Petkove3e1cfa2011-08-11 13:41:17 -070060string ByteString::HexEncode() const {
61 return base::HexEncode(GetConstData(), GetLength());
62}
63
Paul Stewart3ecfa2b2011-07-15 10:47:42 -070064} // namespace shill