1 /* 2 * Copyright (C) 2020 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #include <libnl++/Attributes.h> 18 19 namespace android::nl { 20 Attributes()21Attributes::Attributes() {} 22 Attributes(Buffer<nlattr> buffer)23Attributes::Attributes(Buffer<nlattr> buffer) : Buffer<nlattr>(buffer) {} 24 index() const25const Attributes::Index& Attributes::index() const { 26 if (mIndex.has_value()) return *mIndex; 27 28 mIndex = Index(); 29 auto& index = *mIndex; 30 31 for (auto attr : static_cast<Buffer<nlattr>>(*this)) { 32 index.emplace(attr->nla_type, attr); 33 } 34 35 return index; 36 } 37 contains(nlattrtype_t attrtype) const38bool Attributes::contains(nlattrtype_t attrtype) const { 39 return index().count(attrtype) > 0; 40 } 41 42 /* Parser specializations for selected types (more to come if necessary). */ 43 44 template <> parse(Buffer<nlattr> buf)45Attributes Attributes::parse(Buffer<nlattr> buf) { 46 return buf.data<nlattr>(); 47 } 48 49 template <> parse(Buffer<nlattr> buf)50std::string Attributes::parse(Buffer<nlattr> buf) { 51 const auto rawString = buf.data<char>().getRaw(); 52 std::string str(rawString.ptr(), rawString.len()); 53 54 str.erase(std::find(str.begin(), str.end(), '\0'), str.end()); 55 56 return str; 57 } 58 59 template <typename T> parseUnsigned(Buffer<nlattr> buf)60static T parseUnsigned(Buffer<nlattr> buf) { 61 return buf.data<T>().copyFirst(); 62 } 63 64 template <> parse(Buffer<nlattr> buf)65uint8_t Attributes::parse(Buffer<nlattr> buf) { 66 return parseUnsigned<uint8_t>(buf); 67 } 68 69 template <> parse(Buffer<nlattr> buf)70uint16_t Attributes::parse(Buffer<nlattr> buf) { 71 return parseUnsigned<uint16_t>(buf); 72 } 73 74 template <> parse(Buffer<nlattr> buf)75uint32_t Attributes::parse(Buffer<nlattr> buf) { 76 return parseUnsigned<uint32_t>(buf); 77 } 78 79 template <> parse(Buffer<nlattr> buf)80uint64_t Attributes::parse(Buffer<nlattr> buf) { 81 return parseUnsigned<uint64_t>(buf); 82 } 83 84 } // namespace android::nl 85