Merge remote-tracking branch 'origin/stable-2.0'
[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 /* Ensure that `write_pos' < `write_end' by enlarging the buffer when
133 necessary. Update `read_buf' to account for written chars. The
134 buffer is enlarged geometrically. */
135 static void
136 st_flush (SCM port)
137 {
138 scm_t_port *pt = SCM_PTAB_ENTRY (port);
139
140 if (pt->write_pos == pt->write_end)
141 st_resize_port (pt, pt->write_buf_size * 2);
142
143 pt->read_pos = pt->write_pos;
144 if (pt->read_pos > pt->read_end)
145 {
146 pt->read_end = (unsigned char *) pt->read_pos;
147 pt->read_buf_size = pt->read_end - pt->read_buf;
148 }
149 pt->rw_active = SCM_PORT_NEITHER;
150 }
151
152 static void
153 st_write (SCM port, const void *data, size_t size)
154 {
155 scm_t_port *pt = SCM_PTAB_ENTRY (port);
156 const char *input = (char *) data;
157
158 while (size > 0)
159 {
160 int space = pt->write_end - pt->write_pos;
161 int write_len = (size > space) ? space : size;
162
163 memcpy ((char *) pt->write_pos, input, write_len);
164 pt->write_pos += write_len;
165 size -= write_len;
166 input += write_len;
167 if (write_len == space)
168 st_flush (port);
169 }
170 }
171
172 static void
173 st_end_input (SCM port, int offset)
174 {
175 scm_t_port *pt = SCM_PTAB_ENTRY (port);
176
177 if (pt->read_pos - pt->read_buf < offset)
178 scm_misc_error ("st_end_input", "negative position", SCM_EOL);
179
180 pt->write_pos = (unsigned char *) (pt->read_pos = pt->read_pos - offset);
181 pt->rw_active = SCM_PORT_NEITHER;
182 }
183
184 static scm_t_off
185 st_seek (SCM port, scm_t_off offset, int whence)
186 {
187 scm_t_port *pt = SCM_PTAB_ENTRY (port);
188 scm_t_off target;
189
190 if (pt->rw_active == SCM_PORT_READ && offset == 0 && whence == SEEK_CUR)
191 /* special case to avoid disturbing the unread-char buffer. */
192 {
193 if (pt->read_buf == pt->putback_buf)
194 {
195 target = pt->saved_read_pos - pt->saved_read_buf
196 - (pt->read_end - pt->read_pos);
197 }
198 else
199 {
200 target = pt->read_pos - pt->read_buf;
201 }
202 }
203 else
204 /* all other cases. */
205 {
206 if (pt->rw_active == SCM_PORT_WRITE)
207 st_flush (port);
208
209 if (pt->rw_active == SCM_PORT_READ)
210 scm_end_input_unlocked (port);
211
212 switch (whence)
213 {
214 case SEEK_CUR:
215 target = pt->read_pos - pt->read_buf + offset;
216 break;
217 case SEEK_END:
218 target = pt->read_end - pt->read_buf + offset;
219 break;
220 default: /* SEEK_SET */
221 target = offset;
222 break;
223 }
224
225 if (target < 0)
226 scm_misc_error ("st_seek", "negative offset", SCM_EOL);
227
228 if (target >= pt->write_buf_size)
229 {
230 if (!(SCM_CELL_WORD_0 (port) & SCM_WRTNG))
231 {
232 if (target > pt->write_buf_size)
233 {
234 scm_misc_error ("st_seek",
235 "seek past end of read-only strport",
236 SCM_EOL);
237 }
238 }
239 else if (target == pt->write_buf_size)
240 st_resize_port (pt, target * 2);
241 }
242 pt->read_pos = pt->write_pos = pt->read_buf + target;
243 if (pt->read_pos > pt->read_end)
244 {
245 pt->read_end = (unsigned char *) pt->read_pos;
246 pt->read_buf_size = pt->read_end - pt->read_buf;
247 }
248 }
249 return target;
250 }
251
252 static void
253 st_truncate (SCM port, scm_t_off length)
254 {
255 scm_t_port *pt = SCM_PTAB_ENTRY (port);
256
257 if (length > pt->write_buf_size)
258 st_resize_port (pt, length);
259
260 pt->read_buf_size = length;
261 pt->read_end = pt->read_buf + length;
262 if (pt->read_pos > pt->read_end)
263 pt->read_pos = pt->read_end;
264
265 if (pt->write_pos > pt->read_end)
266 pt->write_pos = pt->read_end;
267 }
268
269 /* The initial size in bytes of a string port's buffer. */
270 #define INITIAL_BUFFER_SIZE 128
271
272 /* Return a new string port with MODES. If STR is #f, a new backing
273 buffer is allocated; otherwise STR must be a string and a copy of it
274 serves as the buffer for the new port. */
275 SCM
276 scm_mkstrport (SCM pos, SCM str, long modes, const char *caller)
277 {
278 SCM z, buf;
279 scm_t_port *pt;
280 const char *encoding;
281 size_t read_buf_size, str_len, c_pos;
282 char *c_buf;
283
284 if (!((modes & SCM_WRTNG) || (modes & SCM_RDNG)))
285 scm_misc_error ("scm_mkstrport", "port must read or write", SCM_EOL);
286
287 encoding = scm_i_default_port_encoding ();
288
289 if (scm_is_false (str))
290 {
291 /* Allocate a new buffer to write to. */
292 str_len = INITIAL_BUFFER_SIZE;
293 buf = scm_c_make_bytevector (str_len);
294 c_buf = (char *) SCM_BYTEVECTOR_CONTENTS (buf);
295
296 /* Reset `read_buf_size'. It will contain the actual number of
297 bytes written to the port. */
298 read_buf_size = 0;
299 c_pos = 0;
300 }
301 else
302 {
303 /* STR is a string. */
304 char *copy;
305
306 SCM_ASSERT (scm_is_string (str), str, SCM_ARG1, caller);
307
308 /* Create a copy of STR in ENCODING. */
309 copy = scm_to_stringn (str, &str_len, encoding,
310 SCM_FAILED_CONVERSION_ERROR);
311 buf = scm_c_make_bytevector (str_len);
312 c_buf = (char *) SCM_BYTEVECTOR_CONTENTS (buf);
313 memcpy (c_buf, copy, str_len);
314 free (copy);
315
316 c_pos = scm_to_unsigned_integer (pos, 0, str_len);
317 read_buf_size = str_len;
318 }
319
320 z = scm_c_make_port_with_encoding (scm_tc16_strport, modes,
321 encoding,
322 SCM_FAILED_CONVERSION_ERROR,
323 (scm_t_bits)buf);
324
325 pt = SCM_PTAB_ENTRY (z);
326 pt->write_buf = pt->read_buf = (unsigned char *) c_buf;
327 pt->read_pos = pt->write_pos = pt->read_buf + c_pos;
328 pt->read_buf_size = read_buf_size;
329 pt->write_buf_size = str_len;
330 pt->write_end = pt->read_end = pt->read_buf + pt->read_buf_size;
331 pt->rw_random = 1;
332
333 /* Ensure WRITE_POS is writable. */
334 if ((modes & SCM_WRTNG) && pt->write_pos == pt->write_end)
335 st_flush (z);
336
337 return z;
338 }
339
340 /* Create a new string from the buffer of PORT, a string port, converting from
341 PORT's encoding to the standard string representation. */
342 SCM
343 scm_strport_to_string (SCM port)
344 {
345 SCM str;
346 scm_t_port *pt = SCM_PTAB_ENTRY (port);
347
348 if (pt->rw_active == SCM_PORT_WRITE)
349 st_flush (port);
350
351 if (pt->read_buf_size == 0)
352 return scm_nullstr;
353
354 if (pt->encoding == NULL)
355 {
356 char *buf;
357 str = scm_i_make_string (pt->read_buf_size, &buf, 0);
358 memcpy (buf, pt->read_buf, pt->read_buf_size);
359 }
360 else
361 str = scm_from_stringn ((char *)pt->read_buf, pt->read_buf_size,
362 pt->encoding, pt->ilseq_handler);
363 scm_remember_upto_here_1 (port);
364 return str;
365 }
366
367 SCM_DEFINE (scm_object_to_string, "object->string", 1, 1, 0,
368 (SCM obj, SCM printer),
369 "Return a Scheme string obtained by printing @var{obj}.\n"
370 "Printing function can be specified by the optional second\n"
371 "argument @var{printer} (default: @code{write}).")
372 #define FUNC_NAME s_scm_object_to_string
373 {
374 SCM port, result;
375
376 if (!SCM_UNBNDP (printer))
377 SCM_VALIDATE_PROC (2, printer);
378
379 port = scm_mkstrport (SCM_INUM0, SCM_BOOL_F,
380 SCM_OPN | SCM_WRTNG, FUNC_NAME);
381
382 if (SCM_UNBNDP (printer))
383 scm_write (obj, port);
384 else
385 scm_call_2 (printer, obj, port);
386
387 result = scm_strport_to_string (port);
388
389 /* Explicitly close PORT so that the iconv CDs associated with it are
390 deallocated right away. This is important because CDs use a lot of
391 memory that's not visible to the GC, so not freeing them can lead
392 to almost large heap usage. See
393 <http://wingolog.org/archives/2011/02/25/ports-weaks-gc-and-dark-matter>
394 for details. */
395 scm_close_port (port);
396
397 return result;
398 }
399 #undef FUNC_NAME
400
401 SCM_DEFINE (scm_call_with_output_string, "call-with-output-string", 1, 0, 0,
402 (SCM proc),
403 "Calls the one-argument procedure @var{proc} with a newly created output\n"
404 "port. When the function returns, the string composed of the characters\n"
405 "written into the port is returned.")
406 #define FUNC_NAME s_scm_call_with_output_string
407 {
408 SCM p;
409
410 p = scm_mkstrport (SCM_INUM0, SCM_BOOL_F,
411 SCM_OPN | SCM_WRTNG,
412 FUNC_NAME);
413 scm_call_1 (proc, p);
414
415 return scm_get_output_string (p);
416 }
417 #undef FUNC_NAME
418
419 SCM_DEFINE (scm_call_with_input_string, "call-with-input-string", 2, 0, 0,
420 (SCM string, SCM proc),
421 "Calls the one-argument procedure @var{proc} with a newly\n"
422 "created input port from which @var{string}'s contents may be\n"
423 "read. The value yielded by the @var{proc} is returned.")
424 #define FUNC_NAME s_scm_call_with_input_string
425 {
426 SCM p = scm_mkstrport(SCM_INUM0, string, SCM_OPN | SCM_RDNG, FUNC_NAME);
427 return scm_call_1 (proc, p);
428 }
429 #undef FUNC_NAME
430
431 SCM_DEFINE (scm_open_input_string, "open-input-string", 1, 0, 0,
432 (SCM str),
433 "Take a string and return an input port that delivers characters\n"
434 "from the string. The port can be closed by\n"
435 "@code{close-input-port}, though its storage will be reclaimed\n"
436 "by the garbage collector if it becomes inaccessible.")
437 #define FUNC_NAME s_scm_open_input_string
438 {
439 SCM p = scm_mkstrport(SCM_INUM0, str, SCM_OPN | SCM_RDNG, FUNC_NAME);
440 return p;
441 }
442 #undef FUNC_NAME
443
444 SCM_DEFINE (scm_open_output_string, "open-output-string", 0, 0, 0,
445 (void),
446 "Return an output port that will accumulate characters for\n"
447 "retrieval by @code{get-output-string}. The port can be closed\n"
448 "by the procedure @code{close-output-port}, though its storage\n"
449 "will be reclaimed by the garbage collector if it becomes\n"
450 "inaccessible.")
451 #define FUNC_NAME s_scm_open_output_string
452 {
453 SCM p;
454
455 p = scm_mkstrport (SCM_INUM0, SCM_BOOL_F,
456 SCM_OPN | SCM_WRTNG,
457 FUNC_NAME);
458 return p;
459 }
460 #undef FUNC_NAME
461
462 SCM_DEFINE (scm_get_output_string, "get-output-string", 1, 0, 0,
463 (SCM port),
464 "Given an output port created by @code{open-output-string},\n"
465 "return a string consisting of the characters that have been\n"
466 "output to the port so far.")
467 #define FUNC_NAME s_scm_get_output_string
468 {
469 SCM_VALIDATE_OPOUTSTRPORT (1, port);
470 return scm_strport_to_string (port);
471 }
472 #undef FUNC_NAME
473
474
475 /* Given a null-terminated string EXPR containing a Scheme expression
476 read it, and return it as an SCM value. */
477 SCM
478 scm_c_read_string (const char *expr)
479 {
480 SCM port = scm_mkstrport (SCM_INUM0,
481 scm_from_locale_string (expr),
482 SCM_OPN | SCM_RDNG,
483 "scm_c_read_string");
484 SCM form;
485
486 form = scm_read (port);
487
488 scm_close_port (port);
489 return form;
490 }
491
492 /* Given a null-terminated string EXPR containing Scheme program text,
493 evaluate it, and return the result of the last expression evaluated. */
494 SCM
495 scm_c_eval_string (const char *expr)
496 {
497 return scm_eval_string (scm_from_locale_string (expr));
498 }
499
500 SCM
501 scm_c_eval_string_in_module (const char *expr, SCM module)
502 {
503 return scm_eval_string_in_module (scm_from_locale_string (expr), module);
504 }
505
506
507 SCM_DEFINE (scm_eval_string_in_module, "eval-string", 1, 1, 0,
508 (SCM string, SCM module),
509 "Evaluate @var{string} as the text representation of a Scheme\n"
510 "form or forms, and return whatever value they produce.\n"
511 "Evaluation takes place in the given module, or the current\n"
512 "module when no module is given.\n"
513 "While the code is evaluated, the given module is made the\n"
514 "current one. The current module is restored when this\n"
515 "procedure returns.")
516 #define FUNC_NAME s_scm_eval_string_in_module
517 {
518 static SCM eval_string = SCM_BOOL_F, k_module = SCM_BOOL_F;
519
520 if (scm_is_false (eval_string))
521 {
522 eval_string = scm_c_public_lookup ("ice-9 eval-string", "eval-string");
523 k_module = scm_from_locale_keyword ("module");
524 }
525
526 if (SCM_UNBNDP (module))
527 module = scm_current_module ();
528 else
529 SCM_VALIDATE_MODULE (2, module);
530
531 return scm_call_3 (scm_variable_ref (eval_string), string, k_module, module);
532 }
533 #undef FUNC_NAME
534
535 SCM
536 scm_eval_string (SCM string)
537 {
538 return scm_eval_string_in_module (string, SCM_UNDEFINED);
539 }
540
541 static scm_t_bits
542 scm_make_stptob ()
543 {
544 scm_t_bits tc = scm_make_port_type ("string", stfill_buffer, st_write);
545
546 scm_set_port_end_input (tc, st_end_input);
547 scm_set_port_flush (tc, st_flush);
548 scm_set_port_seek (tc, st_seek);
549 scm_set_port_truncate (tc, st_truncate);
550
551 return tc;
552 }
553
554 void
555 scm_init_strports ()
556 {
557 scm_tc16_strport = scm_make_stptob ();
558
559 #include "libguile/strports.x"
560 }
561
562
563 /*
564 Local Variables:
565 c-file-style: "gnu"
566 End:
567 */