InStream/OutStream
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
#include <c_FileInputStream.h>
|
||||
|
||||
typedef struct {
|
||||
c_InStream_t base;
|
||||
FILE* fp;
|
||||
c_Allocator_t allocator;
|
||||
} c_FileInImpl_t;
|
||||
|
||||
static c_err_t _FileIn_Read(c_InStream_t* self, void* buf, c_size_t len, c_size_t* bytes_read) {
|
||||
c_FileInImpl_t* impl = (c_FileInImpl_t*)self;
|
||||
if (!impl->fp || !buf || len == 0) return C_ERR_PARAM;
|
||||
|
||||
c_size_t items = fread(buf, 1, (size_t)len, impl->fp);
|
||||
if (bytes_read) *bytes_read = items;
|
||||
|
||||
if (items == 0 && ferror(impl->fp)) return C_ERR_FAIL;
|
||||
return (items == len) ? C_SUCCESS : C_ERR_OUTOFBOUND;
|
||||
}
|
||||
|
||||
static void _FileIn_Destroy(c_InStream_t* self) {
|
||||
c_FileInImpl_t* impl = (c_FileInImpl_t*)self;
|
||||
c_Allocator_t alloc = impl->allocator;
|
||||
c_Allocator_Free(&alloc, impl);
|
||||
}
|
||||
|
||||
static const c_InStreamVtbl_t g_FileInVtbl = { _FileIn_Read, _FileIn_Destroy };
|
||||
|
||||
c_err_t c_FileInputStream_Create(c_InStream_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_FileInImpl_t* impl = (c_FileInImpl_t*)c_Allocator_Calloc(&alloc, 1, sizeof(c_FileInImpl_t));
|
||||
if (!impl) return C_ERR_NOMEM;
|
||||
|
||||
impl->base.vtbl = &g_FileInVtbl;
|
||||
impl->fp = file_handle;
|
||||
impl->allocator = alloc;
|
||||
*out_stream = &impl->base;
|
||||
return C_SUCCESS;
|
||||
}
|
||||
Reference in New Issue
Block a user