Merge branch 'master' of ssh+git://git.sv.gnu.org/srv/git/lilypond
[lilypond.git] / flower / memory-stream.cc
blob863f4bd4def2de6fb785178de84d495ed70e9937
1 /*
2 memory-stream.cc -- implement Memory_out_stream
4 source file of the GNU LilyPond music typesetter
6 (c) 2005--2007 Han-Wen Nienhuys <hanwen@xs4all.nl>
7 */
9 #include <cassert>
10 #include <cstring>
11 #include <cstdlib>
12 using namespace std;
14 #include "memory-stream.hh"
17 TODO: add read support as well.
19 const int Memory_out_stream::block_size_ = 1024;
21 lily_cookie_io_functions_t
22 Memory_out_stream::functions_
23 = {
24 Memory_out_stream::reader,
25 Memory_out_stream::writer,
26 Memory_out_stream::seeker,
27 Memory_out_stream::cleaner
30 int
31 Memory_out_stream::cleaner (void *cookie)
33 Memory_out_stream *stream = (Memory_out_stream *) cookie;
35 stream->file_ = 0;
36 return 0;
39 Memory_out_stream::Memory_out_stream ()
41 size_ = 0;
42 buffer_ = 0;
43 buffer_blocks_ = 0;
44 file_ = 0;
46 #if 0
47 file_ = fopencookie ((void *) this, "w", functions_);
48 #endif
51 Memory_out_stream::~Memory_out_stream ()
53 if (file_)
54 fclose (file_);
56 free (buffer_);
59 FILE *
60 Memory_out_stream::get_file () const
62 return file_;
65 ssize_t
66 Memory_out_stream::get_length () const
68 return size_;
71 char const *
72 Memory_out_stream::get_string () const
74 return buffer_;
77 ssize_t
78 Memory_out_stream::writer (void *cookie,
79 char const *buffer,
80 size_t size)
82 Memory_out_stream *stream = (Memory_out_stream *) cookie;
84 ssize_t newsize = stream->size_ + size;
86 bool change = false;
87 while (newsize > stream->buffer_blocks_ * block_size_)
89 stream->buffer_blocks_ *= 2;
90 stream->buffer_blocks_ += 1;
91 change = true;
94 if (change)
95 stream->buffer_ = (char *) realloc (stream->buffer_,
96 stream->buffer_blocks_ * block_size_);
98 memcpy (stream->buffer_ + stream->size_, buffer, size);
99 stream->size_ = newsize;
101 return size;
104 ssize_t
105 Memory_out_stream::reader (void *cookie,
106 char *buffer,
107 size_t size)
109 (void) cookie;
110 (void) buffer;
111 (void) size;
113 assert (false);
114 return 0;
118 Memory_out_stream::seeker (void *, off64_t *, int whence)
120 (void) whence;
122 assert (false);
123 return 0;