Paul Stewart | 3ecfa2b | 2011-07-15 10:47:42 -0700 | [diff] [blame] | 1 | // 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 Petkov | e3e1cfa | 2011-08-11 13:41:17 -0700 | [diff] [blame] | 9 | #include <base/string_number_conversions.h> |
| 10 | |
| 11 | using std::string; |
| 12 | |
Paul Stewart | 3ecfa2b | 2011-07-15 10:47:42 -0700 | [diff] [blame] | 13 | namespace shill { |
| 14 | |
| 15 | // static |
| 16 | ByteString ByteString::CreateFromCPUUInt32(uint32 val) { |
| 17 | return ByteString(reinterpret_cast<unsigned char *>(&val), sizeof(val)); |
| 18 | } |
| 19 | |
| 20 | // static |
| 21 | ByteString ByteString::CreateFromNetUInt32(uint32 val) { |
| 22 | return CreateFromCPUUInt32(htonl(val)); |
| 23 | } |
| 24 | |
| 25 | bool 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 | |
| 34 | bool ByteString::ConvertToNetUInt32(uint32 *val) const { |
| 35 | if (!ConvertToCPUUInt32(val)) { |
| 36 | return false; |
| 37 | } |
| 38 | *val = ntohl(*val); |
| 39 | return true; |
| 40 | } |
| 41 | |
| 42 | bool 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 | |
| 52 | bool ByteString::Equals(const ByteString &b) const { |
| 53 | return data_ == b.data_; |
| 54 | } |
| 55 | |
Paul Stewart | dd7df79 | 2011-07-15 11:09:50 -0700 | [diff] [blame] | 56 | void ByteString::Append(const ByteString &b) { |
| 57 | data_.insert(data_.end(), b.data_.begin(), b.data_.end()); |
| 58 | } |
| 59 | |
Darin Petkov | e3e1cfa | 2011-08-11 13:41:17 -0700 | [diff] [blame] | 60 | string ByteString::HexEncode() const { |
| 61 | return base::HexEncode(GetConstData(), GetLength()); |
| 62 | } |
| 63 | |
Paul Stewart | 3ecfa2b | 2011-07-15 10:47:42 -0700 | [diff] [blame] | 64 | } // namespace shill |