aboutsummaryrefslogtreecommitdiff
path: root/lib/base/rawfile.cpp
blob: f5fb91ee1120e11002c3dfff1eea9eeebf45ac67 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#include <unistd.h>
#include <fcntl.h>
#include <lib/base/rawfile.h>
#include <lib/base/eerror.h>

eRawFile::eRawFile()
{
	m_fd = -1;
	m_splitsize = 0;
	m_totallength = 0;
	m_current_offset = 0;
	m_base_offset = 0;
	m_nrfiles = 0;
	m_current_file = 0;
}

eRawFile::~eRawFile()
{
	close();
}

int eRawFile::open(const char *filename)
{
	close();
	m_basename = filename;
	scan();
	m_current_offset = 0;
	m_fd = ::open(filename, O_RDONLY | O_LARGEFILE);
	return m_fd;
}

void eRawFile::setfd(int fd)
{
	close();
	m_nrfiles = 1;
	m_fd = fd;
}

off_t eRawFile::lseek(off_t offset, int whence)
{
		/* if there is only one file, use the native lseek - the file could be growing! */
	if (!m_nrfiles)
		return ::lseek(m_fd, offset, whence);
	switch (whence)
	{
	case SEEK_SET:
		m_current_offset = offset;
		break;
	case SEEK_CUR:
		m_current_offset += offset;
		break;
	case SEEK_END:
		m_current_offset = m_totallength + offset;
		break;
	}
	if (m_current_offset < 0)
		m_current_offset = 0;
	return m_current_offset;
}

int eRawFile::close()
{
	int ret = ::close(m_fd);
	m_fd = -1;
	return ret;
}

ssize_t eRawFile::read(void *buf, size_t count)
{
	switchOffset(m_current_offset);
	int ret = ::read(m_fd, buf, count);
	if (ret > 0)
		m_current_offset += ret;
	return ret;
}

int eRawFile::valid()
{
	return m_fd != -1;
}

void eRawFile::scan()
{
	m_nrfiles = 0;
	m_totallength = 0;
	while (m_nrfiles < 1000) /* .999 is the last possible */
	{
		int f = openFile(m_nrfiles);
		if (f < 0)
			break;
		if (!m_nrfiles)
			m_splitsize = ::lseek(f, 0, SEEK_END);
		m_totallength += ::lseek(f, 0, SEEK_END);
		::close(f);
		
		++m_nrfiles;
	}
	eDebug("found %d files, splitsize: %llx, totallength: %llx", m_nrfiles, m_splitsize, m_totallength);
}

int eRawFile::switchOffset(off_t off)
{
	if (m_splitsize)
	{
		int filenr = off / m_splitsize;
		if (filenr >= m_nrfiles)
			filenr = m_nrfiles - 1;

		if (filenr != m_current_file)
		{
			close();
			setfd(openFile(filenr));
			m_base_offset = m_splitsize * filenr;
			eDebug("switched to file %d", filenr);
		}
	} else
		m_base_offset = 0;
	
	return ::lseek(m_fd, off - m_base_offset, SEEK_SET) + m_base_offset;
}

int eRawFile::openFile(int nr)
{
	std::string filename = m_basename;
	if (m_nrfiles)
	{
		char suffix[5];
		snprintf(suffix, 5, ".%03d", nr);
		filename += suffix;
	}
	return ::open(filename.c_str(), O_RDONLY);
}