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