1 /* Copyright (C) 2003, 2004, 2005, 2006, 2008, 2009 Dean Beeler, Jerome Fisher
2  * Copyright (C) 2011-2017 Dean Beeler, Jerome Fisher, Sergey V. Mikayev
3  *
4  *  This program is free software: you can redistribute it and/or modify
5  *  it under the terms of the GNU Lesser General Public License as published by
6  *  the Free Software Foundation, either version 2.1 of the License, or
7  *  (at your option) any later version.
8  *
9  *  This program is distributed in the hope that it will be useful,
10  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *  GNU Lesser General Public License for more details.
13  *
14  *  You should have received a copy of the GNU Lesser General Public License
15  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17 
18 #ifdef MT32EMU_SHARED
19 #include <locale>
20 #endif
21 
22 #include "internals.h"
23 
24 // Disable MSVC STL exceptions
25 #ifdef _MSC_VER
26 #define _HAS_EXCEPTIONS 0
27 #endif
28 #include "FileStream.h"
29 
30 namespace MT32Emu {
31 
configureSystemLocale()32 static inline void configureSystemLocale() {
33 #ifdef MT32EMU_SHARED
34 	static bool configured = false;
35 
36 	if (configured) return;
37 	configured = true;
38 	std::locale::global(std::locale(""));
39 #endif
40 }
41 
42 using std::ios_base;
43 
FileStream()44 FileStream::FileStream() : ifsp(*new std::ifstream), data(NULL), size(0)
45 {}
46 
~FileStream()47 FileStream::~FileStream() {
48 	// destructor closes ifsp
49 	delete &ifsp;
50 	delete[] data;
51 }
52 
getSize()53 size_t FileStream::getSize() {
54 	if (size != 0) {
55 		return size;
56 	}
57 	if (!ifsp.is_open()) {
58 		return 0;
59 	}
60 	ifsp.seekg(0, ios_base::end);
61 	size = size_t(ifsp.tellg());
62 	return size;
63 }
64 
getData()65 const Bit8u *FileStream::getData() {
66 	if (data != NULL) {
67 		return data;
68 	}
69 	if (!ifsp.is_open()) {
70 		return NULL;
71 	}
72 	if (getSize() == 0) {
73 		return NULL;
74 	}
75 	Bit8u *fileData = new Bit8u[size];
76 	if (fileData == NULL) {
77 		return NULL;
78 	}
79 	ifsp.seekg(0);
80 	ifsp.read(reinterpret_cast<char *>(fileData), std::streamsize(size));
81 	if (size_t(ifsp.tellg()) != size) {
82 		delete[] fileData;
83 		return NULL;
84 	}
85 	data = fileData;
86 	close();
87 	return data;
88 }
89 
open(const char * filename)90 bool FileStream::open(const char *filename) {
91 	configureSystemLocale();
92 	ifsp.clear();
93 	ifsp.open(filename, ios_base::in | ios_base::binary);
94 	return !ifsp.fail();
95 }
96 
close()97 void FileStream::close() {
98 	ifsp.close();
99 	ifsp.clear();
100 }
101 
102 } // namespace MT32Emu
103