seeking out problem file.
[feisty_meow.git] / nucleus / library / filesystem / huge_file.cpp
1 /*****************************************************************************\
2 *                                                                             *
3 *  Name   : huge_file                                                         *
4 *  Author : Chris Koeritz                                                     *
5 *                                                                             *
6 *******************************************************************************
7 * Copyright (c) 2007-$now By Author.  This program is free software; you can  *
8 * redistribute it and/or modify it under the terms of the GNU General Public  *
9 * License as published by the Free Software Foundation; either version 2 of   *
10 * the License or (at your option) any later version.  This is online at:      *
11 *     http://www.fsf.org/copyleft/gpl.html                                    *
12 * Please send any updates to: fred@gruntose.com                               *
13 \*****************************************************************************/
14
15 #include "byte_filer.h"
16 #include "huge_file.h"
17
18 #include <basis/byte_array.h>
19 #include <basis/functions.h>
20 #include <basis/guards.h>
21
22 #include <stdio.h>
23 #include <sys/time.h>
24
25 #undef LOG
26 #define LOG(to_print) printf("%s::%s: %s\n", static_class_name(), func, astring(to_print).s())
27
28 //#define DEBUG_HUGE_FILE
29   // uncomment for noisy version.
30
31 using namespace basis;
32
33 namespace filesystem {
34
35 huge_file::huge_file(const astring &filename, const astring &permissions)
36 : _real_file(new byte_filer(filename, permissions)),
37   _file_pointer(0)
38 {
39 }
40
41 huge_file::~huge_file()
42 {
43   WHACK(_real_file);
44 }
45
46 void huge_file::flush() { _real_file->flush(); }
47
48 bool huge_file::truncate() { return _real_file->truncate(); }
49
50 double huge_file::length()
51 {
52   FUNCDEF("length");
53
54 //trying to read to see if we're past endpoint.
55 //  if this approach works, length may want to close and reopen file for
56 //  reading, since we can't add any bytes to it for writing just to find
57 //  the length out.
58
59
60   double save_posn = _file_pointer;
61   // skip to the beginning of the file so we can try to find the end.
62   _file_pointer = 0;
63   _real_file->seek(0, byte_filer::FROM_START);
64   size_t naive_size = _real_file->length();
65   if (naive_size < _real_file->file_size_limit()) {
66     // lucked out; we are within normal file size limitations.
67     seek(save_posn, byte_filer::FROM_START);
68     return double(naive_size);
69   }
70   
71   double best_highest = 0.0;  // the maximum we've safely seeked to.
72
73   size_t big_jump = byte_filer::file_size_limit();
74     // try with the largest possible seek at first.
75
76   while (true) {
77 #ifdef DEBUG_HUGE_FILE
78     LOG(a_sprintf("best highest=%.0f", best_highest));
79 #endif
80     // iterate until we reach our exit condition, which seems like it must
81     // always occur eventually unless the file is being monkeyed with.
82     bool seek_ret = _real_file->seek(int(big_jump), byte_filer::FROM_CURRENT);
83 #ifdef DEBUG_HUGE_FILE
84     LOG(a_sprintf("  seek ret=%d", int(seek_ret)));
85 #endif
86     byte_array temp_bytes;
87     int bytes_read = _real_file->read(temp_bytes, 1);
88     if (bytes_read < 1)
89       seek_ret = false;
90 #ifdef DEBUG_HUGE_FILE
91     LOG(a_sprintf("  read %d bytes", bytes_read));
92 #endif
93     bool at_eof = _real_file->eof();
94 #ifdef DEBUG_HUGE_FILE
95     LOG(a_sprintf("  at_eof=%d", int(at_eof)));
96 #endif
97     if (seek_ret && !at_eof) {
98 #ifdef DEBUG_HUGE_FILE
99       LOG("seek worked, incrementing best highest and trying same jump again");
100 #endif
101       // the seek worked, so we'll just jump forward again.
102       best_highest += double(big_jump);
103       _file_pointer += double(big_jump);
104       continue;
105     } else if (seek_ret && at_eof) {
106 #ifdef DEBUG_HUGE_FILE
107       LOG("seek worked but found eof exactly.");
108 #endif
109       // the seek did worked, but apparently we've also found the end point.
110       best_highest += double(big_jump);
111       _file_pointer += double(big_jump);
112       break;
113     } else {
114       // that seek was too large, so we need to back down and try a smaller
115       // seek size.
116 #ifdef DEBUG_HUGE_FILE
117       LOG("seek failed, going back to best highest and trying same jump again");
118 #endif
119       _file_pointer = 0;
120       _real_file->seek(0, byte_filer::FROM_START); 
121       outcome worked = seek(best_highest, byte_filer::FROM_START);
122         // this uses our version to position at large sizes.
123       if (worked != OKAY) {
124         // this is a bad failure; it says that the file size changed or
125         // something malfunctioned.  we should always be able to get back to
126         // the last good size we found if the file is static.
127         LOG(a_sprintf("failed to seek back to best highest %.0f on ",
128             best_highest) + _real_file->name());
129         // try to repair our ideas about the file by starting the process
130         // over.
131 //hmmm: count the number of times restarted and bail after N.
132         seek_ret = _real_file->seek(0, byte_filer::FROM_START);
133         _file_pointer = 0;
134         if (!seek_ret) {
135           // the heck with this.  we can't even go back to the start.  this
136           // file seems to be screwed up now.
137           LOG(astring("failed to seek back to start of file!  on ")
138               + _real_file->name());
139           return 0;
140         }
141         // reset the rest of the positions for our failed attempt to return
142         // to what we already thought was good.
143         _file_pointer = 0;
144         big_jump = byte_filer::file_size_limit();
145         best_highest = 0;
146         continue;
147       }
148       // okay, nothing bad happened when we went back to our last good point.
149       if (big_jump <= 0) {
150         // success in finding the smallest place that we can't seek between.
151 #ifdef DEBUG_HUGE_FILE
152         LOG("got down to smallest big jump, 0!");
153 #endif
154         break;
155       }
156       // formula expects that the maximum file size is a power of 2.
157       big_jump /= 2;
158 #ifdef DEBUG_HUGE_FILE
159       LOG(a_sprintf("restraining big jump down to %u.", big_jump));
160 #endif
161       continue;
162     }
163   }
164
165   // go back to where we started out.
166   seek(0, byte_filer::FROM_START);
167   seek(save_posn, byte_filer::FROM_CURRENT);
168 #ifdef DEBUG_HUGE_FILE
169   LOG(a_sprintf("saying file len is %.0f.", best_highest + 1.0));
170 #endif
171   return best_highest + 1.0;
172 }
173
174 bool huge_file::good() const { return _real_file->good(); }
175
176 bool huge_file::eof() const { return _real_file->eof(); }
177
178 outcome huge_file::move_to(double absolute_posn)
179 {
180 #ifdef DEBUG_HUGE_FILE
181   FUNCDEF("move_to");
182 #endif
183   double difference = absolute_posn - _file_pointer;
184     // calculate the size we want to offset.
185 #ifdef DEBUG_HUGE_FILE
186   LOG(a_sprintf("abs_pos=%.0f difference=%.0f old_filepoint=%.0f",
187       absolute_posn, difference, _file_pointer));
188 #endif
189   // if we're at the same place, we don't have to do anything.
190   if (difference < 0.000001) {
191 #ifdef DEBUG_HUGE_FILE
192     LOG("difference was minimal, saying we're done.");
193 #endif
194     return OKAY;
195   }
196   while (absolute_value(difference) > 0.000001) {
197     double seek_size = minimum(double(byte_filer::file_size_limit() - 1),
198         absolute_value(difference));
199     if (difference < 0)
200       seek_size *= -1.0;  // flip sign of seek.
201 #ifdef DEBUG_HUGE_FILE
202     LOG(a_sprintf("  seeksize=%d", int(seek_size)));
203 #endif
204     bool seek_ret = _real_file->seek(int(seek_size),
205         byte_filer::FROM_CURRENT);
206     if (!seek_ret) {
207 #ifdef DEBUG_HUGE_FILE
208       LOG(a_sprintf("failed to seek %d from current", int(seek_size)));
209 #endif
210       return FAILURE;  // seek failed somehow.
211     }
212     _file_pointer += seek_size;
213 #ifdef DEBUG_HUGE_FILE
214     LOG(a_sprintf("  now_filepoint=%.0f", _file_pointer));
215 #endif
216     difference = absolute_posn - _file_pointer;
217 #ifdef DEBUG_HUGE_FILE
218     LOG(a_sprintf("  now_difference=%.0f", difference));
219 #endif
220   }
221   return OKAY;
222 }
223
224 outcome huge_file::seek(double new_position, byte_filer::origins origin)
225 {
226 #ifdef DEBUG_HUGE_FILE
227   FUNCDEF("seek");
228 #endif
229   if (origin == byte_filer::FROM_CURRENT) {
230     return move_to(_file_pointer + new_position);
231   } else if (origin == byte_filer::FROM_START) {
232     _file_pointer = 0;
233     if (!_real_file->seek(0, byte_filer::FROM_START))
234       return FAILURE;
235     return move_to(new_position);
236   } else if (origin == byte_filer::FROM_END) {
237 #ifdef DEBUG_HUGE_FILE
238     LOG("into precarious FROM_END case.");
239 #endif
240     double file_len = length();  // could take a scary long time possibly.
241 #ifdef DEBUG_HUGE_FILE
242     LOG(a_sprintf("  FROM_END got len %.0f.", file_len));
243 #endif
244     _file_pointer = file_len;
245       // it's safe, although not efficient, for us to call the length()
246       // method here.  our current version of length() uses the byte_filer's
247       // seek method directly and only FROM_CURRENT and FROM_START from this
248       // class's seek method.
249     _real_file->seek(0, byte_filer::FROM_END);
250     return move_to(_file_pointer - new_position);
251   }
252   // unknown origin.
253   return BAD_INPUT;
254 }
255
256 outcome huge_file::read(byte_array &to_fill, int desired_size, int &size_read)
257 {
258   FUNCDEF("read");
259   size_read = 0;
260   int ret = _real_file->read(to_fill, desired_size);
261   if (ret < 0)
262     return FAILURE;  // couldn't read the bytes.
263   _file_pointer += double(size_read);
264   size_read = ret;
265   return OKAY; 
266 }
267
268 outcome huge_file::write(const byte_array &to_write, int &size_written)
269 {
270   FUNCDEF("write");
271   size_written = 0;
272   int ret = _real_file->write(to_write);
273   if (ret < 0)
274     return FAILURE;  // couldn't write the bytes.
275   _file_pointer += double(size_written);
276   size_written = ret;
277   return OKAY;
278 }
279
280 basis::outcome huge_file::touch()
281 {
282   if (filename(_real_file->name()).exists()) {
283     // file exists, so just update time.
284     int ret = utimes(_real_file->name().observe(), NIL);
285     if (ret != 0)
286       return FAILURE;
287   } else {
288     // file doesn't exist yet.
289     byte_array junk(1);
290     int written;
291     outcome ret = write(junk, written);
292     if (ret != OKAY) ret;
293     if (!truncate())
294       return FAILURE;
295   }
296   return OKAY;
297 }
298
299 } //namespace.
300