1 
2 #ifndef __FILEREADER_H_
3 #define __FILEREADER_H_
4 
5 #include "config.h"
6 #include "acbuf.h"
7 #include "fileio.h"
8 #include "filelocks.h"
9 
10 namespace acng
11 {
12 
13 class IDecompressor;
14 
15 
16 /*!
17  * Helper class used to read files.
18  *
19  * Could use boost::iostream templates for most of that, but Boost became such a monster nowadays.
20  * And for my work, my class behaves smarter.
21  */
22 class filereader {
23 
24 public:
25 	filereader();
26 	~filereader();
27 
28 	//! Opens any supported file.
29 	/* @param sFilename File to open. Writes the base
30 	 * 			filename w/o suffix or path prefix back into it
31 	 * @param bCriticalOpen Terminate program on failure
32 	 */
33 	bool OpenFile(const mstring & sFilename, bool bNoMagic=false, unsigned nFakeTrailingNewlines=0);
34 
35 	//////! Filename with all prepended path and compressed suffix stripped
36 	//////void GetBaseFileName(mstring & sOut);
37 	//! Returns lines when beginning with non-space, otherwise empty string.
38 	//! @return False on errors.
39 	bool GetOneLine(mstring & sOut, bool bForceUncompress=false);
GetCurrentLine()40 	unsigned GetCurrentLine() const { return m_nCurLine;} ;
41 	bool CheckGoodState(bool bTerminateOnErrors, cmstring *reportFilePath=nullptr) const;
42 
43 	bool GetChecksum(int csType, uint8_t out[], off_t &scannedSize, FILE *pDumpFile=nullptr);
44 	static bool GetChecksum(const mstring & sFileName, int csType, uint8_t out[],
45 			bool bTryUnpack, off_t &scannedSize, FILE *pDumpFile=nullptr);
46 
GetBuffer()47 	inline const char *GetBuffer() const { return m_szFileBuf; };
GetSize()48 	inline size_t GetSize() const { return m_nBufSize; };
49 
50 	void Close();
51 
getSErrorString()52 	const mstring& getSErrorString() const
53 	{
54 		return m_sErrorString;
55 	}
56 
57 private:
58 
59 	bool m_bError, m_bEof;
60 	// XXX: not totally happy, this could be a simple const char* for most usecases
61 	mstring m_sErrorString;
62 
63 	char *m_szFileBuf;
64 	size_t m_nBufSize, m_nBufPos;
65 
66 	acbuf m_UncompBuf; // uncompressed window
67 
68 	// visible position reporting
69 	unsigned m_nCurLine;
70 
71 	int m_fd;
72 
73 	int m_nEofLines;
74 
75 	std::unique_ptr<IDecompressor> m_Dec;
76 
77 	// not to be copied
78 	filereader& operator=(const filereader&);
79 	filereader(const filereader&);
80 	std::unique_ptr<TFileShrinkGuard> m_mmapLock;
81 };
82 
83 extern uint_fast16_t hexmap[];
84 
CsEqual(const char * sz,uint8_t b[],unsigned short binLen)85 inline bool CsEqual(const char *sz, uint8_t b[], unsigned short binLen)
86 {
87 	CUCHAR *a=(CUCHAR*)sz;
88 	if(!a)
89 		return false;
90 	for(int i=0; i<binLen;i++)
91 	{
92 		if(!*a)
93 			return false;
94 
95 		uint_fast16_t r=hexmap[a[i*2]] * 16 + hexmap[a[i*2+1]];
96 		if(r != b[i]) return false;
97 	}
98 	return true;
99 };
100 
101 bool Bz2compressFile(const char *pathIn, const char*pathOut);
102 
103 }
104 
105 #endif // __FILEREADER_H
106