Use a bytevector as the backing buffer of string ports.
[bpt/guile.git] / libguile / strports.c
1 /* Copyright (C) 1995,1996,1998,1999,2000,2001,2002, 2003, 2005, 2006, 2009, 2010, 2011 Free Software Foundation, Inc.
2 *
3 * This library is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU Lesser General Public License
5 * as published by the Free Software Foundation; either version 3 of
6 * the License, or (at your option) any later version.
7 *
8 * This library is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * Lesser General Public License for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public
14 * License along with this library; if not, write to the Free Software
15 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
16 * 02110-1301 USA
17 */
18
19
20 \f
21
22 #ifdef HAVE_CONFIG_H
23 # include <config.h>
24 #endif
25
26 #include "libguile/_scm.h"
27
28 #include <stdio.h>
29 #ifdef HAVE_UNISTD_H
30 #include <unistd.h>
31 #endif
32
33 #include "libguile/bytevectors.h"
34 #include "libguile/eval.h"
35 #include "libguile/ports.h"
36 #include "libguile/read.h"
37 #include "libguile/root.h"
38 #include "libguile/strings.h"
39 #include "libguile/modules.h"
40 #include "libguile/validate.h"
41 #include "libguile/deprecation.h"
42 #include "libguile/srfi-4.h"
43
44 #include "libguile/strports.h"
45
46 #ifdef HAVE_STRING_H
47 #include <string.h>
48 #endif
49
50 \f
51
52 /* {Ports - string ports}
53 *
54 */
55
56 /* NOTES:
57
58 write_buf/write_end point to the ends of the allocated bytevector.
59 read_buf/read_end in principle point to the part of the bytevector which
60 has been written to, but this is only updated after a flush.
61 read_pos and write_pos in principle should be equal, but this is only true
62 when rw_active is SCM_PORT_NEITHER.
63
64 ENHANCE-ME - output blocks:
65
66 The current code keeps an output string as a single block. That means
67 when the size is increased the entire old contents must be copied. It'd
68 be more efficient to begin a new block when the old one is full, so
69 there's no re-copying of previous data.
70
71 To make seeking efficient, keeping the pieces in a vector might be best,
72 though appending is probably the most common operation. The size of each
73 block could be progressively increased, so the bigger the string the
74 bigger the blocks.
75
76 When `get-output-string' is called the blocks have to be coalesced into a
77 string, the result could be kept as a single big block. If blocks were
78 strings then `get-output-string' could notice when there's just one and
79 return that with a copy-on-write (though repeated calls to
80 `get-output-string' are probably unlikely).
81
82 Another possibility would be to extend the port mechanism to let SCM
83 strings come through directly from `display' and friends. That way if a
84 big string is written it can be kept as a copy-on-write, saving time
85 copying and maybe saving some space. */
86
87
88 scm_t_bits scm_tc16_strport;
89
90
91 static int
92 stfill_buffer (SCM port)
93 {
94 scm_t_port *pt = SCM_PTAB_ENTRY (port);
95
96 if (pt->read_pos >= pt->read_end)
97 return EOF;
98 else
99 return scm_return_first_int (*pt->read_pos, port);
100 }
101
102 /* Change the size of a port's bytevector to NEW_SIZE. This doesn't
103 change `read_buf_size'. */
104 static void
105 st_resize_port (scm_t_port *pt, scm_t_off new_size)
106 {
107 SCM old_stream = SCM_PACK (pt->stream);
108 const signed char *src = SCM_BYTEVECTOR_CONTENTS (old_stream);
109 SCM new_stream = scm_c_make_bytevector (new_size);
110 signed char *dst = SCM_BYTEVECTOR_CONTENTS (new_stream);
111 unsigned long int old_size = SCM_BYTEVECTOR_LENGTH (old_stream);
112 unsigned long int min_size = min (old_size, new_size);
113
114 scm_t_off index = pt->write_pos - pt->write_buf;
115
116 pt->write_buf_size = new_size;
117
118 memcpy (dst, src, min_size);
119
120 scm_remember_upto_here_1 (old_stream);
121
122 /* reset buffer. */
123 {
124 pt->stream = SCM_UNPACK (new_stream);
125 pt->read_buf = pt->write_buf = (unsigned char *)dst;
126 pt->read_pos = pt->write_pos = pt->write_buf + index;
127 pt->write_end = pt->write_buf + pt->write_buf_size;
128 pt->read_end = pt->read_buf + pt->read_buf_size;
129 }
130 }
131
132 /* amount by which write_buf is expanded. */
133 #define SCM_WRITE_BLOCK 80
134
135 /* ensure that write_pos < write_end by enlarging the buffer when
136 necessary. update read_buf to account for written chars.
137
138 The buffer is enlarged by 1.5 times, plus SCM_WRITE_BLOCK. Adding just a
139 fixed amount is no good, because there's a block copy for each increment,
140 and that copying would take quadratic time. In the past it was found to
141 be very slow just adding 80 bytes each time (eg. about 10 seconds for
142 writing a 100kbyte string). */
143
144 static void
145 st_flush (SCM port)
146 {
147 scm_t_port *pt = SCM_PTAB_ENTRY (port);
148
149 if (pt->write_pos == pt->write_end)
150 {
151 st_resize_port (pt, pt->write_buf_size * 3 / 2 + SCM_WRITE_BLOCK);
152 }
153 pt->read_pos = pt->write_pos;
154 if (pt->read_pos > pt->read_end)
155 {
156 pt->read_end = (unsigned char *) pt->read_pos;
157 pt->read_buf_size = pt->read_end - pt->read_buf;
158 }
159 pt->rw_active = SCM_PORT_NEITHER;
160 }
161
162 static void
163 st_write (SCM port, const void *data, size_t size)
164 {
165 scm_t_port *pt = SCM_PTAB_ENTRY (port);
166 const char *input = (char *) data;
167
168 while (size > 0)
169 {
170 int space = pt->write_end - pt->write_pos;
171 int write_len = (size > space) ? space : size;
172
173 memcpy ((char *) pt->write_pos, input, write_len);
174 pt->write_pos += write_len;
175 size -= write_len;
176 input += write_len;
177 if (write_len == space)
178 st_flush (port);
179 }
180 }
181
182 static void
183 st_end_input (SCM port, int offset)
184 {
185 scm_t_port *pt = SCM_PTAB_ENTRY (port);
186
187 if (pt->read_pos - pt->read_buf < offset)
188 scm_misc_error ("st_end_input", "negative position", SCM_EOL);
189
190 pt->write_pos = (unsigned char *) (pt->read_pos = pt->read_pos - offset);
191 pt->rw_active = SCM_PORT_NEITHER;
192 }
193
194 static scm_t_off
195 st_seek (SCM port, scm_t_off offset, int whence)
196 {
197 scm_t_port *pt = SCM_PTAB_ENTRY (port);
198 scm_t_off target;
199
200 if (pt->rw_active == SCM_PORT_READ && offset == 0 && whence == SEEK_CUR)
201 /* special case to avoid disturbing the unread-char buffer. */
202 {
203 if (pt->read_buf == pt->putback_buf)
204 {
205 target = pt->saved_read_pos - pt->saved_read_buf
206 - (pt->read_end - pt->read_pos);
207 }
208 else
209 {
210 target = pt->read_pos - pt->read_buf;
211 }
212 }
213 else
214 /* all other cases. */
215 {
216 if (pt->rw_active == SCM_PORT_WRITE)
217 st_flush (port);
218
219 if (pt->rw_active == SCM_PORT_READ)
220 scm_end_input (port);
221
222 switch (whence)
223 {
224 case SEEK_CUR:
225 target = pt->read_pos - pt->read_buf + offset;
226 break;
227 case SEEK_END:
228 target = pt->read_end - pt->read_buf + offset;
229 break;
230 default: /* SEEK_SET */
231 target = offset;
232 break;
233 }
234
235 if (target < 0)
236 scm_misc_error ("st_seek", "negative offset", SCM_EOL);
237
238 if (target >= pt->write_buf_size)
239 {
240 if (!(SCM_CELL_WORD_0 (port) & SCM_WRTNG))
241 {
242 if (target > pt->write_buf_size)
243 {
244 scm_misc_error ("st_seek",
245 "seek past end of read-only strport",
246 SCM_EOL);
247 }
248 }
249 else
250 {
251 st_resize_port (pt, target + (target == pt->write_buf_size
252 ? SCM_WRITE_BLOCK
253 : 0));
254 }
255 }
256 pt->read_pos = pt->write_pos = pt->read_buf + target;
257 if (pt->read_pos > pt->read_end)
258 {
259 pt->read_end = (unsigned char *) pt->read_pos;
260 pt->read_buf_size = pt->read_end - pt->read_buf;
261 }
262 }
263 return target;
264 }
265
266 static void
267 st_truncate (SCM port, scm_t_off length)
268 {
269 scm_t_port *pt = SCM_PTAB_ENTRY (port);
270
271 if (length > pt->write_buf_size)
272 st_resize_port (pt, length);
273
274 pt->read_buf_size = length;
275 pt->read_end = pt->read_buf + length;
276 if (pt->read_pos > pt->read_end)
277 pt->read_pos = pt->read_end;
278
279 if (pt->write_pos > pt->read_end)
280 pt->write_pos = pt->read_end;
281 }
282
283 SCM
284 scm_mkstrport (SCM pos, SCM str, long modes, const char *caller)
285 {
286 SCM z, buf;
287 scm_t_port *pt;
288 size_t str_len, c_pos;
289 char *c_buf;
290
291 if (!((modes & SCM_WRTNG) || (modes & SCM_RDNG)))
292 scm_misc_error ("scm_mkstrport", "port must read or write", SCM_EOL);
293
294 scm_dynwind_begin (0);
295 scm_i_dynwind_pthread_mutex_lock (&scm_i_port_table_mutex);
296
297 z = scm_new_port_table_entry (scm_tc16_strport);
298 pt = SCM_PTAB_ENTRY(z);
299
300 {
301 /* STR is a string. */
302 char *copy;
303
304 SCM_ASSERT (scm_is_string (str), str, SCM_ARG1, caller);
305
306 /* Create a copy of STR in the encoding of PT. */
307 copy = scm_to_stringn (str, &str_len, pt->encoding,
308 SCM_FAILED_CONVERSION_ERROR);
309 buf = scm_c_make_bytevector (str_len);
310 c_buf = (char *) SCM_BYTEVECTOR_CONTENTS (buf);
311 memcpy (c_buf, copy, str_len);
312 free (copy);
313
314 c_pos = scm_to_unsigned_integer (pos, 0, str_len);
315 pt->read_buf_size = str_len;
316 }
317
318 SCM_SETSTREAM (z, SCM_UNPACK (buf));
319 SCM_SET_CELL_TYPE (z, scm_tc16_strport | modes);
320
321 pt->write_buf = pt->read_buf = (unsigned char *) c_buf;
322 pt->read_pos = pt->write_pos = pt->read_buf + c_pos;
323 pt->write_buf_size = str_len;
324 pt->write_end = pt->read_end = pt->read_buf + pt->read_buf_size;
325
326 pt->rw_random = 1;
327
328 scm_dynwind_end ();
329
330 /* Ensure WRITE_POS is writable. */
331 if ((modes & SCM_WRTNG) && pt->write_pos == pt->write_end)
332 st_flush (z);
333
334 scm_i_set_conversion_strategy_x (z, SCM_FAILED_CONVERSION_ERROR);
335 return z;
336 }
337
338 /* Create a new string from the buffer of PORT, a string port, converting from
339 PORT's encoding to the standard string representation. */
340 SCM
341 scm_strport_to_string (SCM port)
342 {
343 SCM str;
344 scm_t_port *pt = SCM_PTAB_ENTRY (port);
345
346 if (pt->rw_active == SCM_PORT_WRITE)
347 st_flush (port);
348
349 if (pt->read_buf_size == 0)
350 return scm_nullstr;
351
352 if (pt->encoding == NULL)
353 {
354 char *buf;
355 str = scm_i_make_string (pt->read_buf_size, &buf);
356 memcpy (buf, pt->read_buf, pt->read_buf_size);
357 }
358 else
359 str = scm_from_stringn ((char *)pt->read_buf, pt->read_buf_size,
360 pt->encoding, pt->ilseq_handler);
361 scm_remember_upto_here_1 (port);
362 return str;
363 }
364
365 SCM_DEFINE (scm_object_to_string, "object->string", 1, 1, 0,
366 (SCM obj, SCM printer),
367 "Return a Scheme string obtained by printing @var{obj}.\n"
368 "Printing function can be specified by the optional second\n"
369 "argument @var{printer} (default: @code{write}).")
370 #define FUNC_NAME s_scm_object_to_string
371 {
372 SCM str, port;
373
374 if (!SCM_UNBNDP (printer))
375 SCM_VALIDATE_PROC (2, printer);
376
377 str = scm_c_make_string (0, SCM_UNDEFINED);
378 port = scm_mkstrport (SCM_INUM0, str, SCM_OPN | SCM_WRTNG, FUNC_NAME);
379
380 if (SCM_UNBNDP (printer))
381 scm_write (obj, port);
382 else
383 scm_call_2 (printer, obj, port);
384
385 return scm_strport_to_string (port);
386 }
387 #undef FUNC_NAME
388
389 SCM_DEFINE (scm_call_with_output_string, "call-with-output-string", 1, 0, 0,
390 (SCM proc),
391 "Calls the one-argument procedure @var{proc} with a newly created output\n"
392 "port. When the function returns, the string composed of the characters\n"
393 "written into the port is returned.")
394 #define FUNC_NAME s_scm_call_with_output_string
395 {
396 SCM p;
397
398 p = scm_mkstrport (SCM_INUM0,
399 scm_make_string (SCM_INUM0, SCM_UNDEFINED),
400 SCM_OPN | SCM_WRTNG,
401 FUNC_NAME);
402 scm_call_1 (proc, p);
403
404 return scm_get_output_string (p);
405 }
406 #undef FUNC_NAME
407
408 SCM_DEFINE (scm_call_with_input_string, "call-with-input-string", 2, 0, 0,
409 (SCM string, SCM proc),
410 "Calls the one-argument procedure @var{proc} with a newly\n"
411 "created input port from which @var{string}'s contents may be\n"
412 "read. The value yielded by the @var{proc} is returned.")
413 #define FUNC_NAME s_scm_call_with_input_string
414 {
415 SCM p = scm_mkstrport(SCM_INUM0, string, SCM_OPN | SCM_RDNG, FUNC_NAME);
416 return scm_call_1 (proc, p);
417 }
418 #undef FUNC_NAME
419
420 SCM_DEFINE (scm_open_input_string, "open-input-string", 1, 0, 0,
421 (SCM str),
422 "Take a string and return an input port that delivers characters\n"
423 "from the string. The port can be closed by\n"
424 "@code{close-input-port}, though its storage will be reclaimed\n"
425 "by the garbage collector if it becomes inaccessible.")
426 #define FUNC_NAME s_scm_open_input_string
427 {
428 SCM p = scm_mkstrport(SCM_INUM0, str, SCM_OPN | SCM_RDNG, FUNC_NAME);
429 return p;
430 }
431 #undef FUNC_NAME
432
433 SCM_DEFINE (scm_open_output_string, "open-output-string", 0, 0, 0,
434 (void),
435 "Return an output port that will accumulate characters for\n"
436 "retrieval by @code{get-output-string}. The port can be closed\n"
437 "by the procedure @code{close-output-port}, though its storage\n"
438 "will be reclaimed by the garbage collector if it becomes\n"
439 "inaccessible.")
440 #define FUNC_NAME s_scm_open_output_string
441 {
442 SCM p;
443
444 p = scm_mkstrport (SCM_INUM0,
445 scm_make_string (SCM_INUM0, SCM_UNDEFINED),
446 SCM_OPN | SCM_WRTNG,
447 FUNC_NAME);
448 return p;
449 }
450 #undef FUNC_NAME
451
452 SCM_DEFINE (scm_get_output_string, "get-output-string", 1, 0, 0,
453 (SCM port),
454 "Given an output port created by @code{open-output-string},\n"
455 "return a string consisting of the characters that have been\n"
456 "output to the port so far.")
457 #define FUNC_NAME s_scm_get_output_string
458 {
459 SCM_VALIDATE_OPOUTSTRPORT (1, port);
460 return scm_strport_to_string (port);
461 }
462 #undef FUNC_NAME
463
464
465 /* Given a null-terminated string EXPR containing a Scheme expression
466 read it, and return it as an SCM value. */
467 SCM
468 scm_c_read_string (const char *expr)
469 {
470 /* FIXME: the c string gets packed into a string, only to get
471 immediately unpacked in scm_mkstrport. */
472 SCM port = scm_mkstrport (SCM_INUM0,
473 scm_from_locale_string (expr),
474 SCM_OPN | SCM_RDNG,
475 "scm_c_read_string");
476 SCM form;
477
478 form = scm_read (port);
479
480 scm_close_port (port);
481 return form;
482 }
483
484 /* Given a null-terminated string EXPR containing Scheme program text,
485 evaluate it, and return the result of the last expression evaluated. */
486 SCM
487 scm_c_eval_string (const char *expr)
488 {
489 return scm_eval_string (scm_from_locale_string (expr));
490 }
491
492 SCM
493 scm_c_eval_string_in_module (const char *expr, SCM module)
494 {
495 return scm_eval_string_in_module (scm_from_locale_string (expr), module);
496 }
497
498
499 static SCM
500 inner_eval_string (void *data)
501 {
502 SCM port = (SCM)data;
503 SCM form;
504 SCM ans = SCM_UNSPECIFIED;
505
506 /* Read expressions from that port; ignore the values. */
507 while (!SCM_EOF_OBJECT_P (form = scm_read (port)))
508 ans = scm_primitive_eval_x (form);
509
510 /* Don't close the port here; if we re-enter this function via a
511 continuation, then the next time we enter it, we'll get an error.
512 It's a string port anyway, so there's no advantage to closing it
513 early. */
514
515 return ans;
516 }
517
518 SCM_DEFINE (scm_eval_string_in_module, "eval-string", 1, 1, 0,
519 (SCM string, SCM module),
520 "Evaluate @var{string} as the text representation of a Scheme\n"
521 "form or forms, and return whatever value they produce.\n"
522 "Evaluation takes place in the given module, or the current\n"
523 "module when no module is given.\n"
524 "While the code is evaluated, the given module is made the\n"
525 "current one. The current module is restored when this\n"
526 "procedure returns.")
527 #define FUNC_NAME s_scm_eval_string_in_module
528 {
529 SCM port = scm_mkstrport (SCM_INUM0, string, SCM_OPN | SCM_RDNG,
530 FUNC_NAME);
531 if (SCM_UNBNDP (module))
532 module = scm_current_module ();
533 else
534 SCM_VALIDATE_MODULE (2, module);
535 return scm_c_call_with_current_module (module,
536 inner_eval_string, (void *)port);
537 }
538 #undef FUNC_NAME
539
540 SCM
541 scm_eval_string (SCM string)
542 {
543 return scm_eval_string_in_module (string, SCM_UNDEFINED);
544 }
545
546 static scm_t_bits
547 scm_make_stptob ()
548 {
549 scm_t_bits tc = scm_make_port_type ("string", stfill_buffer, st_write);
550
551 scm_set_port_end_input (tc, st_end_input);
552 scm_set_port_flush (tc, st_flush);
553 scm_set_port_seek (tc, st_seek);
554 scm_set_port_truncate (tc, st_truncate);
555
556 return tc;
557 }
558
559 void
560 scm_init_strports ()
561 {
562 scm_tc16_strport = scm_make_stptob ();
563
564 #include "libguile/strports.x"
565 }
566
567
568 /*
569 Local Variables:
570 c-file-style: "gnu"
571 End:
572 */