1 /* 2 * Copyright (c) 2021 The WebRTC project authors. All Rights Reserved. 3 * 4 * Use of this source code is governed by a BSD-style license 5 * that can be found in the LICENSE file in the root of the source 6 * tree. An additional intellectual property rights grant can be found 7 * in the file PATENTS. All contributing project authors may 8 * be found in the AUTHORS file in the root of the source tree. 9 */ 10 #ifndef NET_DCSCTP_PACKET_PARAMETER_PARAMETER_H_ 11 #define NET_DCSCTP_PACKET_PARAMETER_PARAMETER_H_ 12 13 #include <stddef.h> 14 15 #include <algorithm> 16 #include <cstdint> 17 #include <iterator> 18 #include <memory> 19 #include <string> 20 #include <type_traits> 21 #include <utility> 22 #include <vector> 23 24 #include "absl/algorithm/container.h" 25 #include "absl/strings/string_view.h" 26 #include "absl/types/optional.h" 27 #include "api/array_view.h" 28 #include "net/dcsctp/packet/tlv_trait.h" 29 #include "rtc_base/strings/string_builder.h" 30 31 namespace dcsctp { 32 33 class Parameter { 34 public: Parameter()35 Parameter() {} 36 virtual ~Parameter() = default; 37 38 Parameter(const Parameter& other) = default; 39 Parameter& operator=(const Parameter& other) = default; 40 41 virtual void SerializeTo(std::vector<uint8_t>& out) const = 0; 42 virtual std::string ToString() const = 0; 43 }; 44 45 struct ParameterDescriptor { ParameterDescriptorParameterDescriptor46 ParameterDescriptor(uint16_t type, rtc::ArrayView<const uint8_t> data) 47 : type(type), data(data) {} 48 uint16_t type; 49 rtc::ArrayView<const uint8_t> data; 50 }; 51 52 class Parameters { 53 public: 54 class Builder { 55 public: Builder()56 Builder() {} 57 Builder& Add(const Parameter& p); Build()58 Parameters Build() { return Parameters(std::move(data_)); } 59 60 private: 61 std::vector<uint8_t> data_; 62 }; 63 64 static absl::optional<Parameters> Parse(rtc::ArrayView<const uint8_t> data); 65 Parameters()66 Parameters() {} 67 Parameters(Parameters&& other) = default; 68 Parameters& operator=(Parameters&& other) = default; 69 data()70 rtc::ArrayView<const uint8_t> data() const { return data_; } 71 std::vector<ParameterDescriptor> descriptors() const; 72 73 template <typename P> get()74 absl::optional<P> get() const { 75 static_assert(std::is_base_of<Parameter, P>::value, 76 "Template parameter not derived from Parameter"); 77 for (const auto& p : descriptors()) { 78 if (p.type == P::kType) { 79 return P::Parse(p.data); 80 } 81 } 82 return absl::nullopt; 83 } 84 85 private: Parameters(std::vector<uint8_t> data)86 explicit Parameters(std::vector<uint8_t> data) : data_(std::move(data)) {} 87 std::vector<uint8_t> data_; 88 }; 89 90 struct ParameterConfig { 91 static constexpr int kTypeSizeInBytes = 2; 92 }; 93 94 } // namespace dcsctp 95 96 #endif // NET_DCSCTP_PACKET_PARAMETER_PARAMETER_H_ 97