#include "cfileno.h"

#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>

cTBFileNo::cTBFileNo(void) {
	m_Filed        = -1;
	m_BytesRead    = 0;
	m_BytesWritten = 0;
	m_IsEof        = true;
}

cTBFileNo::~cTBFileNo() {
	if (IsOpen())
		Close();
}

bool cTBFileNo::Open(int Filed) {
	if (IsOpen())
		Close();

	if (::fcntl(Filed, F_GETFL) == -1)
		return false;

	m_Filed = Filed;
	m_BytesRead = 0;
	m_BytesWritten = 0;
	m_IsEof = false;
	return true;
}

bool cTBFileNo::Close(void) {
	int result;

	if (!IsOpen())
		return false;

	result  = ::close(m_Filed);
	m_Filed = -1;
	
	return (result != -1);
}

ssize_t cTBFileNo::Read(char *Buffer, size_t Size, size_t &Offset) {
	ssize_t bytes;
	if ((bytes = SysRead(Buffer + Offset, Size - Offset)) > 0) {
		Offset += bytes;
		m_BytesRead += bytes;
	}

	return bytes;
}

ssize_t cTBFileNo::Write(char *Buffer, size_t &Length) {
	ssize_t bytes;
	if ((bytes = SysWrite(Buffer, Length)) > 0) {
		Length -= bytes;
		memmove(Buffer, Buffer + bytes, Length);
		m_BytesWritten += bytes;
	}
	return bytes;
}
