5#include "../Common/CompilerMacrosExport.h"
6#include "../Common/PlatformMacrosInstructionSet.h"
7#ifndef SC_EXPORT_LIBRARY_ASYNC_STREAMS
8#define SC_EXPORT_LIBRARY_ASYNC_STREAMS 0
10#define SC_ASYNC_STREAMS_EXPORT SC_COMPILER_LIBRARY_EXPORT(SC_EXPORT_LIBRARY_ASYNC_STREAMS)
12#include "../Common/AlignedStorage.h"
13#include "../Common/Assert.h"
14#include "../Common/Function.h"
15#include "../Common/IGrowableBufferSpan.h"
16#include "../Common/PlatformMacrosInstructionSet.h"
17#include "../Common/Result.h"
18#include "../Common/Span.h"
19#include "Internal/CircularQueue.h"
20#include "Internal/Event.h"
56SC_DECLARE_ASSERT_PROVIDER(AsyncStreamsAssert, SC_ASYNC_STREAMS_EXPORT);
58#define SC_ASYNC_STREAMS_ASSERT_RELEASE(e) SC_ASSERT_PROVIDER_RELEASE(SC::AsyncStreamsAssert, e)
59#define SC_ASYNC_STREAMS_ASSERT_DEBUG(e) SC_ASSERT_PROVIDER_DEBUG(SC::AsyncStreamsAssert, e)
60#define SC_ASYNC_STREAMS_TRUST_RESULT(expression) SC_ASYNC_STREAMS_ASSERT_RELEASE(expression)
65 struct SC_ASYNC_STREAMS_EXPORT
ID
67 using NumericType = int32_t;
69 static constexpr NumericType InvalidValue = -1;
71 NumericType identifier;
73 constexpr ID() : identifier(InvalidValue) {}
74 explicit constexpr ID(int32_t value) : identifier(value) {}
76 [[nodiscard]]
constexpr bool isValid()
const {
return identifier != InvalidValue; }
77 [[nodiscard]]
constexpr bool operator==(
ID other)
const {
return identifier == other.identifier; }
79 enum class Type : uint8_t
88 AsyncBufferView() : writableData(), offset(0), length(0), refs(0), type(Type::Empty), reUse(false) {}
89 AsyncBufferView(Span<char> data) : writableData(data)
91 type = Type::Writable;
93 length = data.sizeInBytes();
96 AsyncBufferView(Span<const char> data) : readonlyData(data)
98 type = Type::ReadOnly;
100 length = data.sizeInBytes();
110 template <
typename T>
113 type = Type::Growable;
120 getGrowableBuffer = [t = forward<T>(t)](GrowableStorage& storage,
bool construct)
mutable -> IGrowableBuffer*
122 using Type =
typename TypeTraits::RemoveReference<T>::type;
125 placementNew(storage.reinterpret_as<GrowableBuffer<Type>>(), t);
126 return &storage.reinterpret_as<GrowableBuffer<Type>>();
130 dtor(storage.reinterpret_as<GrowableBuffer<Type>>());
139 readonlyData = {literal, N - 1};
140 type = Type::ReadOnly;
145 Type getType()
const {
return type; }
148#if SC_PLATFORM_64_BIT
149 static constexpr int TypeErasedCaptureSize =
sizeof(
void*) * 3;
151 static constexpr int TypeErasedCaptureSize =
sizeof(
void*) * 6;
153 static constexpr int TypeErasedGrowableSize =
sizeof(
void*) * 6;
155 using GrowableStorage = AlignedStorage<TypeErasedGrowableSize>;
156 Function<IGrowableBuffer*(GrowableStorage&, bool), TypeErasedCaptureSize> getGrowableBuffer;
160 Span<char> writableData;
161 Span<const char> readonlyData;
163 AsyncBufferView::ID parentID;
165 friend struct AsyncBuffersPool;
170 Type type = Type::Empty;
204 static Result
sliceInEqualParts(Span<AsyncBufferView> buffers, Span<char> memory,
size_t numSlices);
207 void setBuffers(Span<AsyncBufferView> newBuffers) { buffers = newBuffers; }
210 [[nodiscard]]
size_t getNumBuffers()
const {
return buffers.sizeInElements(); }
218 Span<AsyncBufferView> buffers;
237 static constexpr int MaxListeners = 8;
239 Event<MaxListeners, Result> eventError;
263 [[nodiscard]]
bool isEnded()
const {
return state == State::Ended; }
266 [[nodiscard]]
bool hasQueuedData()
const {
return not readQueue.isEmpty(); }
272 [[nodiscard]]
bool canStart()
const {
return state == State::CanRead; }
278 constexpr void setReadQueue(Span<Request> requests) { readQueue = requests; }
326 void maybeDestroyEndedReadable();
330 enum class State : uint8_t
345 State state = State::Stopped;
347 bool destroyed =
false;
348 bool autoDestroy =
true;
352 CircularQueue<Request> readQueue;
376 static constexpr int MaxListeners = 8;
378 Event<MaxListeners, Result> eventError;
390 constexpr void setWriteQueue(Span<Request> requests) { writeQueue = requests; }
434 [[nodiscard]]
bool isStillWriting()
const {
return state == State::Writing or state == State::Ending; }
463 void stop() { state = State::Stopped; }
466 [[nodiscard]]
bool canAcceptWrite()
const
468 return (state == State::Stopped or state == State::Writing) and not writeQueue.isFull();
471 enum class State : uint8_t
480 State state = State::Stopped;
482 bool destroyed =
false;
483 bool autoDestroy =
true;
485 AsyncBuffersPool* buffers =
nullptr;
487 CircularQueue<Request> writeQueue;
495 Result init(
AsyncBuffersPool& buffersPool, Span<AsyncReadableStream::Request> readableRequests,
496 Span<AsyncWritableStream::Request> writableRequests);
506 void afterProcess(Span<const char> inputAfter, Span<char> outputAfter);
507 void afterFinalize(Span<char> outputAfter,
bool streamEnded);
509 virtual Result onProcess(Span<const char>, Span<char>) = 0;
510 virtual Result onFinalize(Span<char>) = 0;
514 virtual bool canEndWritable()
override;
518 Span<const char> inputData;
519 Span<char> outputData;
536 State state = State::None;
559 static constexpr int MaxListeners = 8;
560 static constexpr int MaxTransforms = 8;
561 static constexpr int MaxSinks = 8;
573 Event<MaxListeners, Result> eventError = {};
596 PendingWrite pendingWrites[MaxTransforms + MaxSinks] = {};
597 bool shouldEndWhenDrained =
false;
598 bool endingPipes =
false;
602 void emitError(Result res);
603 Result checkBuffersPool();
613 bool retryPendingWrites();
614 bool hasPendingWrites()
const;
616 void releasePendingWrites();
Definition AsyncStreams.h:66
A Span of bytes memory to be read or written by async streams.
Definition AsyncStreams.h:64
AsyncBufferView(T &&t)
Saves a copy (or a moved instance) of a String / Buffer (or anything that works with GrowableBuffer<T...
Definition AsyncStreams.h:111
void setReusable(bool reusable)
Tags this AsyncBufferView as reusable after its refCount goes to zero.
Definition AsyncStreams.h:105
Holds a Span of AsyncBufferView (allocated by user) holding available memory for the streams.
Definition AsyncStreams.h:177
Result getReadableData(AsyncBufferView::ID bufferID, Span< const char > &data)
Access data span owned by the buffer.
void setBuffers(Span< AsyncBufferView > newBuffers)
Sets memory for the new buffers.
Definition AsyncStreams.h:207
void refBuffer(AsyncBufferView::ID bufferID)
Increments a buffer reference count.
AsyncBufferView * getBuffer(AsyncBufferView::ID bufferID)
Access the raw AsyncBufferView (if any) at a given bufferID (or nullptr if invalid)
Result createChildView(AsyncBufferView::ID parentBufferID, size_t offset, size_t length, AsyncBufferView::ID &outChildBufferID)
Creates a child view that references a slice of the parent buffer.
void setNewBufferSize(AsyncBufferView::ID bufferID, size_t newSizeInBytes)
Sets the new size in bytes for the buffer.
Result getWritableData(AsyncBufferView::ID bufferID, Span< char > &data)
Access data span owned by the buffer.
static Result sliceInEqualParts(Span< AsyncBufferView > buffers, Span< char > memory, size_t numSlices)
Splits a span of memory in equally sized slices, assigning them to buffers and marking them as reusab...
Result requestNewBuffer(size_t minimumSizeInBytes, AsyncBufferView::ID &bufferID, Span< char > &data)
Requests a new available buffer that is at least minimumSizeInBytes, incrementing its refcount.
Result pushBuffer(AsyncBufferView &&buffer, AsyncBufferView::ID &bufferID)
Adds a buffer to the pool in any empty slot (found by scanning from start to end)
void unrefBuffer(AsyncBufferView::ID bufferID)
Decrements a buffer reference count.
size_t getNumBuffers() const
Gets size of buffers held by the pool.
Definition AsyncStreams.h:210
A stream that can both produce and consume buffers.
Definition AsyncStreams.h:492
virtual Result asyncRead() override
Function that every stream must define to implement its custom read operation.
Definition AsyncStreams.h:591
Pipes read data from SC::AsyncReadableStream, forwarding them to SC::AsyncWritableStream.
Definition AsyncStreams.h:558
Result pipe()
Reports errors by source, transforms or sinks.
bool unpipe()
Unregisters all events from source, transforms and sinks.
Result start()
Starts the pipeline.
Definition AsyncStreams.h:233
Async source abstraction emitting data events in caller provided byte buffers.
Definition AsyncStreams.h:228
bool getAutoDestroy() const
Returns true if stream will automatically call .destroy() when Ended state is reached.
Definition AsyncStreams.h:307
void pushEnd()
Use pushEnd from inside AsyncReadableStream::asyncRead to signal production end.
void emitError(Result error)
Signals an async error received.
void resumeReading()
Resumes the readable stream paused by AsyncReadableStream::pause.
bool push(AsyncBufferView::ID bufferID, size_t newSize)
Use push from inside AsyncReadableStream::asyncRead function to queue received data.
Event< MaxListeners > eventEnd
Emitted when a new buffer has been read.
Definition AsyncStreams.h:241
bool hasBeenDestroyed() const
Returns true if the stream has been already destroyed (asynchronously through destroy())
Definition AsyncStreams.h:269
Result finishedDestroyingReadable()
Called from inside asyncDestroy to transition from Destroying to Destroyed state (emitting eventClose...
virtual Result asyncResumeReading()
Function that streams may define to resume an already pending async read.
bool hasQueuedData() const
Returns true if there are buffered reads waiting to be emitted.
Definition AsyncStreams.h:266
Event< MaxListeners > eventClose
Emitted when there is no more data.
Definition AsyncStreams.h:242
Event< MaxListeners, AsyncBufferView::ID > eventData
Emitted when an error occurs.
Definition AsyncStreams.h:240
AsyncBuffersPool & getBuffersPool()
Obtains the AsyncBuffersPool to request more buffers.
size_t getReadQueueSize() const
Returns the size of read queue.
Definition AsyncStreams.h:281
void setAutoDestroy(bool value)
If set to true will automatically call .destroy() when Ended state is reached.
Definition AsyncStreams.h:304
virtual Result asyncDestroyReadable()
Function that a readable stream can re-implement to release its internal resources.
void destroy()
Forcefully destroys the readable stream before calling end event releasing all resources.
virtual Result asyncRead()=0
Function that every stream must define to implement its custom read operation.
bool getBufferOrPause(size_t minumumSizeInBytes, AsyncBufferView::ID &bufferID, Span< char > &data)
Returns an unused buffer from pool or pauses the stream if none is available.
bool isEnded() const
Returns true if the stream is ended (AsyncReadableStream::end has been called)
Definition AsyncStreams.h:263
constexpr void setReadQueue(Span< Request > requests)
Sets the read queue for this readable stream.
Definition AsyncStreams.h:278
Result init(AsyncBuffersPool &buffersPool)
Emitted when the underlying resource has been closed.
void reactivate(bool doReactivate)
Use reactivate(true) from inside AsyncReadableStream::asyncRead function to ask the state machine to ...
void pause()
Pauses the readable stream (that can be later resumed)
bool canStart() const
Returns true when start() is currently valid for this stream.
Definition AsyncStreams.h:272
Result unshift(AsyncBufferView::ID bufferID)
Push back a buffer to the front of the read queue (e.g. for un-consumed data)
Result start()
Starts the readable stream, that will emit eventData.
Traits exposing AsyncStreams public types through a single template parameter.
Definition AsyncStreams.h:542
Definition AsyncStreams.h:371
Async destination abstraction where bytes can be written to.
Definition AsyncStreams.h:364
size_t getWriteQueueSize() const
Returns the size of write queue.
Definition AsyncStreams.h:393
Event< MaxListeners > eventFinish
Emitted when write queue is empty.
Definition AsyncStreams.h:381
Result write(AsyncBufferView::ID bufferID, Function< void(AsyncBufferView::ID)> cb={})
Writes a buffer (that must be allocated by the AsyncBuffersPool passed in AsyncWritableStream) When t...
void end()
Ends the writable stream, waiting for all in-flight and queued writes to finish.
void destroy()
Forcefully destroys the writable stream before calling end event releasing all resources.
void emitError(Result error)
Signals an async error received.
void finishedDestroyingWritable()
Function that MUST be called by re-implementations of asyncDestroyWritable once they're done.
Event< MaxListeners > eventDrain
Emitted when an error occurs.
Definition AsyncStreams.h:380
virtual bool canEndWritable()
Allows keeping a writable in ENDING state until it has finished flushing all pending data.
virtual Result asyncWrite(AsyncBufferView::ID, Function< void(AsyncBufferView::ID)> func)=0
Function that every stream must define to implement its custom write operation.
bool isStillWriting() const
Returns true if this stream is writing something.
Definition AsyncStreams.h:434
void resumeWriting()
Resumes writing queued requests for this stream.
virtual Result asyncDestroyWritable()
Function that a writable stream can re-implement to release its internal resources.
void setAutoDestroy(bool value)
If set to true will automatically call .destroy() when Ended state is reached.
Definition AsyncStreams.h:440
bool hasBeenDestroyed() const
Returns true if the stream has been already destroyed (asynchronously through destroy())
Definition AsyncStreams.h:437
Result init(AsyncBuffersPool &buffersPool)
Emitted when the underlying resource has been closed.
void finishedWriting(AsyncBufferView::ID bufferID, Function< void(AsyncBufferView::ID)> &&cb, Result res)
Signals that the given buffer (previously queued by write) has been fully written.
bool getAutoDestroy() const
Returns true if stream will automatically call .destroy() when Ended state is reached.
Definition AsyncStreams.h:443
void tryAsync(Result potentialError)
Will emit error if the passed in Result is false.
Result unshift(AsyncBufferView::ID bufferID, Function< void(AsyncBufferView::ID)> &&cb)
Puts back a buffer at the top of the write queue.
Result write(AsyncBufferView &&bufferView, Function< void(AsyncBufferView::ID)> cb={})
Push a new buffer view to the queue, registering it with the allocator.
AsyncBuffersPool & getBuffersPool()
Obtains the buffers pool to access its data.
Event< MaxListeners > eventClose
Emitted when no more data can be written.
Definition AsyncStreams.h:382
constexpr void setWriteQueue(Span< Request > requests)
Sets the write queue for this writable stream.
Definition AsyncStreams.h:390