xref: /aosp_15_r20/external/webrtc/net/dcsctp/packet/error_cause/user_initiated_abort_cause.cc (revision d9f758449e529ab9291ac668be2861e7a55c2422)
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 #include "net/dcsctp/packet/error_cause/user_initiated_abort_cause.h"
11 
12 #include <stdint.h>
13 
14 #include <string>
15 #include <type_traits>
16 #include <vector>
17 
18 #include "absl/types/optional.h"
19 #include "api/array_view.h"
20 #include "net/dcsctp/packet/bounded_byte_reader.h"
21 #include "net/dcsctp/packet/bounded_byte_writer.h"
22 #include "net/dcsctp/packet/tlv_trait.h"
23 #include "rtc_base/strings/string_builder.h"
24 
25 namespace dcsctp {
26 
27 // https://tools.ietf.org/html/rfc4960#section-3.3.10.12
28 
29 //   0                   1                   2                   3
30 //   0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
31 //  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
32 //  |         Cause Code=12         |      Cause Length=Variable    |
33 //  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
34 //  /                    Upper Layer Abort Reason                   /
35 //  \                                                               \
36 //  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
37 constexpr int UserInitiatedAbortCause::kType;
38 
Parse(rtc::ArrayView<const uint8_t> data)39 absl::optional<UserInitiatedAbortCause> UserInitiatedAbortCause::Parse(
40     rtc::ArrayView<const uint8_t> data) {
41   absl::optional<BoundedByteReader<kHeaderSize>> reader = ParseTLV(data);
42   if (!reader.has_value()) {
43     return absl::nullopt;
44   }
45   if (reader->variable_data().empty()) {
46     return UserInitiatedAbortCause("");
47   }
48   return UserInitiatedAbortCause(
49       std::string(reinterpret_cast<const char*>(reader->variable_data().data()),
50                   reader->variable_data().size()));
51 }
52 
SerializeTo(std::vector<uint8_t> & out) const53 void UserInitiatedAbortCause::SerializeTo(std::vector<uint8_t>& out) const {
54   BoundedByteWriter<kHeaderSize> writer =
55       AllocateTLV(out, upper_layer_abort_reason_.size());
56   writer.CopyToVariableData(rtc::MakeArrayView(
57       reinterpret_cast<const uint8_t*>(upper_layer_abort_reason_.data()),
58       upper_layer_abort_reason_.size()));
59 }
60 
ToString() const61 std::string UserInitiatedAbortCause::ToString() const {
62   rtc::StringBuilder sb;
63   sb << "User-Initiated Abort, reason=" << upper_layer_abort_reason_;
64   return sb.Release();
65 }
66 
67 }  // namespace dcsctp
68