blob: fae4953868606728326f136758ff07026d964c3a [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
Paul Stewart91a5aac2012-07-20 11:55:40 -070015ByteString ByteString::GetSubstring(size_t offset, size_t length) const {
16 if (offset > GetLength()) {
17 offset = GetLength();
18 }
19 if (length > GetLength() - offset) {
20 length = GetLength() - offset;
21 }
22 return ByteString(GetConstData() + offset, length);
23}
24
Paul Stewart3ecfa2b2011-07-15 10:47:42 -070025// static
26ByteString ByteString::CreateFromCPUUInt32(uint32 val) {
27 return ByteString(reinterpret_cast<unsigned char *>(&val), sizeof(val));
28}
29
30// static
31ByteString ByteString::CreateFromNetUInt32(uint32 val) {
32 return CreateFromCPUUInt32(htonl(val));
33}
34
35bool ByteString::ConvertToCPUUInt32(uint32 *val) const {
36 if (val == NULL || data_.size() != sizeof(*val)) {
37 return false;
38 }
39 memcpy(val, GetConstData(), sizeof(*val));
40
41 return true;
42}
43
44bool ByteString::ConvertToNetUInt32(uint32 *val) const {
45 if (!ConvertToCPUUInt32(val)) {
46 return false;
47 }
48 *val = ntohl(*val);
49 return true;
50}
51
52bool ByteString::IsZero() const {
53 for (std::vector<unsigned char>::const_iterator i = data_.begin();
54 i != data_.end(); ++i) {
55 if (*i != 0) {
56 return false;
57 }
58 }
59 return true;
60}
61
Paul Stewartfe1c0e12012-04-30 19:57:04 -070062bool ByteString::BitwiseAnd(const ByteString &b) {
Paul Stewartf7bf9bf2012-04-17 17:30:14 -070063 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
Paul Stewartfe1c0e12012-04-30 19:57:04 -070072bool ByteString::BitwiseOr(const ByteString &b) {
73 if (GetLength() != b.GetLength()) {
74 return false;
75 }
76 for (size_t i = 0; i < GetLength(); ++i) {
77 data_[i] |= b.data_[i];
78 }
79 return true;
80}
81
82void ByteString::BitwiseInvert() {
83 for (size_t i = 0; i < GetLength(); ++i) {
84 data_[i] = ~data_[i];
85 }
86}
87
Paul Stewart3ecfa2b2011-07-15 10:47:42 -070088bool ByteString::Equals(const ByteString &b) const {
89 return data_ == b.data_;
90}
91
Paul Stewartdd7df792011-07-15 11:09:50 -070092void ByteString::Append(const ByteString &b) {
93 data_.insert(data_.end(), b.data_.begin(), b.data_.end());
94}
95
Darin Petkove3e1cfa2011-08-11 13:41:17 -070096string ByteString::HexEncode() const {
97 return base::HexEncode(GetConstData(), GetLength());
98}
99
Paul Stewart3ecfa2b2011-07-15 10:47:42 -0700100} // namespace shill