blob: f18275656d305df4ad7a175f949847a5fd57df16 [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
Paul Stewartfe1c0e12012-04-30 19:57:04 -070052bool ByteString::BitwiseAnd(const ByteString &b) {
Paul Stewartf7bf9bf2012-04-17 17:30:14 -070053 if (GetLength() != b.GetLength()) {
54 return false;
55 }
56 for (size_t i = 0; i < GetLength(); ++i) {
57 data_[i] &= b.data_[i];
58 }
59 return true;
60}
61
Paul Stewartfe1c0e12012-04-30 19:57:04 -070062bool ByteString::BitwiseOr(const ByteString &b) {
63 if (GetLength() != b.GetLength()) {
64 return false;
65 }
66 for (size_t i = 0; i < GetLength(); ++i) {
67 data_[i] |= b.data_[i];
68 }
69 return true;
70}
71
72void ByteString::BitwiseInvert() {
73 for (size_t i = 0; i < GetLength(); ++i) {
74 data_[i] = ~data_[i];
75 }
76}
77
Paul Stewart3ecfa2b2011-07-15 10:47:42 -070078bool ByteString::Equals(const ByteString &b) const {
79 return data_ == b.data_;
80}
81
Paul Stewartdd7df792011-07-15 11:09:50 -070082void ByteString::Append(const ByteString &b) {
83 data_.insert(data_.end(), b.data_.begin(), b.data_.end());
84}
85
Darin Petkove3e1cfa2011-08-11 13:41:17 -070086string ByteString::HexEncode() const {
87 return base::HexEncode(GetConstData(), GetLength());
88}
89
Paul Stewart3ecfa2b2011-07-15 10:47:42 -070090} // namespace shill