
/*
 *
 * UNICON - The Console Chinese & I18N
 * Copyright (c) 1999-2002
 *
 * This file is part of UNICON, a console Chinese & I18N
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 * See the file COPYING directory of this archive
 * Author: see CREDITS
 */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

typedef struct MemFile_handle
{
	void	*pBuf;
	long	nBeginPos, nLen;
	long	nCurPos;
}
MemFile_T;

// Open a memory file, each memory file have a pointer of begin, current, and len
// And a buf is storing all the data of the memory file.
// Hence, to open a memfile, provide a File Discriptor, the begining position, and len.
// Note: the Begin Pointer is based on the file Offset.
long openMemFile (FILE *fp, long nBegin, long nLen)
{
	MemFile_T *p;
	void *pBuf;

	if (fp == NULL)
	   return 0;

	pBuf = (void*) malloc (nLen); 
	if (pBuf == NULL)
		return 0;

	fseek (fp, nBegin, SEEK_SET);
	nLen = fread (pBuf, 1, nLen, fp);

	p = (MemFile_T *) malloc (sizeof (MemFile_T)); 
	if (p == NULL)
	{
		free (pBuf);
		return 0;
	}
	p->nLen = nLen;
	p->nBeginPos = p->nCurPos = nBegin;
	p->pBuf = pBuf;
	return (long) p;
}

long closeMemFile (long handle)
{
	MemFile_T *p = (MemFile_T *) handle;

	if (p)
	{
		if (p->pBuf)
			free (p->pBuf);
		free (p);
	}
	return 0;
}

// Read data from current memfile position, read nLen byte data,
// The current pointer will be update by nLen.
int readMemFile (long handle, long nLen, void *buf)
{
    MemFile_T *p = (MemFile_T *) handle;
    char  *a = (char *) p->pBuf;
    void *p1 = (void *) &a[p->nCurPos - p->nBeginPos];
    memcpy (buf, p1, nLen);
    p->nCurPos += nLen;
    return nLen;
}

long lseekMemFile (long handle, long nNewBegin)
{
    MemFile_T *p = (MemFile_T *) handle;
    p->nCurPos = nNewBegin;
    return nNewBegin;
}

long ftellMemFile (long handle)
{
    MemFile_T *p = (MemFile_T *) handle;
    return p->nCurPos;
}

