5#include "../Foundation/AlignedStorage.h"
6#include "../Foundation/Function.h"
7#include "../Foundation/Internal/IGrowableBuffer.h"
8#include "../Foundation/Result.h"
9#include "../Foundation/Span.h"
10#include "Internal/CircularQueue.h"
11#include "Internal/Event.h"
51 struct SC_COMPILER_EXPORT
ID
55 static constexpr NumericType InvalidValue = -1;
57 NumericType identifier;
59 constexpr ID() : identifier(InvalidValue) {}
60 explicit constexpr ID(
int32_t value) : identifier(value) {}
62 [[nodiscard]]
constexpr bool isValid()
const {
return identifier != InvalidValue; }
63 [[nodiscard]]
constexpr bool operator==(
ID other)
const {
return identifier == other.identifier; }
74 AsyncBufferView() : writableData(), offset(0), length(0), refs(0), type(Type::Empty), reUse(false) {}
75 AsyncBufferView(Span<char> data) : writableData(data)
77 type = Type::Writable;
79 length = data.sizeInBytes();
82 AsyncBufferView(Span<const char> data) : readonlyData(data)
84 type = Type::ReadOnly;
86 length = data.sizeInBytes();
99 type = Type::Growable;
106 getGrowableBuffer = [t = forward<T>(t)](
GrowableStorage& storage,
bool construct)
mutable -> IGrowableBuffer*
108 using Type =
typename TypeTraits::RemoveReference<T>::type;
111 placementNew(storage.reinterpret_as<GrowableBuffer<Type>>(), t);
112 return &storage.reinterpret_as<GrowableBuffer<Type>>();
116 dtor(storage.reinterpret_as<GrowableBuffer<Type>>());
125 readonlyData = {literal, N - 1};
126 type = Type::ReadOnly;
131 Type getType()
const {
return type; }
134#if SC_PLATFORM_64_BIT
135 static constexpr int TypeErasedCaptureSize =
sizeof(
void*) * 3;
137 static constexpr int TypeErasedCaptureSize =
sizeof(
void*) * 6;
139 static constexpr int TypeErasedGrowableSize =
sizeof(
void*) * 6;
141 using GrowableStorage = AlignedStorage<TypeErasedGrowableSize>;
142 Function<IGrowableBuffer*(GrowableStorage&, bool), TypeErasedCaptureSize> getGrowableBuffer;
146 Span<char> writableData;
147 Span<const char> readonlyData;
149 AsyncBufferView::ID parentID;
151 friend struct AsyncBuffersPool;
156 Type type = Type::Empty;
196 [[nodiscard]]
size_t getNumBuffers()
const {
return buffers.sizeInElements(); }
220 static constexpr int MaxListeners = 8;
222 Event<MaxListeners, Result> eventError;
246 [[nodiscard]]
bool isEnded()
const {
return state == State::Ended; }
318 State state = State::Stopped;
320 bool destroyed =
false;
321 bool autoDestroy =
true;
325 CircularQueue<Request> readQueue;
344 static constexpr int MaxListeners = 8;
346 Event<MaxListeners, Result> eventError;
402 [[nodiscard]]
bool isStillWriting()
const {
return state == State::Writing or state == State::Ending; }
431 void stop() { state = State::Stopped; }
443 State state = State::Stopped;
445 bool destroyed =
false;
446 bool autoDestroy =
true;
448 AsyncBuffersPool* buffers =
nullptr;
450 CircularQueue<Request> writeQueue;
470 void afterFinalize(
Span<char> outputAfter,
bool streamEnded);
477 virtual bool canEndWritable()
override;
499 State state = State::None;
511 static constexpr int MaxListeners = 8;
512 static constexpr int MaxTransforms = 8;
513 static constexpr int MaxSinks = 8;
525 Event<MaxListeners, Result> eventError = {};
540 void emitError(
Result res);
541 Result checkBuffersPool();
unsigned char uint8_t
Platform independent (1) byte unsigned int.
Definition PrimitiveTypes.h:36
int int32_t
Platform independent (4) bytes signed int.
Definition PrimitiveTypes.h:46
struct SC_COMPILER_EXPORT Function
Wraps function pointers, member functions and lambdas without ever allocating.
Definition Function.h:19
A buffer of bytes with given alignment.
Definition AlignedStorage.h:29
Definition AsyncStreams.h:52
A Span of bytes memory to be read or written by async streams.
Definition AsyncStreams.h:50
AsyncBufferView(T &&t)
Saves a copy (or a moved instance) of a String / Buffer (or anything that works with GrowableBuffer<T...
Definition AsyncStreams.h:97
void setReusable(bool reusable)
Tags this AsyncBufferView as reusable after its refCount goes to zero.
Definition AsyncStreams.h:91
Holds a Span of AsyncBufferView (allocated by user) holding available memory for the streams.
Definition AsyncStreams.h:163
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:193
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:196
A stream that can both produce and consume buffers.
Definition AsyncStreams.h:455
virtual Result asyncRead() override
Function that every stream must define to implement its custom read operation.
Pipes read data from SC::AsyncReadableStream, forwarding them to SC::AsyncWritableStream.
Definition AsyncStreams.h:510
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:216
Async source abstraction emitting data events in caller provided byte buffers.
Definition AsyncStreams.h:214
bool getAutoDestroy() const
Returns true if stream will automatically call .destroy() when Ended state is reached.
Definition AsyncStreams.h:284
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:224
bool hasBeenDestroyed() const
Returns true if the stream has been already destroyed (asynchronously through destroy())
Definition AsyncStreams.h:249
Result finishedDestroyingReadable()
Called from inside asyncDestroy to transition from Destroying to Destroyed state (emitting eventClose...
Event< MaxListeners > eventClose
Emitted when there is no more data.
Definition AsyncStreams.h:225
Event< MaxListeners, AsyncBufferView::ID > eventData
Emitted when an error occurs.
Definition AsyncStreams.h:223
AsyncBuffersPool & getBuffersPool()
Obtains the AsyncBuffersPool to request more buffers.
size_t getReadQueueSize() const
Returns the size of read queue.
Definition AsyncStreams.h:258
void setAutoDestroy(bool value)
If set to true will automatically call .destroy() when Ended state is reached.
Definition AsyncStreams.h:281
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:246
constexpr void setReadQueue(Span< Request > requests)
Sets the read queue for this readable stream.
Definition AsyncStreams.h:255
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)
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.
Definition AsyncStreams.h:339
Async destination abstraction where bytes can be written to.
Definition AsyncStreams.h:337
size_t getWriteQueueSize() const
Returns the size of write queue.
Definition AsyncStreams.h:361
Event< MaxListeners > eventFinish
Emitted when write queue is empty.
Definition AsyncStreams.h:349
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:348
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:402
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:408
bool hasBeenDestroyed() const
Returns true if the stream has been already destroyed (asynchronously through destroy())
Definition AsyncStreams.h:405
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:411
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:350
constexpr void setWriteQueue(Span< Request > requests)
Sets the write queue for this writable stream.
Definition AsyncStreams.h:358
An ascii string used as boolean result. SC_TRY macro forwards errors to caller.
Definition Result.h:13
View over a contiguous sequence of items (pointer + size in elements).
Definition Span.h:29