InStream/OutStream
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
#include <c_FileOutputStream.h>
|
||||
|
||||
typedef struct {
|
||||
c_OutStream_t base;
|
||||
FILE* fp;
|
||||
c_Allocator_t allocator;
|
||||
} c_FileOutImpl_t;
|
||||
|
||||
static c_err_t _FileOut_Write(c_OutStream_t* self, const void* buf, c_size_t len, c_size_t* written) {
|
||||
c_FileOutImpl_t* impl = (c_FileOutImpl_t*)self;
|
||||
if (!impl->fp || !buf || len == 0) return C_ERR_PARAM;
|
||||
c_size_t items = fwrite(buf, 1, (size_t)len, impl->fp);
|
||||
if (written) *written = items;
|
||||
return (items == len) ? C_SUCCESS : C_ERR_FAIL;
|
||||
}
|
||||
|
||||
static c_err_t _FileOut_Flush(c_OutStream_t* self) {
|
||||
c_FileOutImpl_t* impl = (c_FileOutImpl_t*)self;
|
||||
return (fflush(impl->fp) == 0) ? C_SUCCESS : C_ERR_FAIL;
|
||||
}
|
||||
|
||||
static void _FileOut_Destroy(c_OutStream_t* self) {
|
||||
c_FileOutImpl_t* impl = (c_FileOutImpl_t*)self;
|
||||
c_Allocator_t alloc = impl->allocator;
|
||||
c_Allocator_Free(&alloc, impl);
|
||||
}
|
||||
|
||||
static const c_OutStreamVtbl_t g_FileOutVtbl = { _FileOut_Write, _FileOut_Flush, _FileOut_Destroy };
|
||||
|
||||
c_err_t c_FileOutputStream_Create(c_OutStream_t** out_stream, FILE* file_handle, c_Allocator_t* allocator) {
|
||||
if (!out_stream || !file_handle) return C_ERR_PARAM;
|
||||
c_Allocator_t alloc = allocator ? *allocator : c_DefaultAllocator;
|
||||
c_FileOutImpl_t* impl = (c_FileOutImpl_t*)c_Allocator_Calloc(&alloc, 1, sizeof(c_FileOutImpl_t));
|
||||
if (!impl) return C_ERR_NOMEM;
|
||||
impl->base.vtbl = &g_FileOutVtbl;
|
||||
impl->fp = file_handle;
|
||||
impl->allocator = alloc;
|
||||
*out_stream = &impl->base;
|
||||
return C_SUCCESS;
|
||||
}
|
||||
Reference in New Issue
Block a user