#ifndef __myu_super_stream_H__
#define __myu_super_stream_H__

#include <stdio.h>
#include <stdarg.h>
#include "mslcommon.h"
//#include <auto_fp.h>
#include "mslfile.h"

NSMSL_START

//	myu_super_stream Class Definitation
class super_stream{
public:
	virtual int printf( const char *format, ... )
	{
		va_list vl;
		va_start( vl, format );
		int r = printf(format, vl);
		va_end( vl );
		return r;
	}
	virtual int vprintf( const char *format, va_list ap )=0;
};

//	file_stream Class Definitation
class file_stream : public super_stream, auto_fp{
public:
	file_stream(const char* path, const char* mode){ auto_fp::open(path,mode); }
	file_stream(FILE* fp) : auto_fp(fp){}
	
	int vprintf( const char *format, va_list ap )
	{
		return vfprintf(auto_fp::get(), format, ap);
	}
};

//	string_stream Class Definitation
class string_stream : public super_stream{
protected:
	char *m_pBuf;
	int m_nBufSize;
	int m_nPos;
public:
	string_stream(int bufsize){
		m_pBuf = new char[bufsize];
		m_nBufSize = bufsize;
		clear();
	}
	virtual ~string_stream(){ SAFE_DELETE_ARY(m_pBuf); }
	void clear(){ ZeroMemory(m_pBuf, m_nBufSize); m_nPos = 0; }

	/*int printf( const char *format, ... )
	{
		va_list vl;
		va_start( vl, format );
		int r = printf(format, vl);
		va_end( vl );
		return r;
	}*/

	int vprintf( const char *format, va_list ap )
	{
		char *pBuf = m_pBuf + m_nPos;
		int nBufSize = m_nBufSize - m_nPos;
	#ifdef WIN32
		m_pBuf[m_nBufSize-1] = '\0';
		//int r = _vsnprintf(m_pBuf, m_nBufSize-1, format, ap);
		int r = _vsnprintf(pBuf, nBufSize-1, format, ap);
		return r;
	#else
		//return -1;
		//int r = vsnprintf(m_pBuf, m_nBufSize, format, ap);
		int r = vsnprintf(pBuf, nBufSize, format, ap);
	#endif
		m_nPos += r;
	}

	char* get(){ return m_pBuf; }
	char* GetBuf(){ return m_pBuf; }
	char* GetBuffer(){ return m_pBuf; }
	operator char*(){ return m_pBuf; }
	operator const char* (){ return m_pBuf; }
};

NSMSL_END

#endif//__myu_super_stream_H__