datachannel.hpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /**
  2. * Copyright (c) 2019 Paul-Louis Ageneau
  3. *
  4. * This Source Code Form is subject to the terms of the Mozilla Public
  5. * License, v. 2.0. If a copy of the MPL was not distributed with this
  6. * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  7. */
  8. #ifndef RTC_DATA_CHANNEL_H
  9. #define RTC_DATA_CHANNEL_H
  10. #include "channel.hpp"
  11. #include "common.hpp"
  12. #include "reliability.hpp"
  13. #include <type_traits>
  14. namespace rtc {
  15. namespace impl {
  16. struct DataChannel;
  17. struct PeerConnection;
  18. } // namespace impl
  19. class RTC_CPP_EXPORT DataChannel final : private CheshireCat<impl::DataChannel>, public Channel {
  20. public:
  21. DataChannel(impl_ptr<impl::DataChannel> impl);
  22. ~DataChannel() override;
  23. optional<uint16_t> stream() const;
  24. optional<uint16_t> id() const;
  25. string label() const;
  26. string protocol() const;
  27. Reliability reliability() const;
  28. bool isOpen(void) const override;
  29. bool isClosed(void) const override;
  30. size_t maxMessageSize() const override;
  31. void close(void) override;
  32. bool send(message_variant data) override;
  33. bool send(const byte *data, size_t size) override;
  34. template <typename Buffer> bool sendBuffer(const Buffer &buf);
  35. template <typename Iterator> bool sendBuffer(Iterator first, Iterator last);
  36. private:
  37. using CheshireCat<impl::DataChannel>::impl;
  38. };
  39. template <typename Buffer> std::pair<const byte *, size_t> to_bytes(const Buffer &buf) {
  40. using T = typename std::remove_pointer<decltype(buf.data())>::type;
  41. using E = typename std::conditional<std::is_void<T>::value, byte, T>::type;
  42. return std::make_pair(static_cast<const byte *>(static_cast<const void *>(buf.data())),
  43. buf.size() * sizeof(E));
  44. }
  45. template <typename Buffer> bool DataChannel::sendBuffer(const Buffer &buf) {
  46. auto [bytes, size] = to_bytes(buf);
  47. return send(bytes, size);
  48. }
  49. template <typename Iterator> bool DataChannel::sendBuffer(Iterator first, Iterator last) {
  50. size_t size = 0;
  51. for (Iterator it = first; it != last; ++it)
  52. size += it->size();
  53. binary buffer(size);
  54. byte *pos = buffer.data();
  55. for (Iterator it = first; it != last; ++it) {
  56. auto [bytes, len] = to_bytes(*it);
  57. pos = std::copy(bytes, bytes + len, pos);
  58. }
  59. return send(std::move(buffer));
  60. }
  61. } // namespace rtc
  62. #endif