1 /*
2 * Copyright (c) 2022 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/rx/reassembly_streams.h"
11
12 #include <cstddef>
13 #include <map>
14 #include <utility>
15
16 namespace dcsctp {
17
AssembleMessage(std::map<UnwrappedTSN,Data>::iterator start,std::map<UnwrappedTSN,Data>::iterator end)18 ReassembledMessage AssembleMessage(std::map<UnwrappedTSN, Data>::iterator start,
19 std::map<UnwrappedTSN, Data>::iterator end) {
20 size_t count = std::distance(start, end);
21
22 if (count == 1) {
23 // Fast path - zero-copy
24 Data& data = start->second;
25
26 return ReassembledMessage{
27 .tsns = {start->first},
28 .message = DcSctpMessage(data.stream_id, data.ppid,
29 std::move(start->second.payload)),
30 };
31 }
32
33 // Slow path - will need to concatenate the payload.
34 std::vector<UnwrappedTSN> tsns;
35 std::vector<uint8_t> payload;
36
37 size_t payload_size = std::accumulate(
38 start, end, 0,
39 [](size_t v, const auto& p) { return v + p.second.size(); });
40
41 tsns.reserve(count);
42 payload.reserve(payload_size);
43 for (auto it = start; it != end; ++it) {
44 Data& data = it->second;
45 tsns.push_back(it->first);
46 payload.insert(payload.end(), data.payload.begin(), data.payload.end());
47 }
48
49 return ReassembledMessage{
50 .tsns = std::move(tsns),
51 .message = DcSctpMessage(start->second.stream_id, start->second.ppid,
52 std::move(payload)),
53 };
54 }
55 } // namespace dcsctp
56