Debian Codegraph @

terps/tads/tads3/vmfile.h

raw symbols SCIP
1 /* $Header: d:/cvsroot/tads/tads3/VMFILE.H,v 1.2 1999/05/17 02:52:28 MJRoberts Exp $ */
2
3 /*
4 * Copyright (c) 1998, 2002 Michael J. Roberts. All Rights Reserved.
5 *
6 * Please see the accompanying license file, LICENSE.TXT, for information
7 * on using and copying this software.
8 */
9 /*
10 Name
11 vmfile.h - VM external file interface
12 Function
13
14 Notes
15
16 Modified
17 10/28/98 MJRoberts - Creation
18 */
19
20 #ifndef VMFILE_H
21 #define VMFILE_H
22
23 #include "t3std.h"
24 #include "vmerr.h"
25 #include "osifcnet.h"
26
27
28 /* ------------------------------------------------------------------------ */
29 /*
30 * VM external file interface. The VM uses this interface for
31 * manipulating files that contain program images and saved state.
32 */
33
34 class CVmFile
35 {
36 public:
37 /* create a new file object */
38 CVmFile()
39 {
40 /* no file yet */
41 fp_ = 0;
42
43 /* presume the base seek position is at the start of the file */
44 seek_base_ = 0;
45 }
46
47 CVmFile(osfildef *fp, long seek_base)
48 {
49 fp_ = fp;
50 seek_base_ = seek_base;
51 }
52
53 /*
54 * Duplicate the file handle, a la stdio freopen(). 'mode' is a
55 * simplified fopen()-style mode string, with the same syntax as used
56 * in osfdup().
57 */
58 CVmFile *dup(const char *mode)
59 {
60 /* duplicate our file handle */
61 osfildef *fpdup = osfdup(fp_, mode);
62 if (fpdup == 0)
63 return 0;
64
65 /* create a new CVmFile wrapper for the new handle */
66 return new CVmFile(fpdup, seek_base_);
67 }
68
69 /* delete the file */
70 ~CVmFile();
71
72 /*
73 * Set the file to use an existing underlying OS file handle. The
74 * seek_base value gives the byte offset within the OS file handle
75 * of our virtual byte stream; this is useful if the file object is
76 * handling a byte stream embedded within a larger OS file (such as
77 * a resource within a file containing multiple resources). If
78 * we're simply providing access to the entire underlying file, the
79 * seek_base value should be zero.
80 */
81 void set_file(osfildef *fp, long seek_base)
82 {
83 /* remember the file handle and seek position */
84 fp_ = fp;
85 seek_base_ = seek_base;
86 }
87
88 /*
89 * Detach from the underlying OS file handle. Normally, when we are
90 * deleted, we'll close our underlying OS file handle. If the
91 * caller has a separate reference to the OS file handle and wants
92 * to keep the handle open after deleting us, the caller should use
93 * this function to detach us from the OS file handle before
94 * deleting us.
95 *
96 * After calling this routine, no operations can be performed on the
97 * underlying file through this object, since we will have forgotten
98 * the file handle.
99 */
100 void detach_file()
101 {
102 /* forget our file handle */
103 fp_ = 0;
104 }
105
106 /*
107 * Open an existing file for reading. Throws an error if the file
108 * does not exist.
109 */
110 void open_read(const char *fname, os_filetype_t typ);
111
112 /*
113 * Create a file for writing, replacing any existing file. Throws
114 * an error if the file cannot be created.
115 */
116 void open_write(const char *fname, os_filetype_t typ);
117
118 /* close the underlying file */
119 void close()
120 {
121 osfcls(fp_);
122 fp_ = 0;
123 }
124
125 /* flush buffers */
126 void flush()
127 {
128 if (osfflush(fp_))
129 err_throw(VMERR_WRITE_FILE);
130 }
131
132 /*
133 * Read various types from the file. These routines throw an error
134 * if the data cannot be read.
135 */
136 uchar read_byte() { char b; read_bytes(&b, 1); return (uchar)b; }
137 uint read_uint2() { char b[2]; read_bytes(b, 2); return osrp2(b); }
138 int read_int2() { char b[2]; read_bytes(b, 2); return osrp2s(b); }
139 long read_int4() { char b[4]; read_bytes(b, 4); return osrp4s(b); }
140 ulong read_uint4() { char b[4]; read_bytes(b, 4); return t3rp4u(b); }
141
142 /* read bytes - throws an error if all of the bytes cannot be read */
143 void read_bytes(char *buf, size_t buflen)
144 {
145 if (buflen != 0 && osfrb(fp_, buf, buflen))
146 err_throw(VMERR_READ_FILE);
147 }
148
149 /*
150 * Read bytes, with no error on partial read. If the full request
151 * can't be satisfied (because of end of file, partial read on pipe or
152 * socket, etc), reads as many as are available and returns the count.
153 * If no bytes are available, returns zero. This routine can still
154 * throw an error if some other error occurs besides end-of-file (file
155 * not open, etc).
156 */
157 size_t read_nbytes(char *buf, size_t buflen)
158 {
159 return buflen == 0 ? 0 : osfrbc(fp_, buf, buflen);
160 }
161
162 /* read a line (fgets semantics) */
163 char *read_line(char *buf, size_t buflen)
164 { return osfgets(buf, buflen, fp_); }
165
166 /*
167 * read a string with a one-byte length prefix, adding a null
168 * terminator; returns the length
169 */
170 size_t read_str_byte_prefix(char *buf, size_t buflen)
171 {
172 size_t len = read_byte();
173 if (len+1 > buflen)
174 err_throw(VMERR_READ_FILE);
175
176 read_bytes(buf, len);
177 buf[len] = '\0';
178 return len;
179 }
180
181 /*
182 * read a string with a two-byte length prefix, adding a null
183 * terminator; returns the length
184 */
185 size_t read_str_short_prefix(char *buf, size_t buflen)
186 {
187 size_t len = read_uint2();
188 if (len+1 > buflen)
189 err_throw(VMERR_READ_FILE);
190
191 read_bytes(buf, len);
192 buf[len] = '\0';
193 return len;
194 }
195
196 /*
197 * Read a string with a two-byte length prefix, allocating the buffer
198 * with lib_alloc_str() (the caller frees it with lib_free_str()).
199 * We'll null-terminate the result, and optionally return the length in
200 * '*lenp'. 'lenp' call be null if the length isn't needed.
201 */
202 char *read_str_short_prefix(size_t *lenp)
203 {
204 size_t len = read_uint2();
205 char *buf = lib_alloc_str(len);
206 read_bytes(buf, len);
207 buf[len] = '\0';
208
209 if (lenp != 0)
210 *lenp = len;
211
212 return buf;
213 }
214
215 /*
216 * Write various types to the file. These routines throw an error
217 * if the data cannot be written.
218 */
219 void write_byte(char c) { char b[1]; b[0] = c; write_bytes(b, 1); }
220 void write_int2(int v) { char b[2]; oswp2s(b, v); write_bytes(b, 2); }
221 void write_uint2(uint v) { char b[2]; oswp2(b, v); write_bytes(b, 2); }
222 void write_int4(int v) { char b[4]; oswp4s(b, v); write_bytes(b, 4); }
223 void write_uint4(uint v) { char b[4]; oswp4(b, v); write_bytes(b, 4); }
224
225 /*
226 * Write a string with a single-byte length prefix. Throws an error if
227 * the string is too long.
228 */
229 void write_str_byte_prefix(const char *str, size_t len)
230 {
231 /* make sure it fits */
232 if (len > 255)
233 err_throw(VMERR_WRITE_FILE);
234
235 /* write the prefix and the string */
236 write_byte((char)len);
237 write_bytes(str, len);
238 }
239 void write_str_byte_prefix(const char *str)
240 { write_str_byte_prefix(str, strlen(str)); }
241
242 /* write a string with a two-byte length prefix */
243 void write_str_short_prefix(const char *str, size_t len)
244 {
245 /* make sure it fits */
246 if (len > 65535)
247 err_throw(VMERR_WRITE_FILE);
248
249 /* write the prefix and string */
250 write_uint2((int)len);
251 write_bytes(str, len);
252 }
253 void write_str_short_prefix(const char *str)
254 { write_str_short_prefix(str, strlen(str)); }
255
256 /* write bytes - throws an error if the bytes cannot be written */
257 void write_bytes(const char *buf, size_t buflen)
258 {
259 if (buflen != 0 && osfwb(fp_, buf, buflen))
260 err_throw(VMERR_WRITE_FILE);
261 }
262
263 /* get the current seek position */
264 long get_pos() const { return osfpos(fp_) - seek_base_; }
265
266 /* seek to a new position */
267 void set_pos(long seekpos)
268 {
269 /* seek relative to the base seek position */
270 osfseek(fp_, seekpos + seek_base_, OSFSK_SET);
271 }
272
273 /* seek to a position relative to the end of the file */
274 void set_pos_from_eof(long pos) { osfseek(fp_, pos, OSFSK_END); }
275
276 /* seek to a position relative to the current file position */
277 void set_pos_from_cur(long pos) { osfseek(fp_, pos, OSFSK_CUR); }
278
279 protected:
280 /* our underlying OS file handle */
281 osfildef *fp_;
282
283 /*
284 * Base seek position - this is useful for virtual byte streams that
285 * are embedded in larger files (resource files, for example).
286 * set_pos() is always relative to this position. Note that
287 * set_pos_from_eof() is *not* relative to this position, so
288 * embedded byte streams must not use set_pos_from_eof() unless the
289 * embedded stream ends at the end of the enclosing file.
290 */
291 long seek_base_;
292 };
293
294 /* ------------------------------------------------------------------------ */
295 /*
296 * Generic stream interface. This is a higher-level type of file interface
297 * than CVmFile: this interface can be implemented on different kinds of
298 * underlying storage formats to provide generic stream access independent
299 * of the actual storage implementation.
300 *
301 * We provide default implementations of the type readers in terms of the
302 * low-level byte reader virtual method, which must be implemented by each
303 * concrete subclass. However, all of the type readers are virtual, so
304 * subclasses can override these if they can be implemented more
305 * efficiently on the underlying stream (for example, some implementations
306 * might have ready access to the data in a buffer already, in which case
307 * it might be faster to avoid the extra buffer copy of the default
308 * implementations of the type readers).
309 */
310 class CVmStream
311 {
312 public:
313 virtual ~CVmStream() { }
314
315 /* clone the stream - see CVmDataSource::clone() for details */
316 virtual CVmStream *clone(VMG_ const char *mode) = 0;
317
318 /* read/write a byte */
319 virtual uchar read_byte() { char b; read_bytes(&b, 1); return (uchar)b; }
320 virtual void write_byte(uchar b) { write_bytes((char *)&b, 1); }
321
322 /*
323 * read various integer types (signed 2-byte, unsigned 2-byte, signed
324 * 4-byte, unsigned 4-byte)
325 */
326 virtual int read_int2() { char b[2]; read_bytes(b, 2); return osrp2s(b); }
327 virtual uint read_uint2()
328 { char b[2]; read_bytes(b, 2); return osrp2(b); }
329 virtual long read_int4() { char b[4]; read_bytes(b, 4); return osrp4s(b); }
330 virtual ulong read_uint4()
331 { char b[4]; read_bytes(b, 4); return t3rp4u(b); }
332
333 /* write an integer value */
334 virtual void write_byte(char c)
335 { char b[1]; b[0] = c; write_bytes(b, 1); }
336 virtual void write_int2(int i)
337 { char b[2]; oswp2s(b, i); write_bytes(b, 2); }
338 virtual void write_uint2(uint i)
339 { char b[2]; oswp2(b, i); write_bytes(b, 2); }
340 virtual void write_int4(long l)
341 { char b[4]; oswp4s(b, l); write_bytes(b, 4); }
342 virtual void write_uint4(ulong l)
343 { char b[4]; oswp4(b, l); write_bytes(b, 4); }
344
345 /*
346 * Read bytes - this must be provided by the implementation. Throws an
347 * error if the full number of bytes requested cannot be read.
348 */
349 virtual void read_bytes(char *buf, size_t len) = 0;
350
351 /*
352 * Read bytes - reads up to the amount requested, but treats a partial
353 * read (due to end of file, partial read on a pipe or socket, etc) as
354 * a success. Returns the actual number of bytes read, which may be
355 * less than the requested number, and can even be zero if the file is
356 * already at EOF.
357 */
358 virtual size_t read_nbytes(char *buf, size_t len) = 0;
359
360 /* read a line - fgets semantics */
361 virtual char *read_line(char *buf, size_t len) = 0;
362
363 /* write bytes */
364 virtual void write_bytes(const char *buf, size_t len) = 0;
365
366 /* get the current seek offset */
367 virtual long get_seek_pos() const = 0;
368
369 /*
370 * set the seek offset - this is only valid with offsets previously
371 * obtained with get_seek_pos()
372 */
373 virtual void set_seek_pos(long pos) = 0;
374
375 /* get the length of the stream's contents */
376 virtual long get_len() = 0;
377 };
378
379 /*
380 * Implementation of the generic stream with an underlying CVmFile object
381 */
382 class CVmFileStream: public CVmStream
383 {
384 public:
385 /* create based on the underlying file object */
386 CVmFileStream(CVmFile *fp) { fp_ = fp; }
387
388 /* clone the stream */
389 virtual CVmStream *clone(VMG_ const char *mode)
390 {
391 /* duplicate the file handle */
392 CVmFile *fpdup = fp_->dup(mode);
393 if (fpdup == 0)
394 return 0;
395
396 /* return a new file stream wrapper for the duplicate handle */
397 return new CVmFileStream(fpdup);
398 }
399
400 /* read bytes */
401 void read_bytes(char *buf, size_t len)
402 { fp_->read_bytes(buf, len); }
403
404 /* read bytes with success on partial read */
405 size_t read_nbytes(char *buf, size_t len)
406 { return fp_->read_nbytes(buf, len); }
407
408 /* read a line */
409 char *read_line(char *buf, size_t len)
410 { return fp_->read_line(buf, len); }
411
412 /* write bytes */
413 void write_bytes(const char *buf, size_t len)
414 { fp_->write_bytes(buf, len); }
415
416 /* get/set the seek position */
417 long get_seek_pos() const { return fp_->get_pos(); }
418 void set_seek_pos(long pos) { fp_->set_pos(pos); }
419
420 /* get the length of the stream */
421 long get_len()
422 {
423 /* remember the current seek position */
424 long orig = fp_->get_pos();
425
426 /* seek to the end of the file */
427 fp_->set_pos_from_eof(0);
428
429 /* the seek position is the file length */
430 long len = fp_->get_pos();
431
432 /* seek back to where we started */
433 fp_->set_pos(orig);
434
435 /* return the stream length */
436 return len;
437 }
438
439 private:
440 /* our underlying file stream */
441 CVmFile *fp_;
442 };
443
444 /*
445 * Reference-counted long int value (service class for CVmCountingStream)
446 */
447 class CVmRefCntLong: public CVmRefCntObj
448 {
449 public:
450 CVmRefCntLong() { val = 0; }
451
452 long val;
453 };
454
455 /*
456 * Counting stream; write-only. This is a stream for measuring the size of
457 * data for writing. We don't actually write anything; we just count the
458 * bytes written.
459 */
460 class CVmCountingStream: public CVmStream
461 {
462 public:
463 CVmCountingStream()
464 {
465 pos_ = 0;
466 len_ = new CVmRefCntLong();
467 }
468
469 CVmCountingStream(CVmRefCntLong *l)
470 {
471 l->add_ref();
472 len_ = l;
473 }
474
475 ~CVmCountingStream() { len_->release_ref(); }
476
477 CVmStream *clone(VMG_ const char * /*mode*/)
478 { return new CVmCountingStream(len_); }
479
480 void read_bytes(char *buf, size_t len) { err_throw(VMERR_READ_FILE); }
481 size_t read_nbytes(char *buf, size_t len)
482 {
483 err_throw(VMERR_READ_FILE);
484 AFTER_ERR_THROW(return 0);
485 }
486 char *read_line(char *buf, size_t len)
487 {
488 err_throw(VMERR_READ_FILE);
489 AFTER_ERR_THROW(return 0);
490 }
491
492 void write_bytes(const char *buf, size_t len)
493 {
494 pos_ += len;
495 if (pos_ > len_->val)
496 len_->val = pos_;
497 }
498
499 long get_seek_pos() const { return pos_; }
500 void set_seek_pos(long pos)
501 { pos_ = (pos < 0 ? 0 : pos > len_->val ? len_->val : pos); }
502
503 long get_len() { return len_->val; }
504
505 protected:
506 /* current seek position */
507 long pos_;
508
509 /* number of bytes written */
510 CVmRefCntLong *len_;
511 };
512
513 /*
514 * Implementation of the generic stream reader for reading or writing a
515 * memory buffer. This uses a fixed, pre-allocated buffer provided by the
516 * caller, so writing is limited to the space in the buffer. (For a more
517 * flexible memory stream writer that allocates space as needed, use
518 * CVmExpandableMemoryStream.)
519 */
520 class CVmMemoryStream: public CVmStream
521 {
522 public:
523 /* create given the underlying memory buffer */
524 CVmMemoryStream(char *buf, size_t len)
525 {
526 /* remember the buffer */
527 buf_ = buf;
528 buflen_ = len;
529
530 /* start at the start of the buffer */
531 p_ = buf;
532 }
533
534 /* clone */
535 virtual CVmStream *clone(VMG_ const char * /*mode*/)
536 { return new CVmMemoryStream(buf_, buflen_); }
537
538 /* read bytes */
539 void read_bytes(char *buf, size_t len)
540 {
541 /* if we don't have enough bytes left, throw an error */
542 if (len > (size_t)((buf_ + buflen_) - p_))
543 err_throw(VMERR_READ_FILE);
544
545 /* copy the data */
546 memcpy(buf, p_, len);
547
548 /* advance past the data we just read */
549 p_ += len;
550 }
551
552 /* read bytes, partial read OK */
553 size_t read_nbytes(char *buf, size_t len)
554 {
555 /* limit the request to the number of bytes available */
556 long avail = (buf_ + buflen_) - p_;
557 if ((long)len > avail)
558 len = (size_t)avail;
559
560 /* copy the data */
561 if (len != 0)
562 memcpy(buf, p_, len);
563
564 /* advance past the data we just read */
565 p_ += len;
566
567 /* return the number of bytes read */
568 return len;
569 }
570
571 /* read a line */
572 char *read_line(char *buf, size_t len)
573 {
574 /* if already at EOF, or there's no buffer, return null */
575 if (p_ >= buf_ + buflen_ || buf == 0 || len == 0)
576 return 0;
577
578 /* read bytes until we fill the buffer or reach '\n' or EOF */
579 char *dst;
580 size_t rem;
581 for (dst = buf, rem = len ; rem > 1 && p_ < buf_ + buflen_ ; --rem)
582 {
583 /* get this character */
584 char c = *p_++;
585
586 /* check for newlines */
587 if (c == '\n' || c == '\r')
588 {
589 /* write CR and LF as simply CR */
590 *dst++ = '\n';
591
592 /* if we have a CR-LF or LF-CR sequence, skip the pair */
593 if (p_ < buf_ + buflen_
594 && ((c == '\n' && *p_ == '\r')
595 || (c == '\r' && *p_ == '\n')))
596 p_ += 1;
597
598 /* done */
599 break;
600 }
601
602 /* copy this character */
603 *dst++ = c;
604 }
605
606 /* add the trailing null and return the buffer */
607 *dst = '\0';
608 return buf;
609 }
610
611 /* write bytes */
612 void write_bytes(const char *buf, size_t len)
613 {
614 /* if we don't have space, throw an error */
615 if (len > (size_t)((buf_ + buflen_) - p_))
616 err_throw(VMERR_WRITE_FILE);
617
618 /* copy the data */
619 memcpy(p_, buf, len);
620
621 /* advance past the data */
622 p_ += len;
623 }
624
625 /* get the position - return an offset from the start of our buffer */
626 long get_seek_pos() const { return p_ - buf_; }
627
628 /* set the position, as an offset from the start of our buffer */
629 void set_seek_pos(long pos)
630 {
631 /* limit it to the available space */
632 if (pos < 0)
633 pos = 0;
634 else if (pos > (long)buflen_)
635 pos = buflen_;
636
637 /* set the position */
638 p_ = buf_ + pos;
639 }
640
641 /* get the stream length */
642 long get_len() { return buflen_; }
643
644 /* set the stream length */
645 void set_len(size_t len) { buflen_ = len; }
646
647 protected:
648 /* our buffer */
649 char *buf_;
650
651 /* size of our buffer */
652 size_t buflen_;
653
654 /* current read/write pointer */
655 char *p_;
656 };
657
658 /*
659 * reference-counted buffer
660 */
661 class CVmRefCntBuf: public CVmRefCntObj
662 {
663 public:
664 CVmRefCntBuf(size_t len)
665 { buf_ = lib_alloc_str(len); }
666
667 CVmRefCntBuf(const char *str, size_t len)
668 { buf_ = lib_copy_str(str, len); }
669
670 char *buf_;
671
672 protected:
673 ~CVmRefCntBuf() { lib_free_str(buf_); }
674 };
675
676 /*
677 * Memory stream, using a private allocated buffer
678 */
679 class CVmPrivateMemoryStream: public CVmMemoryStream
680 {
681 public:
682 CVmPrivateMemoryStream(size_t len)
683 : CVmMemoryStream(0, len)
684 {
685 bufobj_ = new CVmRefCntBuf(len);
686 buf_ = bufobj_->buf_;
687 }
688
689 CVmPrivateMemoryStream(const char *str, size_t len)
690 : CVmMemoryStream(0, len)
691 {
692 bufobj_ = new CVmRefCntBuf(str, len);
693 buf_ = bufobj_->buf_;
694 }
695
696 CVmPrivateMemoryStream(CVmRefCntBuf *bufobj, size_t len)
697 : CVmMemoryStream(bufobj->buf_, len)
698 {
699 bufobj->add_ref();
700 bufobj_ = bufobj;
701 }
702
703 CVmStream *clone(VMG_ const char * /*mode*/)
704 { return new CVmPrivateMemoryStream(bufobj_, buflen_); }
705
706 ~CVmPrivateMemoryStream() { bufobj_->release_ref(); }
707
708 protected:
709 CVmRefCntBuf *bufobj_;
710 };
711
712 /*
713 * Read-only memory stream
714 */
715 class CVmReadOnlyMemoryStream: public CVmMemoryStream
716 {
717 public:
718 CVmReadOnlyMemoryStream(const char *buf, size_t len)
719 : CVmMemoryStream((char *)buf, len)
720 {
721 }
722
723 /* disallow writing */
724 void write_bytes(const char *, size_t) { err_throw(VMERR_WRITE_FILE); }
725 };
726
727 /* expandable memory stream block */
728 struct CVmExpandableMemoryStreamBlock
729 {
730 CVmExpandableMemoryStreamBlock(long ofs)
731 {
732 this->ofs = ofs;
733 nxt = 0;
734 }
735
736 /* block length */
737 static const int BlockLen = 4096;
738
739 /* next block in the list */
740 CVmExpandableMemoryStreamBlock *nxt;
741
742 /* byte offset in the overall stream of the start of this block */
743 long ofs;
744
745 /* block buffer */
746 char buf[BlockLen];
747 };
748
749 /* expandable memory stream block list */
750 class CVmExpandableMemoryStreamList: public CVmRefCntObj
751 {
752 public:
753 static const int BlockLen = CVmExpandableMemoryStreamBlock::BlockLen;
754
755 CVmExpandableMemoryStreamList(long init_len)
756 {
757 /* no blocks yet */
758 first_block_ = last_block_ = 0;
759
760 /* always allocate at least the initial block */
761 add_block();
762 init_len -= BlockLen;
763
764 /* set the seek position to the start of the first block */
765 cur_block_ = first_block_;
766 cur_block_ofs_ = 0;
767
768 /* add more blocks until we've satisfied the length request */
769 for ( ; init_len > 0 ; init_len -= BlockLen)
770 add_block();
771
772 /* the file is currently empty */
773 len_ = 0;
774 }
775
776 /* read bytes */
777 void read_bytes(char *buf, size_t len)
778 {
779 /*
780 * if the request would take us past the current content length,
781 * it's an error
782 */
783 if (cur_block_->ofs + cur_block_ofs_ + (long)len > len_)
784 err_throw(VMERR_READ_FILE);
785
786 /* keep going until we satisfy the request */
787 while (len != 0)
788 {
789 /* figure how much we can read from the current block */
790 size_t rem = BlockLen - cur_block_ofs_;
791 size_t cur = (len < rem ? len : rem);
792
793 /* read that much */
794 if (cur != 0)
795 {
796 memcpy(buf, cur_block_->buf + cur_block_ofs_, cur);
797 cur_block_ofs_ += cur;
798 len -= cur;
799 buf += cur;
800 }
801
802 /* if there's more to read, advance to the next block */
803 if (len != 0)
804 {
805 /* if this is the last block, we can't satisfy the request */
806 if (cur_block_->nxt == 0)
807 err_throw(VMERR_READ_FILE);
808
809 /* advance to the start of the next block */
810 cur_block_ = cur_block_->nxt;
811 cur_block_ofs_ = 0;
812 }
813 }
814 }
815
816 /* read bytes, partial read OK */
817 size_t read_nbytes(char *buf, size_t len)
818 {
819 /* figure the number of bytes available */
820 long avail = (long)len_ - (cur_block_->ofs + cur_block_ofs_);
821
822 /* limit the read to the available bytes */
823 if ((long)len > avail)
824 len = (size_t)avail;
825
826 /* if that leaves us with any bytes to read, do the copy */
827 if (len != 0)
828 read_bytes(buf, len);
829
830 /* return the number of bytes transfered */
831 return len;
832 }
833
834 /* read a line */
835 char *read_line(char *buf, size_t len)
836 {
837 /* if already at EOF, or there's no buffer, return null */
838 if (get_seek_pos() >= len_)
839 return 0;
840
841 /* read bytes until we fill the buffer or reach '\n' or EOF */
842 char *dst;
843 size_t rem;
844 for (dst = buf, rem = len ; rem > 1 ; --rem)
845 {
846 /* get this character - stop at EOF */
847 char c;
848 if (!mread_byte(&c, TRUE))
849 break;
850
851 /* check for newlines */
852 if (c == '\n' || c == '\r')
853 {
854 /* write CR and LF as simply CR */
855 *dst++ = '\n';
856
857 /* if we have a CR-LF or LF-CR sequence, skip the pair */
858 char c2;
859 if (mread_byte(&c2, FALSE)
860 && ((c == '\n' && c2 == '\r')
861 || (c == '\r' && c2 == '\n')))
862 {
863 /* skip the second character of the pair */
864 mread_byte(&c2, TRUE);
865 }
866
867 /* done */
868 break;
869 }
870
871 /* copy this character */
872 *dst++ = c;
873 }
874
875 /* add the trailing null and return the buffer */
876 *dst = '\0';
877 return buf;
878 }
879
880 /* write bytes */
881 void write_bytes(const char *buf, size_t len)
882 {
883 /* keep going until we satisfy the request */
884 while (len != 0)
885 {
886 /* figure how much we can write to the current block */
887 size_t rem = BlockLen - cur_block_ofs_;
888 size_t cur = (len < rem ? len : rem);
889
890 /* write that much */
891 if (cur != 0)
892 {
893 memcpy(cur_block_->buf + cur_block_ofs_, buf, cur);
894 cur_block_ofs_ += cur;
895 len -= cur;
896 buf += cur;
897 }
898
899 /* if there's more to write, advance to the next block */
900 if (len != 0)
901 {
902 /* if this is the last block, add a new one */
903 if (cur_block_->nxt == 0)
904 {
905 add_block();
906 if (cur_block_->nxt == 0)
907 err_throw(VMERR_WRITE_FILE);
908 }
909
910 /* advance to the next block */
911 cur_block_ = cur_block_->nxt;
912 cur_block_ofs_ = 0;
913 }
914 }
915
916 /*
917 * if the seek pointer is past the current content length, we've
918 * written past the old end of the file and thus expanded the file
919 * - note the new length
920 */
921 if (cur_block_->ofs + cur_block_ofs_ > len_)
922 len_ = cur_block_->ofs + cur_block_ofs_;
923 }
924
925 /* get the current seek offset */
926 long get_seek_pos() const
927 {
928 /*
929 * figure the seek position as the current block's base offset plus
930 * the current offset within that block
931 */
932 return cur_block_->ofs + cur_block_ofs_;
933 }
934
935 /* set the seek offset */
936 void set_seek_pos(long pos)
937 {
938 /* limit the position to the file's bounds */
939 if (pos < 0)
940 {
941 /* at start of file */
942 pos = 0;
943 }
944 else if (pos >= len_)
945 {
946 /*
947 * At end of file. This is a special case for setting the
948 * block pointer, because we could be positioned at the last
949 * byte of the last block, which we won't find in our scan.
950 * Explicitly set the position here.
951 */
952 pos = len_;
953 cur_block_ = last_block_;
954 cur_block_ofs_ = pos - last_block_->ofs;
955
956 /* we've set the block position, so skip the usual search */
957 return;
958 }
959
960 /* find the block containing the seek offset */
961 CVmExpandableMemoryStreamBlock *b;
962 for (b = first_block_ ; b != 0 ; b = b->nxt)
963 {
964 /* if the offset is within this block, we're done */
965 if (pos >= b->ofs && pos < b->ofs + BlockLen)
966 {
967 /* set the current pointers */
968 cur_block_ = b;
969 cur_block_ofs_ = pos - b->ofs;
970
971 /* stop scanning */
972 break;
973 }
974 }
975 }
976
977 /* get the length of the stream's contents */
978 long get_len() { return len_; }
979
980 protected:
981 ~CVmExpandableMemoryStreamList()
982 {
983 /* delete our block list */
984 CVmExpandableMemoryStreamBlock *cur, *nxt;
985 for (cur = first_block_ ; cur != 0 ; cur = nxt)
986 {
987 nxt = cur->nxt;
988 delete cur;
989 }
990 }
991
992 /* add a block to the end of the list */
993 void add_block()
994 {
995 long ofs = last_block_ == 0 ? 0 : last_block_->ofs + BlockLen;
996 CVmExpandableMemoryStreamBlock *b =
997 new CVmExpandableMemoryStreamBlock(ofs);
998
999 if (last_block_ != 0)
1000 last_block_->nxt = b;
1001 else
1002 first_block_ = b;
1003 last_block_ = b;
1004 }
1005
1006 /*
1007 * read one byte, incrementing the read pointer if desired; returns
1008 * true on success, false on EOF
1009 */
1010 int mread_byte(char *c, int inc)
1011 {
1012 /* check for EOF */
1013 if (cur_block_->ofs + cur_block_ofs_ >= len_)
1014 return FALSE;
1015
1016 /* if we're out of bytes in this block, move to the next block */
1017 if (cur_block_ofs_ >= BlockLen)
1018 {
1019 cur_block_ = cur_block_->nxt;
1020 cur_block_ofs_ = 0;
1021 }
1022
1023 /* set the return byte */
1024 *c = cur_block_->buf[cur_block_ofs_];
1025
1026 /* increment the pointer if desired */
1027 if (inc)
1028 cur_block_ofs_ += 1;
1029
1030 /* success */
1031 return TRUE;
1032 }
1033
1034 /* current seek block and offset */
1035 CVmExpandableMemoryStreamBlock *cur_block_;
1036 long cur_block_ofs_;
1037
1038 /* total file length */
1039 long len_;
1040
1041 /* head/tail of block list */
1042 CVmExpandableMemoryStreamBlock *first_block_;
1043 CVmExpandableMemoryStreamBlock *last_block_;
1044 };
1045
1046 /*
1047 * Expandable memory stream. This automatically allocates additional
1048 * buffer space as needed.
1049 */
1050
1051 class CVmExpandableMemoryStream: public CVmStream
1052 {
1053 public:
1054 CVmExpandableMemoryStream(long init_len)
1055 {
1056 bl = new CVmExpandableMemoryStreamList(init_len);
1057 }
1058
1059 virtual CVmStream *clone(VMG_ const char * /*mode*/)
1060 { return new CVmExpandableMemoryStream(bl); }
1061
1062 ~CVmExpandableMemoryStream() { bl->release_ref(); }
1063
1064 /* read bytes */
1065 virtual void read_bytes(char *buf, size_t len)
1066 { bl->read_bytes(buf, len); }
1067
1068 /* read bytes, partial read OK */
1069 virtual size_t read_nbytes(char *buf, size_t len)
1070 { return bl->read_nbytes(buf, len); }
1071
1072 /* read a line */
1073 virtual char *read_line(char *buf, size_t len)
1074 { return bl->read_line(buf, len); }
1075
1076 /* write bytes */
1077 virtual void write_bytes(const char *buf, size_t len)
1078 { bl->write_bytes(buf, len); }
1079
1080 /* get the current seek offset */
1081 virtual long get_seek_pos() const
1082 { return bl->get_seek_pos(); }
1083
1084 /* set the seek offset */
1085 virtual void set_seek_pos(long pos)
1086 { bl->set_seek_pos(pos); }
1087
1088 /* get the length of the stream's contents */
1089 virtual long get_len()
1090 { return bl->get_len(); }
1091
1092 protected:
1093 CVmExpandableMemoryStream(CVmExpandableMemoryStreamList *bl)
1094 {
1095 bl->add_ref();
1096 this->bl = bl;
1097 }
1098
1099 CVmExpandableMemoryStreamList *bl;
1100 };
1101
1102 #endif /* VMFILE_H */
1103