myio_byte_array.c

最終更新:2010/1/21

myio_byte_array.c

001: /*
002:  * バイト配列をソースとする入力ストリーム
003:  */
004: 
005: #include "myio_byte_array.h"
006: 
007: /*
008:  * size バイト分のデータを読み出す関数。
009:  * 返り値は buf に読み出したバイト数。
010:  * エラー時には -1 が返る。
011:  */
012: 
013: int myio_read_ba (
014:   MYIO *in
015:   , char *buf
016:   , int size
017: ) {
018:   int nbytes = 0;
019:   myio_ba_ctx *ctx = (myio_ba_ctx*)(in->ptr);
020:   if (!ctx || ! ctx->ba) {
021:     return -1;
022:   }
023: 
024:   if (ctx->pos >= ctx->size) {
025:     return 0;
026:   }
027:   
028:   if (ctx->pos + size > ctx->size) {
029:     nbytes = ctx->size - ctx->pos;
030:   } else {
031:     nbytes = size;
032:   }
033:   
034:   {
035:     int i;
036:     for (i=0; i<nbytes; i++) {
037:       buf[i] = ctx->ba[ctx->pos + i];
038:     }
039:   }
040:   
041:   ctx->pos += nbytes;
042:   
043:   return nbytes;
044: }
045: 
046: MYIO_METHOD myio_ba_method = {
047:   MYIO_METHOD_NAME_BA
048:   , (void*)0
049:   , myio_read_ba
050:   , (void*)0
051:   , (void*)0
052: };
053: 
054: 
055: MYIO *MYIO_ba_new (
056:   char *ba               /* バイト配列 */
057:   , int size             /* バイト配列のサイズ */
058:   , void *alloc_func     /* メモリアロケーションの関数 */
059:   , void *alloc_func_ctx /* メモリアロケーションの関数のコンテクストデータ */
060: ) {
061:   myio_ba_ctx *ctx = (void*)0;
062:   MYIO *myio = (void*)0;
063:   void * (*alloc_f)(void*,int) = alloc_func;
064:   if (!ba || size<=0) {
065:     return (void*)0;
066:   }
067:   
068:   if (alloc_f == (void*)0) {
069:     return (void*)0;
070:   }
071:   ctx = (myio_ba_ctx *)alloc_f(alloc_func_ctx, sizeof(myio_ba_ctx));
072:   
073:   if (!ctx) {
074:     return (void*)0;
075:   }
076: 
077:   ctx->ba = ba;
078:   ctx->size = size;
079:   ctx->pos = 0;
080:   
081:   myio = (MYIO*)alloc_f(alloc_func_ctx, sizeof(MYIO));
082: 
083:   if (!myio) {
084:     return (void*)0;
085:   }
086: 
087:   return MYIO_make(myio, &myio_ba_method, 1, 0, ctx);
088: }
Copyright (C) KAKU PROJECT (2009)KAKU PROJECT (2009)