blob: 3acdfd45b8c50a15d03901b451e082f217a75fa5 [file] [log] [blame]
Pierre Ossman82c279e2015-02-04 14:11:42 +01001/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
2 * Copyright (C) 2013 D. R. Commander. All Rights Reserved.
3 * Copyright 2015 Pierre Ossman for Cendio AB
4 *
5 * This is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This software is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this software; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
18 * USA.
19 */
20
21#include <errno.h>
22
23#include <rdr/Exception.h>
24#include <rdr/FileInStream.h>
25
26using namespace rdr;
27
28FileInStream::FileInStream(const char *fileName)
29{
30 file = fopen(fileName, "rb");
31 if (!file)
32 throw SystemException("fopen", errno);
33 ptr = end = b;
34}
35
36FileInStream::~FileInStream(void) {
37 if (file) {
38 fclose(file);
39 file = NULL;
40 }
41}
42
43void FileInStream::reset(void) {
44 if (!file)
45 throw Exception("File is not open");
46 if (fseek(file, 0, SEEK_SET) != 0)
47 throw SystemException("fseek", errno);
48 ptr = end = b;
49}
50
51int FileInStream::pos()
52{
53 if (!file)
54 throw Exception("File is not open");
55
56 return ftell(file) + ptr - b;
57}
58
59int FileInStream::overrun(int itemSize, int nItems, bool wait)
60{
Pierre Ossman5c23b9e2015-03-03 16:26:03 +010061 if (itemSize > (int)sizeof(b))
Pierre Ossman82c279e2015-02-04 14:11:42 +010062 throw Exception("FileInStream overrun: max itemSize exceeded");
63
64 if (end - ptr != 0)
65 memmove(b, ptr, end - ptr);
66
67 end -= ptr - b;
68 ptr = b;
69
70
71 while (end < b + itemSize) {
72 size_t n = fread((U8 *)end, b + sizeof(b) - end, 1, file);
Steve Kondikb315dfa2017-07-08 01:57:16 -070073 if (n == 0) {
74 if (ferror(file))
Pierre Ossmana7bbe9c2015-03-03 16:17:51 +010075 throw SystemException("fread", errno);
Pierre Ossman82c279e2015-02-04 14:11:42 +010076 if (feof(file))
77 throw EndOfStream();
Steve Kondikb315dfa2017-07-08 01:57:16 -070078 return 0;
Pierre Ossman82c279e2015-02-04 14:11:42 +010079 }
80 end += b + sizeof(b) - end;
81 }
82
83 if (itemSize * nItems > end - ptr)
84 nItems = (end - ptr) / itemSize;
85
86 return nItems;
87}