1
0
Fork 0

use callbacks to send the byte stream

This commit is contained in:
Kevin Matz 2023-05-15 11:28:39 -04:00
parent 0bd30d1151
commit fdf801c962
2 changed files with 38 additions and 4 deletions

View File

@ -39,4 +39,34 @@ Sender::~Sender()
}
/**
* @brief Sender::send
* @param msg
*/
void Sender::send(std::shared_ptr<Message> msg) const
{
auto buffer = std::vector<uint8_t>(msg->streamSize());
auto stream = std::make_shared<bufferstream>(buffer.data(), buffer.size());
msg->oStream(stream);
if (auto sp = sender_.lock()) // the owner is still holding the token
(*sp)(stream);
}
/**
* @brief Sender::setSender
* @param cb
* @return
*/
std::shared_ptr<void> Sender::setSender(const std::function<void(std::shared_ptr<bufferstream>)> cb)
{
// wrap the callback with a shared pointer
auto sp = std::make_shared<std::function<void(std::shared_ptr<bufferstream>)>>(std::move(cb));
// store sender function (as a weak pointer)
sender_ = sp;
// return token that caller must keep throughout it's scope
return sp;
}
} // namespace OSC

View File

@ -23,6 +23,8 @@
*/
#pragma once
#include <bufferstream.h>
#include <functional>
#include <memory>
#include "message.h"
@ -40,10 +42,12 @@ public:
explicit Sender();
virtual ~Sender();
/**
* @brief send
*/
virtual void send(std::shared_ptr<Message>) = 0;
void send(std::shared_ptr<Message>) const;
std::shared_ptr<void> setSender(const std::function<void(std::shared_ptr<bufferstream>)>);
private:
std::weak_ptr<const std::function<void(std::shared_ptr<bufferstream>)>> sender_;
};
} // namespace OSC