Merge remote-tracking branch 'origin/stable-2.0'
[bpt/guile.git] / libguile / ports.c
1 /* Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004,
2 * 2006, 2007, 2008, 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 /* Headers. */
23
24 #define _LARGEFILE64_SOURCE /* ask for stat64 etc */
25
26 #ifdef HAVE_CONFIG_H
27 # include <config.h>
28 #endif
29
30 #include <stdio.h>
31 #include <errno.h>
32 #include <fcntl.h> /* for chsize on mingw */
33 #include <assert.h>
34 #include <iconv.h>
35 #include <uniconv.h>
36 #include <unistr.h>
37 #include <striconveh.h>
38
39 #include <assert.h>
40
41 #include "libguile/_scm.h"
42 #include "libguile/async.h"
43 #include "libguile/deprecation.h"
44 #include "libguile/eval.h"
45 #include "libguile/fports.h" /* direct access for seek and truncate */
46 #include "libguile/goops.h"
47 #include "libguile/smob.h"
48 #include "libguile/chars.h"
49 #include "libguile/dynwind.h"
50
51 #include "libguile/keywords.h"
52 #include "libguile/hashtab.h"
53 #include "libguile/root.h"
54 #include "libguile/strings.h"
55 #include "libguile/mallocs.h"
56 #include "libguile/validate.h"
57 #include "libguile/ports.h"
58 #include "libguile/vectors.h"
59 #include "libguile/weak-set.h"
60 #include "libguile/fluids.h"
61 #include "libguile/eq.h"
62
63 #ifdef HAVE_STRING_H
64 #include <string.h>
65 #endif
66
67 #ifdef HAVE_IO_H
68 #include <io.h>
69 #endif
70
71 #ifdef HAVE_UNISTD_H
72 #include <unistd.h>
73 #endif
74
75 #ifdef HAVE_SYS_IOCTL_H
76 #include <sys/ioctl.h>
77 #endif
78
79 /* Mingw (version 3.4.5, circa 2006) has ftruncate as an alias for chsize
80 already, but have this code here in case that wasn't so in past versions,
81 or perhaps to help other minimal DOS environments.
82
83 gnulib ftruncate.c has code using fcntl F_CHSIZE and F_FREESP, which
84 might be possibilities if we've got other systems without ftruncate. */
85
86 #if defined HAVE_CHSIZE && ! defined HAVE_FTRUNCATE
87 #define ftruncate(fd, size) chsize (fd, size)
88 #undef HAVE_FTRUNCATE
89 #define HAVE_FTRUNCATE 1
90 #endif
91
92 \f
93 /* The port kind table --- a dynamically resized array of port types. */
94
95
96 /* scm_ptobs scm_numptob
97 * implement a dynamically resized array of ptob records.
98 * Indexes into this table are used when generating type
99 * tags for smobjects (if you know a tag you can get an index and conversely).
100 */
101 static scm_t_ptob_descriptor **scm_ptobs = NULL;
102 static long scm_numptob = 0; /* Number of port types. */
103 static long scm_ptobs_size = 0; /* Number of slots in the port type
104 table. */
105 static scm_i_pthread_mutex_t scm_ptobs_lock = SCM_I_PTHREAD_MUTEX_INITIALIZER;
106
107 long
108 scm_c_num_port_types (void)
109 {
110 long ret;
111
112 scm_i_pthread_mutex_lock (&scm_ptobs_lock);
113 ret = scm_numptob;
114 scm_i_pthread_mutex_unlock (&scm_ptobs_lock);
115
116 return ret;
117 }
118
119 scm_t_ptob_descriptor*
120 scm_c_port_type_ref (long ptobnum)
121 {
122 scm_t_ptob_descriptor *ret = NULL;
123
124 scm_i_pthread_mutex_lock (&scm_ptobs_lock);
125
126 if (0 <= ptobnum && ptobnum < scm_numptob)
127 ret = scm_ptobs[ptobnum];
128
129 scm_i_pthread_mutex_unlock (&scm_ptobs_lock);
130
131 if (!ret)
132 scm_out_of_range ("scm_c_port_type_ref", scm_from_long (ptobnum));
133
134 return ret;
135 }
136
137 long
138 scm_c_port_type_add_x (scm_t_ptob_descriptor *desc)
139 {
140 long ret = -1;
141
142 scm_i_pthread_mutex_lock (&scm_ptobs_lock);
143
144 if (scm_numptob + 1 < SCM_I_MAX_PORT_TYPE_COUNT)
145 {
146 if (scm_numptob == scm_ptobs_size)
147 {
148 unsigned long old_size = scm_ptobs_size;
149 scm_t_ptob_descriptor **old_ptobs = scm_ptobs;
150
151 /* Currently there are only 9 predefined port types, so one
152 resize will cover it. */
153 scm_ptobs_size = old_size + 10;
154
155 if (scm_ptobs_size >= SCM_I_MAX_PORT_TYPE_COUNT)
156 scm_ptobs_size = SCM_I_MAX_PORT_TYPE_COUNT;
157
158 scm_ptobs = scm_gc_malloc (sizeof (*scm_ptobs) * scm_ptobs_size,
159 "scm_ptobs");
160
161 memcpy (scm_ptobs, old_ptobs, sizeof (*scm_ptobs) * scm_numptob);
162 }
163
164 ret = scm_numptob++;
165 scm_ptobs[ret] = desc;
166 }
167
168 scm_i_pthread_mutex_unlock (&scm_ptobs_lock);
169
170 if (ret < 0)
171 scm_out_of_range ("scm_c_port_type_add_x", scm_from_long (scm_numptob));
172
173 return ret;
174 }
175
176 /*
177 * We choose to use an interface similar to the smob interface with
178 * fill_input and write as standard fields, passed to the port
179 * type constructor, and optional fields set by setters.
180 */
181
182 static void
183 flush_port_default (SCM port SCM_UNUSED)
184 {
185 }
186
187 static void
188 end_input_default (SCM port SCM_UNUSED, int offset SCM_UNUSED)
189 {
190 }
191
192 scm_t_bits
193 scm_make_port_type (char *name,
194 int (*fill_input) (SCM port),
195 void (*write) (SCM port, const void *data, size_t size))
196 {
197 scm_t_ptob_descriptor *desc;
198 long ptobnum;
199
200 desc = scm_gc_malloc_pointerless (sizeof (*desc), "port-type");
201 memset (desc, 0, sizeof (*desc));
202
203 desc->name = name;
204 desc->print = scm_port_print;
205 desc->write = write;
206 desc->flush = flush_port_default;
207 desc->end_input = end_input_default;
208 desc->fill_input = fill_input;
209
210 ptobnum = scm_c_port_type_add_x (desc);
211
212 /* Make a class object if GOOPS is present. */
213 if (SCM_UNPACK (scm_port_class[0]) != 0)
214 scm_make_port_classes (ptobnum, name);
215
216 return scm_tc7_port + ptobnum * 256;
217 }
218
219 void
220 scm_set_port_mark (scm_t_bits tc, SCM (*mark) (SCM))
221 {
222 scm_c_port_type_ref (SCM_TC2PTOBNUM (tc))->mark = mark;
223 }
224
225 void
226 scm_set_port_free (scm_t_bits tc, size_t (*free) (SCM))
227 {
228 scm_c_port_type_ref (SCM_TC2PTOBNUM (tc))->free = free;
229 }
230
231 void
232 scm_set_port_print (scm_t_bits tc, int (*print) (SCM exp, SCM port,
233 scm_print_state *pstate))
234 {
235 scm_c_port_type_ref (SCM_TC2PTOBNUM (tc))->print = print;
236 }
237
238 void
239 scm_set_port_equalp (scm_t_bits tc, SCM (*equalp) (SCM, SCM))
240 {
241 scm_c_port_type_ref (SCM_TC2PTOBNUM (tc))->equalp = equalp;
242 }
243
244 void
245 scm_set_port_close (scm_t_bits tc, int (*close) (SCM))
246 {
247 scm_c_port_type_ref (SCM_TC2PTOBNUM (tc))->close = close;
248 }
249
250 void
251 scm_set_port_flush (scm_t_bits tc, void (*flush) (SCM port))
252 {
253 scm_c_port_type_ref (SCM_TC2PTOBNUM (tc))->flush = flush;
254 }
255
256 void
257 scm_set_port_end_input (scm_t_bits tc, void (*end_input) (SCM port, int offset))
258 {
259 scm_c_port_type_ref (SCM_TC2PTOBNUM (tc))->end_input = end_input;
260 }
261
262 void
263 scm_set_port_seek (scm_t_bits tc, scm_t_off (*seek) (SCM, scm_t_off, int))
264 {
265 scm_c_port_type_ref (SCM_TC2PTOBNUM (tc))->seek = seek;
266 }
267
268 void
269 scm_set_port_truncate (scm_t_bits tc, void (*truncate) (SCM, scm_t_off))
270 {
271 scm_c_port_type_ref (SCM_TC2PTOBNUM (tc))->truncate = truncate;
272 }
273
274 void
275 scm_set_port_input_waiting (scm_t_bits tc, int (*input_waiting) (SCM))
276 {
277 scm_c_port_type_ref (SCM_TC2PTOBNUM (tc))->input_waiting = input_waiting;
278 }
279
280 \f
281
282 /* Standard ports --- current input, output, error, and more(!). */
283
284 static SCM cur_inport_fluid = SCM_BOOL_F;
285 static SCM cur_outport_fluid = SCM_BOOL_F;
286 static SCM cur_errport_fluid = SCM_BOOL_F;
287 static SCM cur_loadport_fluid = SCM_BOOL_F;
288
289 SCM_DEFINE (scm_current_input_port, "current-input-port", 0, 0, 0,
290 (),
291 "Return the current input port. This is the default port used\n"
292 "by many input procedures. Initially, @code{current-input-port}\n"
293 "returns the @dfn{standard input} in Unix and C terminology.")
294 #define FUNC_NAME s_scm_current_input_port
295 {
296 if (scm_is_true (cur_inport_fluid))
297 return scm_fluid_ref (cur_inport_fluid);
298 else
299 return SCM_BOOL_F;
300 }
301 #undef FUNC_NAME
302
303 SCM_DEFINE (scm_current_output_port, "current-output-port", 0, 0, 0,
304 (),
305 "Return the current output port. This is the default port used\n"
306 "by many output procedures. Initially,\n"
307 "@code{current-output-port} returns the @dfn{standard output} in\n"
308 "Unix and C terminology.")
309 #define FUNC_NAME s_scm_current_output_port
310 {
311 if (scm_is_true (cur_outport_fluid))
312 return scm_fluid_ref (cur_outport_fluid);
313 else
314 return SCM_BOOL_F;
315 }
316 #undef FUNC_NAME
317
318 SCM_DEFINE (scm_current_error_port, "current-error-port", 0, 0, 0,
319 (),
320 "Return the port to which errors and warnings should be sent (the\n"
321 "@dfn{standard error} in Unix and C terminology).")
322 #define FUNC_NAME s_scm_current_error_port
323 {
324 if (scm_is_true (cur_errport_fluid))
325 return scm_fluid_ref (cur_errport_fluid);
326 else
327 return SCM_BOOL_F;
328 }
329 #undef FUNC_NAME
330
331 SCM
332 scm_current_warning_port (void)
333 {
334 static SCM cwp_var = SCM_BOOL_F;
335
336 if (scm_is_false (cwp_var))
337 cwp_var = scm_c_private_lookup ("guile", "current-warning-port");
338
339 return scm_call_0 (scm_variable_ref (cwp_var));
340 }
341
342 SCM_DEFINE (scm_current_load_port, "current-load-port", 0, 0, 0,
343 (),
344 "Return the current-load-port.\n"
345 "The load port is used internally by @code{primitive-load}.")
346 #define FUNC_NAME s_scm_current_load_port
347 {
348 return scm_fluid_ref (cur_loadport_fluid);
349 }
350 #undef FUNC_NAME
351
352 SCM_DEFINE (scm_set_current_input_port, "set-current-input-port", 1, 0, 0,
353 (SCM port),
354 "@deffnx {Scheme Procedure} set-current-output-port port\n"
355 "@deffnx {Scheme Procedure} set-current-error-port port\n"
356 "Change the ports returned by @code{current-input-port},\n"
357 "@code{current-output-port} and @code{current-error-port}, respectively,\n"
358 "so that they use the supplied @var{port} for input or output.")
359 #define FUNC_NAME s_scm_set_current_input_port
360 {
361 SCM oinp = scm_fluid_ref (cur_inport_fluid);
362 SCM_VALIDATE_OPINPORT (1, port);
363 scm_fluid_set_x (cur_inport_fluid, port);
364 return oinp;
365 }
366 #undef FUNC_NAME
367
368
369 SCM_DEFINE (scm_set_current_output_port, "set-current-output-port", 1, 0, 0,
370 (SCM port),
371 "Set the current default output port to @var{port}.")
372 #define FUNC_NAME s_scm_set_current_output_port
373 {
374 SCM ooutp = scm_fluid_ref (cur_outport_fluid);
375 port = SCM_COERCE_OUTPORT (port);
376 SCM_VALIDATE_OPOUTPORT (1, port);
377 scm_fluid_set_x (cur_outport_fluid, port);
378 return ooutp;
379 }
380 #undef FUNC_NAME
381
382
383 SCM_DEFINE (scm_set_current_error_port, "set-current-error-port", 1, 0, 0,
384 (SCM port),
385 "Set the current default error port to @var{port}.")
386 #define FUNC_NAME s_scm_set_current_error_port
387 {
388 SCM oerrp = scm_fluid_ref (cur_errport_fluid);
389 port = SCM_COERCE_OUTPORT (port);
390 SCM_VALIDATE_OPOUTPORT (1, port);
391 scm_fluid_set_x (cur_errport_fluid, port);
392 return oerrp;
393 }
394 #undef FUNC_NAME
395
396
397 SCM
398 scm_set_current_warning_port (SCM port)
399 {
400 static SCM cwp_var = SCM_BOOL_F;
401
402 if (scm_is_false (cwp_var))
403 cwp_var = scm_c_private_lookup ("guile", "current-warning-port");
404
405 return scm_call_1 (scm_variable_ref (cwp_var), port);
406 }
407
408
409 void
410 scm_dynwind_current_input_port (SCM port)
411 #define FUNC_NAME NULL
412 {
413 SCM_VALIDATE_OPINPORT (1, port);
414 scm_dynwind_fluid (cur_inport_fluid, port);
415 }
416 #undef FUNC_NAME
417
418 void
419 scm_dynwind_current_output_port (SCM port)
420 #define FUNC_NAME NULL
421 {
422 port = SCM_COERCE_OUTPORT (port);
423 SCM_VALIDATE_OPOUTPORT (1, port);
424 scm_dynwind_fluid (cur_outport_fluid, port);
425 }
426 #undef FUNC_NAME
427
428 void
429 scm_dynwind_current_error_port (SCM port)
430 #define FUNC_NAME NULL
431 {
432 port = SCM_COERCE_OUTPORT (port);
433 SCM_VALIDATE_OPOUTPORT (1, port);
434 scm_dynwind_fluid (cur_errport_fluid, port);
435 }
436 #undef FUNC_NAME
437
438 void
439 scm_i_dynwind_current_load_port (SCM port)
440 {
441 scm_dynwind_fluid (cur_loadport_fluid, port);
442 }
443
444
445 \f
446
447 /* Retrieving a port's mode. */
448
449 /* Return the flags that characterize a port based on the mode
450 * string used to open a file for that port.
451 *
452 * See PORT FLAGS in scm.h
453 */
454
455 static long
456 scm_i_mode_bits_n (SCM modes)
457 {
458 return (SCM_OPN
459 | (scm_i_string_contains_char (modes, 'r')
460 || scm_i_string_contains_char (modes, '+') ? SCM_RDNG : 0)
461 | (scm_i_string_contains_char (modes, 'w')
462 || scm_i_string_contains_char (modes, 'a')
463 || scm_i_string_contains_char (modes, '+') ? SCM_WRTNG : 0)
464 | (scm_i_string_contains_char (modes, '0') ? SCM_BUF0 : 0)
465 | (scm_i_string_contains_char (modes, 'l') ? SCM_BUFLINE : 0));
466 }
467
468 long
469 scm_mode_bits (char *modes)
470 {
471 return scm_i_mode_bits (scm_from_locale_string (modes));
472 }
473
474 long
475 scm_i_mode_bits (SCM modes)
476 {
477 long bits;
478
479 if (!scm_is_string (modes))
480 scm_wrong_type_arg_msg (NULL, 0, modes, "string");
481
482 bits = scm_i_mode_bits_n (modes);
483 scm_remember_upto_here_1 (modes);
484 return bits;
485 }
486
487 /* Return the mode flags from an open port.
488 * Some modes such as "append" are only used when opening
489 * a file and are not returned here. */
490
491 SCM_DEFINE (scm_port_mode, "port-mode", 1, 0, 0,
492 (SCM port),
493 "Return the port modes associated with the open port @var{port}.\n"
494 "These will not necessarily be identical to the modes used when\n"
495 "the port was opened, since modes such as \"append\" which are\n"
496 "used only during port creation are not retained.")
497 #define FUNC_NAME s_scm_port_mode
498 {
499 char modes[4];
500 modes[0] = '\0';
501
502 port = SCM_COERCE_OUTPORT (port);
503 SCM_VALIDATE_OPPORT (1, port);
504 if (SCM_CELL_WORD_0 (port) & SCM_RDNG) {
505 if (SCM_CELL_WORD_0 (port) & SCM_WRTNG)
506 strcpy (modes, "r+");
507 else
508 strcpy (modes, "r");
509 }
510 else if (SCM_CELL_WORD_0 (port) & SCM_WRTNG)
511 strcpy (modes, "w");
512 if (SCM_CELL_WORD_0 (port) & SCM_BUF0)
513 strcat (modes, "0");
514
515 return scm_from_latin1_string (modes);
516 }
517 #undef FUNC_NAME
518
519
520 \f
521
522 /* The port table --- a weak set of all ports.
523
524 We need a global registry of ports to flush them all at exit, and to
525 get all the ports matching a file descriptor. */
526 SCM scm_i_port_weak_set;
527
528
529 \f
530
531 /* Port finalization. */
532
533 static void finalize_port (GC_PTR, GC_PTR);
534
535 /* Register a finalizer for PORT. */
536 static SCM_C_INLINE_KEYWORD void
537 register_finalizer_for_port (SCM port)
538 {
539 GC_finalization_proc prev_finalizer;
540 GC_PTR prev_finalization_data;
541
542 /* Register a finalizer for PORT so that its iconv CDs get freed and
543 optionally its type's `free' function gets called. */
544 GC_REGISTER_FINALIZER_NO_ORDER (SCM2PTR (port), finalize_port, 0,
545 &prev_finalizer,
546 &prev_finalization_data);
547 }
548
549 /* Finalize the object (a port) pointed to by PTR. */
550 static void
551 finalize_port (GC_PTR ptr, GC_PTR data)
552 {
553 SCM port = SCM_PACK_POINTER (ptr);
554
555 if (!SCM_PORTP (port))
556 abort ();
557
558 if (SCM_OPENP (port))
559 {
560 if (SCM_REVEALED (port) > 0)
561 /* Keep "revealed" ports alive and re-register a finalizer. */
562 register_finalizer_for_port (port);
563 else
564 {
565 scm_t_ptob_descriptor *ptob = SCM_PORT_DESCRIPTOR (port);
566 scm_t_port *entry;
567
568 if (ptob->free)
569 /* Yes, I really do mean `free' rather than `close'. `close'
570 is for explicit `close-port' by user. */
571 ptob->free (port);
572
573 entry = SCM_PTAB_ENTRY (port);
574
575 if (entry->input_cd != (iconv_t) -1)
576 iconv_close (entry->input_cd);
577 if (entry->output_cd != (iconv_t) -1)
578 iconv_close (entry->output_cd);
579
580 SCM_SETSTREAM (port, 0);
581 SCM_CLR_PORT_OPEN_FLAG (port);
582
583 scm_gc_ports_collected++;
584 }
585 }
586 }
587
588
589 \f
590
591 SCM
592 scm_c_make_port_with_encoding (scm_t_bits tag, unsigned long mode_bits,
593 const char *encoding,
594 scm_t_string_failed_conversion_handler handler,
595 scm_t_bits stream)
596 {
597 SCM ret;
598 scm_t_port *entry;
599 scm_t_ptob_descriptor *ptob;
600
601 entry = (scm_t_port *) scm_gc_calloc (sizeof (scm_t_port), "port");
602 ptob = scm_c_port_type_ref (SCM_TC2PTOBNUM (tag));
603
604 ret = scm_words (tag | mode_bits, 3);
605 SCM_SET_CELL_WORD_1 (ret, (scm_t_bits) entry);
606 SCM_SET_CELL_WORD_2 (ret, (scm_t_bits) ptob);
607
608 entry->lock = scm_gc_malloc_pointerless (sizeof (*entry->lock), "port lock");
609 scm_i_pthread_mutex_init (entry->lock, scm_i_pthread_mutexattr_recursive);
610
611 entry->file_name = SCM_BOOL_F;
612 entry->rw_active = SCM_PORT_NEITHER;
613 entry->port = ret;
614 entry->stream = stream;
615 entry->encoding = encoding ? scm_gc_strdup (encoding, "port") : NULL;
616 /* The conversion descriptors will be opened lazily. */
617 entry->input_cd = (iconv_t) -1;
618 entry->output_cd = (iconv_t) -1;
619 entry->ilseq_handler = handler;
620
621 scm_weak_set_add_x (scm_i_port_weak_set, ret);
622
623 /* For each new port, register a finalizer so that it port type's free
624 function can be invoked eventually. */
625 register_finalizer_for_port (ret);
626
627 return ret;
628 }
629
630 SCM
631 scm_c_make_port (scm_t_bits tag, unsigned long mode_bits, scm_t_bits stream)
632 {
633 return scm_c_make_port_with_encoding (tag, mode_bits,
634 scm_i_default_port_encoding (),
635 scm_i_get_conversion_strategy (SCM_BOOL_F),
636 stream);
637 }
638
639 SCM
640 scm_new_port_table_entry (scm_t_bits tag)
641 {
642 return scm_c_make_port (tag, 0, 0);
643 }
644
645 /* Remove a port from the table and destroy it. */
646
647 static void
648 scm_i_remove_port (SCM port)
649 #define FUNC_NAME "scm_remove_port"
650 {
651 scm_t_port *p;
652
653 p = SCM_PTAB_ENTRY (port);
654 scm_port_non_buffer (p);
655 SCM_SETPTAB_ENTRY (port, 0);
656 scm_weak_set_remove_x (scm_i_port_weak_set, port);
657
658 p->putback_buf = NULL;
659 p->putback_buf_size = 0;
660
661 if (p->input_cd != (iconv_t) -1)
662 {
663 iconv_close (p->input_cd);
664 p->input_cd = (iconv_t) -1;
665 }
666
667 if (p->output_cd != (iconv_t) -1)
668 {
669 iconv_close (p->output_cd);
670 p->output_cd = (iconv_t) -1;
671 }
672 }
673 #undef FUNC_NAME
674
675
676 \f
677
678 /* Predicates. */
679
680 SCM_DEFINE (scm_port_p, "port?", 1, 0, 0,
681 (SCM x),
682 "Return a boolean indicating whether @var{x} is a port.\n"
683 "Equivalent to @code{(or (input-port? @var{x}) (output-port?\n"
684 "@var{x}))}.")
685 #define FUNC_NAME s_scm_port_p
686 {
687 return scm_from_bool (SCM_PORTP (x));
688 }
689 #undef FUNC_NAME
690
691 SCM_DEFINE (scm_input_port_p, "input-port?", 1, 0, 0,
692 (SCM x),
693 "Return @code{#t} if @var{x} is an input port, otherwise return\n"
694 "@code{#f}. Any object satisfying this predicate also satisfies\n"
695 "@code{port?}.")
696 #define FUNC_NAME s_scm_input_port_p
697 {
698 return scm_from_bool (SCM_INPUT_PORT_P (x));
699 }
700 #undef FUNC_NAME
701
702 SCM_DEFINE (scm_output_port_p, "output-port?", 1, 0, 0,
703 (SCM x),
704 "Return @code{#t} if @var{x} is an output port, otherwise return\n"
705 "@code{#f}. Any object satisfying this predicate also satisfies\n"
706 "@code{port?}.")
707 #define FUNC_NAME s_scm_output_port_p
708 {
709 x = SCM_COERCE_OUTPORT (x);
710 return scm_from_bool (SCM_OUTPUT_PORT_P (x));
711 }
712 #undef FUNC_NAME
713
714 SCM_DEFINE (scm_port_closed_p, "port-closed?", 1, 0, 0,
715 (SCM port),
716 "Return @code{#t} if @var{port} is closed or @code{#f} if it is\n"
717 "open.")
718 #define FUNC_NAME s_scm_port_closed_p
719 {
720 SCM_VALIDATE_PORT (1, port);
721 return scm_from_bool (!SCM_OPPORTP (port));
722 }
723 #undef FUNC_NAME
724
725 SCM_DEFINE (scm_eof_object_p, "eof-object?", 1, 0, 0,
726 (SCM x),
727 "Return @code{#t} if @var{x} is an end-of-file object; otherwise\n"
728 "return @code{#f}.")
729 #define FUNC_NAME s_scm_eof_object_p
730 {
731 return scm_from_bool (SCM_EOF_OBJECT_P (x));
732 }
733 #undef FUNC_NAME
734
735
736 \f
737
738 /* Closing ports. */
739
740 /* scm_close_port
741 * Call the close operation on a port object.
742 * see also scm_close.
743 */
744 SCM_DEFINE (scm_close_port, "close-port", 1, 0, 0,
745 (SCM port),
746 "Close the specified port object. Return @code{#t} if it\n"
747 "successfully closes a port or @code{#f} if it was already\n"
748 "closed. An exception may be raised if an error occurs, for\n"
749 "example when flushing buffered output. See also @ref{Ports and\n"
750 "File Descriptors, close}, for a procedure which can close file\n"
751 "descriptors.")
752 #define FUNC_NAME s_scm_close_port
753 {
754 int rv;
755
756 port = SCM_COERCE_OUTPORT (port);
757
758 SCM_VALIDATE_PORT (1, port);
759 if (SCM_CLOSEDP (port))
760 return SCM_BOOL_F;
761 if (SCM_PORT_DESCRIPTOR (port)->close)
762 rv = SCM_PORT_DESCRIPTOR (port)->close (port);
763 else
764 rv = 0;
765 scm_i_remove_port (port);
766 SCM_CLR_PORT_OPEN_FLAG (port);
767 return scm_from_bool (rv >= 0);
768 }
769 #undef FUNC_NAME
770
771 SCM_DEFINE (scm_close_input_port, "close-input-port", 1, 0, 0,
772 (SCM port),
773 "Close the specified input port object. The routine has no effect if\n"
774 "the file has already been closed. An exception may be raised if an\n"
775 "error occurs. The value returned is unspecified.\n\n"
776 "See also @ref{Ports and File Descriptors, close}, for a procedure\n"
777 "which can close file descriptors.")
778 #define FUNC_NAME s_scm_close_input_port
779 {
780 SCM_VALIDATE_INPUT_PORT (1, port);
781 scm_close_port (port);
782 return SCM_UNSPECIFIED;
783 }
784 #undef FUNC_NAME
785
786 SCM_DEFINE (scm_close_output_port, "close-output-port", 1, 0, 0,
787 (SCM port),
788 "Close the specified output port object. The routine has no effect if\n"
789 "the file has already been closed. An exception may be raised if an\n"
790 "error occurs. The value returned is unspecified.\n\n"
791 "See also @ref{Ports and File Descriptors, close}, for a procedure\n"
792 "which can close file descriptors.")
793 #define FUNC_NAME s_scm_close_output_port
794 {
795 port = SCM_COERCE_OUTPORT (port);
796 SCM_VALIDATE_OUTPUT_PORT (1, port);
797 scm_close_port (port);
798 return SCM_UNSPECIFIED;
799 }
800 #undef FUNC_NAME
801
802
803 \f
804
805 /* Encoding characters to byte streams, and decoding byte streams to
806 characters. */
807
808 /* A fluid specifying the default encoding for newly created ports. If it is
809 a string, that is the encoding. If it is #f, it is in the "native"
810 (Latin-1) encoding. */
811 SCM_VARIABLE (default_port_encoding_var, "%default-port-encoding");
812
813 static int scm_port_encoding_init = 0;
814
815 /* Use ENCODING as the default encoding for future ports. */
816 void
817 scm_i_set_default_port_encoding (const char *encoding)
818 {
819 if (!scm_port_encoding_init
820 || !scm_is_fluid (SCM_VARIABLE_REF (default_port_encoding_var)))
821 scm_misc_error (NULL, "tried to set port encoding fluid before it is initialized",
822 SCM_EOL);
823
824 if (encoding == NULL
825 || !strcmp (encoding, "ASCII")
826 || !strcmp (encoding, "ANSI_X3.4-1968")
827 || !strcmp (encoding, "ISO-8859-1"))
828 scm_fluid_set_x (SCM_VARIABLE_REF (default_port_encoding_var), SCM_BOOL_F);
829 else
830 scm_fluid_set_x (SCM_VARIABLE_REF (default_port_encoding_var),
831 scm_from_locale_string (encoding));
832 }
833
834 /* Return the name of the default encoding for newly created ports; a
835 return value of NULL means "ISO-8859-1". */
836 const char *
837 scm_i_default_port_encoding (void)
838 {
839 if (!scm_port_encoding_init)
840 return NULL;
841 else if (!scm_is_fluid (SCM_VARIABLE_REF (default_port_encoding_var)))
842 return NULL;
843 else
844 {
845 SCM encoding;
846
847 encoding = scm_fluid_ref (SCM_VARIABLE_REF (default_port_encoding_var));
848 if (!scm_is_string (encoding))
849 return NULL;
850 else
851 return scm_i_string_chars (encoding);
852 }
853 }
854
855 void
856 scm_i_set_port_encoding_x (SCM port, const char *encoding)
857 {
858 scm_t_port *pt;
859 iconv_t new_input_cd, new_output_cd;
860
861 new_input_cd = (iconv_t) -1;
862 new_output_cd = (iconv_t) -1;
863
864 /* Set the character encoding for this port. */
865 pt = SCM_PTAB_ENTRY (port);
866
867 if (encoding == NULL)
868 encoding = "ISO-8859-1";
869
870 if (pt->encoding != encoding)
871 pt->encoding = scm_gc_strdup (encoding, "port");
872
873 /* If ENCODING is UTF-8, then no conversion descriptor is opened
874 because we do I/O ourselves. This saves 100+ KiB for each
875 descriptor. */
876 if (strcmp (encoding, "UTF-8"))
877 {
878 if (SCM_CELL_WORD_0 (port) & SCM_RDNG)
879 {
880 /* Open an input iconv conversion descriptor, from ENCODING
881 to UTF-8. We choose UTF-8, not UTF-32, because iconv
882 implementations can typically convert from anything to
883 UTF-8, but not to UTF-32 (see
884 <http://lists.gnu.org/archive/html/bug-libunistring/2010-09/msg00007.html>). */
885 new_input_cd = iconv_open ("UTF-8", encoding);
886 if (new_input_cd == (iconv_t) -1)
887 goto invalid_encoding;
888 }
889
890 if (SCM_CELL_WORD_0 (port) & SCM_WRTNG)
891 {
892 new_output_cd = iconv_open (encoding, "UTF-8");
893 if (new_output_cd == (iconv_t) -1)
894 {
895 if (new_input_cd != (iconv_t) -1)
896 iconv_close (new_input_cd);
897 goto invalid_encoding;
898 }
899 }
900 }
901
902 if (pt->input_cd != (iconv_t) -1)
903 iconv_close (pt->input_cd);
904 if (pt->output_cd != (iconv_t) -1)
905 iconv_close (pt->output_cd);
906
907 pt->input_cd = new_input_cd;
908 pt->output_cd = new_output_cd;
909
910 return;
911
912 invalid_encoding:
913 {
914 SCM err;
915 err = scm_from_locale_string (encoding);
916 scm_misc_error ("scm_i_set_port_encoding_x",
917 "invalid or unknown character encoding ~s",
918 scm_list_1 (err));
919 }
920 }
921
922 SCM_DEFINE (scm_port_encoding, "port-encoding", 1, 0, 0,
923 (SCM port),
924 "Returns, as a string, the character encoding that @var{port}\n"
925 "uses to interpret its input and output.\n")
926 #define FUNC_NAME s_scm_port_encoding
927 {
928 scm_t_port *pt;
929 const char *enc;
930
931 SCM_VALIDATE_PORT (1, port);
932
933 pt = SCM_PTAB_ENTRY (port);
934 enc = pt->encoding;
935 if (enc)
936 return scm_from_locale_string (pt->encoding);
937 else
938 return SCM_BOOL_F;
939 }
940 #undef FUNC_NAME
941
942 SCM_DEFINE (scm_set_port_encoding_x, "set-port-encoding!", 2, 0, 0,
943 (SCM port, SCM enc),
944 "Sets the character encoding that will be used to interpret all\n"
945 "port I/O. New ports are created with the encoding\n"
946 "appropriate for the current locale if @code{setlocale} has \n"
947 "been called or ISO-8859-1 otherwise\n"
948 "and this procedure can be used to modify that encoding.\n")
949 #define FUNC_NAME s_scm_set_port_encoding_x
950 {
951 char *enc_str;
952
953 SCM_VALIDATE_PORT (1, port);
954 SCM_VALIDATE_STRING (2, enc);
955
956 enc_str = scm_to_locale_string (enc);
957 scm_i_set_port_encoding_x (port, enc_str);
958 free (enc_str);
959
960 return SCM_UNSPECIFIED;
961 }
962 #undef FUNC_NAME
963
964
965 /* This determines how conversions handle unconvertible characters. */
966 SCM_GLOBAL_VARIABLE (scm_conversion_strategy, "%port-conversion-strategy");
967 static int scm_conversion_strategy_init = 0;
968
969 scm_t_string_failed_conversion_handler
970 scm_i_get_conversion_strategy (SCM port)
971 {
972 SCM encoding;
973
974 if (scm_is_false (port))
975 {
976 if (!scm_conversion_strategy_init
977 || !scm_is_fluid (SCM_VARIABLE_REF (scm_conversion_strategy)))
978 return SCM_FAILED_CONVERSION_QUESTION_MARK;
979 else
980 {
981 encoding = scm_fluid_ref (SCM_VARIABLE_REF (scm_conversion_strategy));
982 if (scm_is_false (encoding))
983 return SCM_FAILED_CONVERSION_QUESTION_MARK;
984 else
985 return (scm_t_string_failed_conversion_handler) scm_to_int (encoding);
986 }
987 }
988 else
989 {
990 scm_t_port *pt;
991 pt = SCM_PTAB_ENTRY (port);
992 return pt->ilseq_handler;
993 }
994
995 }
996
997 void
998 scm_i_set_conversion_strategy_x (SCM port,
999 scm_t_string_failed_conversion_handler handler)
1000 {
1001 SCM strategy;
1002 scm_t_port *pt;
1003
1004 strategy = scm_from_int ((int) handler);
1005
1006 if (scm_is_false (port))
1007 {
1008 /* Set the default encoding for future ports. */
1009 if (!scm_conversion_strategy_init
1010 || !scm_is_fluid (SCM_VARIABLE_REF (scm_conversion_strategy)))
1011 scm_misc_error (NULL, "tried to set conversion strategy fluid before it is initialized",
1012 SCM_EOL);
1013 scm_fluid_set_x (SCM_VARIABLE_REF (scm_conversion_strategy), strategy);
1014 }
1015 else
1016 {
1017 /* Set the character encoding for this port. */
1018 pt = SCM_PTAB_ENTRY (port);
1019 pt->ilseq_handler = handler;
1020 }
1021 }
1022
1023 SCM_DEFINE (scm_port_conversion_strategy, "port-conversion-strategy",
1024 1, 0, 0, (SCM port),
1025 "Returns the behavior of the port when handling a character that\n"
1026 "is not representable in the port's current encoding.\n"
1027 "It returns the symbol @code{error} if unrepresentable characters\n"
1028 "should cause exceptions, @code{substitute} if the port should\n"
1029 "try to replace unrepresentable characters with question marks or\n"
1030 "approximate characters, or @code{escape} if unrepresentable\n"
1031 "characters should be converted to string escapes.\n"
1032 "\n"
1033 "If @var{port} is @code{#f}, then the current default behavior\n"
1034 "will be returned. New ports will have this default behavior\n"
1035 "when they are created.\n")
1036 #define FUNC_NAME s_scm_port_conversion_strategy
1037 {
1038 scm_t_string_failed_conversion_handler h;
1039
1040 SCM_VALIDATE_OPPORT (1, port);
1041
1042 if (!scm_is_false (port))
1043 {
1044 SCM_VALIDATE_OPPORT (1, port);
1045 }
1046
1047 h = scm_i_get_conversion_strategy (port);
1048 if (h == SCM_FAILED_CONVERSION_ERROR)
1049 return scm_from_latin1_symbol ("error");
1050 else if (h == SCM_FAILED_CONVERSION_QUESTION_MARK)
1051 return scm_from_latin1_symbol ("substitute");
1052 else if (h == SCM_FAILED_CONVERSION_ESCAPE_SEQUENCE)
1053 return scm_from_latin1_symbol ("escape");
1054 else
1055 abort ();
1056
1057 /* Never gets here. */
1058 return SCM_UNDEFINED;
1059 }
1060 #undef FUNC_NAME
1061
1062 SCM_DEFINE (scm_set_port_conversion_strategy_x, "set-port-conversion-strategy!",
1063 2, 0, 0,
1064 (SCM port, SCM sym),
1065 "Sets the behavior of the interpreter when outputting a character\n"
1066 "that is not representable in the port's current encoding.\n"
1067 "@var{sym} can be either @code{'error}, @code{'substitute}, or\n"
1068 "@code{'escape}. If it is @code{'error}, an error will be thrown\n"
1069 "when an unconvertible character is encountered. If it is\n"
1070 "@code{'substitute}, then unconvertible characters will \n"
1071 "be replaced with approximate characters, or with question marks\n"
1072 "if no approximately correct character is available.\n"
1073 "If it is @code{'escape},\n"
1074 "it will appear as a hex escape when output.\n"
1075 "\n"
1076 "If @var{port} is an open port, the conversion error behavior\n"
1077 "is set for that port. If it is @code{#f}, it is set as the\n"
1078 "default behavior for any future ports that get created in\n"
1079 "this thread.\n")
1080 #define FUNC_NAME s_scm_set_port_conversion_strategy_x
1081 {
1082 SCM err;
1083 SCM qm;
1084 SCM esc;
1085
1086 if (!scm_is_false (port))
1087 {
1088 SCM_VALIDATE_OPPORT (1, port);
1089 }
1090
1091 err = scm_from_latin1_symbol ("error");
1092 if (scm_is_true (scm_eqv_p (sym, err)))
1093 {
1094 scm_i_set_conversion_strategy_x (port, SCM_FAILED_CONVERSION_ERROR);
1095 return SCM_UNSPECIFIED;
1096 }
1097
1098 qm = scm_from_latin1_symbol ("substitute");
1099 if (scm_is_true (scm_eqv_p (sym, qm)))
1100 {
1101 scm_i_set_conversion_strategy_x (port,
1102 SCM_FAILED_CONVERSION_QUESTION_MARK);
1103 return SCM_UNSPECIFIED;
1104 }
1105
1106 esc = scm_from_latin1_symbol ("escape");
1107 if (scm_is_true (scm_eqv_p (sym, esc)))
1108 {
1109 scm_i_set_conversion_strategy_x (port,
1110 SCM_FAILED_CONVERSION_ESCAPE_SEQUENCE);
1111 return SCM_UNSPECIFIED;
1112 }
1113
1114 SCM_MISC_ERROR ("unknown conversion behavior ~s", scm_list_1 (sym));
1115
1116 return SCM_UNSPECIFIED;
1117 }
1118 #undef FUNC_NAME
1119
1120
1121 \f
1122
1123 /* The port lock. */
1124
1125 static void
1126 lock_port (void *mutex)
1127 {
1128 scm_i_pthread_mutex_lock (mutex);
1129 }
1130
1131 static void
1132 unlock_port (void *mutex)
1133 {
1134 scm_i_pthread_mutex_unlock (mutex);
1135 }
1136
1137 void
1138 scm_dynwind_lock_port (SCM port)
1139 #define FUNC_NAME "dynwind-lock-port"
1140 {
1141 scm_i_pthread_mutex_t *lock;
1142 SCM_VALIDATE_OPPORT (SCM_ARG1, port);
1143 scm_c_lock_port (port, &lock);
1144 if (lock)
1145 {
1146 scm_dynwind_unwind_handler (unlock_port, lock, SCM_F_WIND_EXPLICITLY);
1147 scm_dynwind_rewind_handler (lock_port, lock, 0);
1148 }
1149 }
1150 #undef FUNC_NAME
1151
1152
1153 \f
1154
1155 /* Revealed counts --- an oddity inherited from SCSH. */
1156
1157 /* Find a port in the table and return its revealed count.
1158 Also used by the garbage collector.
1159 */
1160 int
1161 scm_revealed_count (SCM port)
1162 {
1163 scm_i_pthread_mutex_t *lock;
1164 int ret;
1165
1166 scm_c_lock_port (port, &lock);
1167 ret = SCM_REVEALED (port);
1168 if (lock)
1169 scm_i_pthread_mutex_unlock (lock);
1170
1171 return ret;
1172 }
1173
1174 SCM_DEFINE (scm_port_revealed, "port-revealed", 1, 0, 0,
1175 (SCM port),
1176 "Return the revealed count for @var{port}.")
1177 #define FUNC_NAME s_scm_port_revealed
1178 {
1179 port = SCM_COERCE_OUTPORT (port);
1180 SCM_VALIDATE_OPENPORT (1, port);
1181 return scm_from_int (scm_revealed_count (port));
1182 }
1183 #undef FUNC_NAME
1184
1185 /* Set the revealed count for a port. */
1186 SCM_DEFINE (scm_set_port_revealed_x, "set-port-revealed!", 2, 0, 0,
1187 (SCM port, SCM rcount),
1188 "Sets the revealed count for a port to a given value.\n"
1189 "The return value is unspecified.")
1190 #define FUNC_NAME s_scm_set_port_revealed_x
1191 {
1192 int r;
1193 scm_i_pthread_mutex_t *lock;
1194
1195 port = SCM_COERCE_OUTPORT (port);
1196 SCM_VALIDATE_OPENPORT (1, port);
1197 r = scm_to_int (rcount);
1198 scm_c_lock_port (port, &lock);
1199 SCM_REVEALED (port) = r;
1200 if (lock)
1201 scm_i_pthread_mutex_unlock (lock);
1202 return SCM_UNSPECIFIED;
1203 }
1204 #undef FUNC_NAME
1205
1206 /* Set the revealed count for a port. */
1207 SCM_DEFINE (scm_adjust_port_revealed_x, "adjust-port-revealed!", 2, 0, 0,
1208 (SCM port, SCM addend),
1209 "Add @var{addend} to the revealed count of @var{port}.\n"
1210 "The return value is unspecified.")
1211 #define FUNC_NAME s_scm_adjust_port_revealed_x
1212 {
1213 scm_i_pthread_mutex_t *lock;
1214 int a;
1215 port = SCM_COERCE_OUTPORT (port);
1216 SCM_VALIDATE_OPENPORT (1, port);
1217 a = scm_to_int (addend);
1218 scm_c_lock_port (port, &lock);
1219 SCM_REVEALED (port) += a;
1220 if (lock)
1221 scm_i_pthread_mutex_unlock (lock);
1222 return SCM_UNSPECIFIED;
1223 }
1224 #undef FUNC_NAME
1225
1226
1227 \f
1228
1229 /* Input. */
1230
1231 int
1232 scm_get_byte_or_eof (SCM port)
1233 {
1234 scm_i_pthread_mutex_t *lock;
1235 int ret;
1236
1237 scm_c_lock_port (port, &lock);
1238 ret = scm_get_byte_or_eof_unlocked (port);
1239 if (lock)
1240 scm_i_pthread_mutex_unlock (lock);
1241
1242 return ret;
1243 }
1244
1245 int
1246 scm_peek_byte_or_eof (SCM port)
1247 {
1248 scm_i_pthread_mutex_t *lock;
1249 int ret;
1250
1251 scm_c_lock_port (port, &lock);
1252 ret = scm_peek_byte_or_eof_unlocked (port);
1253 if (lock)
1254 scm_i_pthread_mutex_unlock (lock);
1255
1256 return ret;
1257 }
1258
1259 /* scm_c_read
1260 *
1261 * Used by an application to read arbitrary number of bytes from an
1262 * SCM port. Same semantics as libc read, except that scm_c_read only
1263 * returns less than SIZE bytes if at end-of-file.
1264 *
1265 * Warning: Doesn't update port line and column counts! */
1266
1267 /* This structure, and the following swap_buffer function, are used
1268 for temporarily swapping a port's own read buffer, and the buffer
1269 that the caller of scm_c_read provides. */
1270 struct port_and_swap_buffer
1271 {
1272 scm_t_port *pt;
1273 unsigned char *buffer;
1274 size_t size;
1275 };
1276
1277 static void
1278 swap_buffer (void *data)
1279 {
1280 struct port_and_swap_buffer *psb = (struct port_and_swap_buffer *) data;
1281 unsigned char *old_buf = psb->pt->read_buf;
1282 size_t old_size = psb->pt->read_buf_size;
1283
1284 /* Make the port use (buffer, size) from the struct. */
1285 psb->pt->read_pos = psb->pt->read_buf = psb->pt->read_end = psb->buffer;
1286 psb->pt->read_buf_size = psb->size;
1287
1288 /* Save the port's old (buffer, size) in the struct. */
1289 psb->buffer = old_buf;
1290 psb->size = old_size;
1291 }
1292
1293 size_t
1294 scm_c_read_unlocked (SCM port, void *buffer, size_t size)
1295 #define FUNC_NAME "scm_c_read"
1296 {
1297 scm_t_port *pt;
1298 size_t n_read = 0, n_available;
1299 struct port_and_swap_buffer psb;
1300
1301 SCM_VALIDATE_OPINPORT (1, port);
1302
1303 pt = SCM_PTAB_ENTRY (port);
1304 if (pt->rw_active == SCM_PORT_WRITE)
1305 SCM_PORT_DESCRIPTOR (port)->flush (port);
1306
1307 if (pt->rw_random)
1308 pt->rw_active = SCM_PORT_READ;
1309
1310 /* Take bytes first from the port's read buffer. */
1311 if (pt->read_pos < pt->read_end)
1312 {
1313 n_available = min (size, pt->read_end - pt->read_pos);
1314 memcpy (buffer, pt->read_pos, n_available);
1315 buffer = (char *) buffer + n_available;
1316 pt->read_pos += n_available;
1317 n_read += n_available;
1318 size -= n_available;
1319 }
1320
1321 /* Avoid the scm_dynwind_* costs if we now have enough data. */
1322 if (size == 0)
1323 return n_read;
1324
1325 /* Now we will call scm_fill_input repeatedly until we have read the
1326 requested number of bytes. (Note that a single scm_fill_input
1327 call does not guarantee to fill the whole of the port's read
1328 buffer.) */
1329 if (pt->read_buf_size <= 1 && pt->encoding == NULL)
1330 {
1331 /* The port that we are reading from is unbuffered - i.e. does
1332 not have its own persistent buffer - but we have a buffer,
1333 provided by our caller, that is the right size for the data
1334 that is wanted. For the following scm_fill_input calls,
1335 therefore, we use the buffer in hand as the port's read
1336 buffer.
1337
1338 We need to make sure that the port's normal (1 byte) buffer
1339 is reinstated in case one of the scm_fill_input () calls
1340 throws an exception; we use the scm_dynwind_* API to achieve
1341 that.
1342
1343 A consequence of this optimization is that the fill_input
1344 functions can't unget characters. That'll push data to the
1345 pushback buffer instead of this psb buffer. */
1346 #if SCM_DEBUG == 1
1347 unsigned char *pback = pt->putback_buf;
1348 #endif
1349 psb.pt = pt;
1350 psb.buffer = buffer;
1351 psb.size = size;
1352 scm_dynwind_begin (SCM_F_DYNWIND_REWINDABLE);
1353 scm_dynwind_rewind_handler (swap_buffer, &psb, SCM_F_WIND_EXPLICITLY);
1354 scm_dynwind_unwind_handler (swap_buffer, &psb, SCM_F_WIND_EXPLICITLY);
1355
1356 /* Call scm_fill_input until we have all the bytes that we need,
1357 or we hit EOF. */
1358 while (pt->read_buf_size && (scm_fill_input_unlocked (port) != EOF))
1359 {
1360 pt->read_buf_size -= (pt->read_end - pt->read_pos);
1361 pt->read_pos = pt->read_buf = pt->read_end;
1362 }
1363 #if SCM_DEBUG == 1
1364 if (pback != pt->putback_buf
1365 || pt->read_buf - (unsigned char *) buffer < 0)
1366 scm_misc_error (FUNC_NAME,
1367 "scm_c_read must not call a fill function that pushes "
1368 "back characters onto an unbuffered port", SCM_EOL);
1369 #endif
1370 n_read += pt->read_buf - (unsigned char *) buffer;
1371
1372 /* Reinstate the port's normal buffer. */
1373 scm_dynwind_end ();
1374 }
1375 else
1376 {
1377 /* The port has its own buffer. It is important that we use it,
1378 even if it happens to be smaller than our caller's buffer, so
1379 that a custom port implementation's entry points (in
1380 particular, fill_input) can rely on the buffer always being
1381 the same as they first set up. */
1382 while (size && (scm_fill_input_unlocked (port) != EOF))
1383 {
1384 n_available = min (size, pt->read_end - pt->read_pos);
1385 memcpy (buffer, pt->read_pos, n_available);
1386 buffer = (char *) buffer + n_available;
1387 pt->read_pos += n_available;
1388 n_read += n_available;
1389 size -= n_available;
1390 }
1391 }
1392
1393 return n_read;
1394 }
1395 #undef FUNC_NAME
1396
1397 size_t
1398 scm_c_read (SCM port, void *buffer, size_t size)
1399 {
1400 scm_i_pthread_mutex_t *lock;
1401 size_t ret;
1402
1403 scm_c_lock_port (port, &lock);
1404 ret = scm_c_read_unlocked (port, buffer, size);
1405 if (lock)
1406 scm_i_pthread_mutex_unlock (lock);
1407
1408
1409 return ret;
1410 }
1411
1412 /* Update the line and column number of PORT after consumption of C. */
1413 static inline void
1414 update_port_lf (scm_t_wchar c, SCM port)
1415 {
1416 switch (c)
1417 {
1418 case '\a':
1419 case EOF:
1420 break;
1421 case '\b':
1422 SCM_DECCOL (port);
1423 break;
1424 case '\n':
1425 SCM_INCLINE (port);
1426 break;
1427 case '\r':
1428 SCM_ZEROCOL (port);
1429 break;
1430 case '\t':
1431 SCM_TABCOL (port);
1432 break;
1433 default:
1434 SCM_INCCOL (port);
1435 break;
1436 }
1437 }
1438
1439 #define SCM_MBCHAR_BUF_SIZE (4)
1440
1441 /* Convert the SIZE-byte UTF-8 sequence in UTF8_BUF to a codepoint.
1442 UTF8_BUF is assumed to contain a valid UTF-8 sequence. */
1443 static scm_t_wchar
1444 utf8_to_codepoint (const scm_t_uint8 *utf8_buf, size_t size)
1445 {
1446 scm_t_wchar codepoint;
1447
1448 if (utf8_buf[0] <= 0x7f)
1449 {
1450 assert (size == 1);
1451 codepoint = utf8_buf[0];
1452 }
1453 else if ((utf8_buf[0] & 0xe0) == 0xc0)
1454 {
1455 assert (size == 2);
1456 codepoint = ((scm_t_wchar) utf8_buf[0] & 0x1f) << 6UL
1457 | (utf8_buf[1] & 0x3f);
1458 }
1459 else if ((utf8_buf[0] & 0xf0) == 0xe0)
1460 {
1461 assert (size == 3);
1462 codepoint = ((scm_t_wchar) utf8_buf[0] & 0x0f) << 12UL
1463 | ((scm_t_wchar) utf8_buf[1] & 0x3f) << 6UL
1464 | (utf8_buf[2] & 0x3f);
1465 }
1466 else
1467 {
1468 assert (size == 4);
1469 codepoint = ((scm_t_wchar) utf8_buf[0] & 0x07) << 18UL
1470 | ((scm_t_wchar) utf8_buf[1] & 0x3f) << 12UL
1471 | ((scm_t_wchar) utf8_buf[2] & 0x3f) << 6UL
1472 | (utf8_buf[3] & 0x3f);
1473 }
1474
1475 return codepoint;
1476 }
1477
1478 /* Read a UTF-8 sequence from PORT. On success, return 0 and set
1479 *CODEPOINT to the codepoint that was read, fill BUF with its UTF-8
1480 representation, and set *LEN to the length in bytes. Return
1481 `EILSEQ' on error. */
1482 static int
1483 get_utf8_codepoint (SCM port, scm_t_wchar *codepoint,
1484 scm_t_uint8 buf[SCM_MBCHAR_BUF_SIZE], size_t *len)
1485 {
1486 #define ASSERT_NOT_EOF(b) \
1487 if (SCM_UNLIKELY ((b) == EOF)) \
1488 goto invalid_seq
1489 #define CONSUME_PEEKED_BYTE() \
1490 pt->read_pos++
1491
1492 int byte;
1493 scm_t_port *pt;
1494
1495 *len = 0;
1496 pt = SCM_PTAB_ENTRY (port);
1497
1498 byte = scm_get_byte_or_eof_unlocked (port);
1499 if (byte == EOF)
1500 {
1501 *codepoint = EOF;
1502 return 0;
1503 }
1504
1505 buf[0] = (scm_t_uint8) byte;
1506 *len = 1;
1507
1508 if (buf[0] <= 0x7f)
1509 /* 1-byte form. */
1510 *codepoint = buf[0];
1511 else if (buf[0] >= 0xc2 && buf[0] <= 0xdf)
1512 {
1513 /* 2-byte form. */
1514 byte = scm_peek_byte_or_eof_unlocked (port);
1515 ASSERT_NOT_EOF (byte);
1516
1517 if (SCM_UNLIKELY ((byte & 0xc0) != 0x80))
1518 goto invalid_seq;
1519
1520 CONSUME_PEEKED_BYTE ();
1521 buf[1] = (scm_t_uint8) byte;
1522 *len = 2;
1523
1524 *codepoint = ((scm_t_wchar) buf[0] & 0x1f) << 6UL
1525 | (buf[1] & 0x3f);
1526 }
1527 else if ((buf[0] & 0xf0) == 0xe0)
1528 {
1529 /* 3-byte form. */
1530 byte = scm_peek_byte_or_eof_unlocked (port);
1531 ASSERT_NOT_EOF (byte);
1532
1533 if (SCM_UNLIKELY ((byte & 0xc0) != 0x80
1534 || (buf[0] == 0xe0 && byte < 0xa0)
1535 || (buf[0] == 0xed && byte > 0x9f)))
1536 goto invalid_seq;
1537
1538 CONSUME_PEEKED_BYTE ();
1539 buf[1] = (scm_t_uint8) byte;
1540 *len = 2;
1541
1542 byte = scm_peek_byte_or_eof_unlocked (port);
1543 ASSERT_NOT_EOF (byte);
1544
1545 if (SCM_UNLIKELY ((byte & 0xc0) != 0x80))
1546 goto invalid_seq;
1547
1548 CONSUME_PEEKED_BYTE ();
1549 buf[2] = (scm_t_uint8) byte;
1550 *len = 3;
1551
1552 *codepoint = ((scm_t_wchar) buf[0] & 0x0f) << 12UL
1553 | ((scm_t_wchar) buf[1] & 0x3f) << 6UL
1554 | (buf[2] & 0x3f);
1555 }
1556 else if (buf[0] >= 0xf0 && buf[0] <= 0xf4)
1557 {
1558 /* 4-byte form. */
1559 byte = scm_peek_byte_or_eof_unlocked (port);
1560 ASSERT_NOT_EOF (byte);
1561
1562 if (SCM_UNLIKELY (((byte & 0xc0) != 0x80)
1563 || (buf[0] == 0xf0 && byte < 0x90)
1564 || (buf[0] == 0xf4 && byte > 0x8f)))
1565 goto invalid_seq;
1566
1567 CONSUME_PEEKED_BYTE ();
1568 buf[1] = (scm_t_uint8) byte;
1569 *len = 2;
1570
1571 byte = scm_peek_byte_or_eof_unlocked (port);
1572 ASSERT_NOT_EOF (byte);
1573
1574 if (SCM_UNLIKELY ((byte & 0xc0) != 0x80))
1575 goto invalid_seq;
1576
1577 CONSUME_PEEKED_BYTE ();
1578 buf[2] = (scm_t_uint8) byte;
1579 *len = 3;
1580
1581 byte = scm_peek_byte_or_eof_unlocked (port);
1582 ASSERT_NOT_EOF (byte);
1583
1584 if (SCM_UNLIKELY ((byte & 0xc0) != 0x80))
1585 goto invalid_seq;
1586
1587 CONSUME_PEEKED_BYTE ();
1588 buf[3] = (scm_t_uint8) byte;
1589 *len = 4;
1590
1591 *codepoint = ((scm_t_wchar) buf[0] & 0x07) << 18UL
1592 | ((scm_t_wchar) buf[1] & 0x3f) << 12UL
1593 | ((scm_t_wchar) buf[2] & 0x3f) << 6UL
1594 | (buf[3] & 0x3f);
1595 }
1596 else
1597 goto invalid_seq;
1598
1599 return 0;
1600
1601 invalid_seq:
1602 /* Here we could choose the consume the faulty byte when it's not a
1603 valid starting byte, but it's not a requirement. What Section 3.9
1604 of Unicode 6.0.0 mandates, though, is to not consume a byte that
1605 would otherwise be a valid starting byte. */
1606
1607 return EILSEQ;
1608
1609 #undef CONSUME_PEEKED_BYTE
1610 #undef ASSERT_NOT_EOF
1611 }
1612
1613 /* Likewise, read a byte sequence from PORT, passing it through its
1614 input conversion descriptor. */
1615 static int
1616 get_iconv_codepoint (SCM port, scm_t_wchar *codepoint,
1617 char buf[SCM_MBCHAR_BUF_SIZE], size_t *len)
1618 {
1619 scm_t_port *pt;
1620 int err, byte_read;
1621 size_t bytes_consumed, output_size;
1622 char *output;
1623 scm_t_uint8 utf8_buf[SCM_MBCHAR_BUF_SIZE];
1624
1625 pt = SCM_PTAB_ENTRY (port);
1626
1627 for (output_size = 0, output = (char *) utf8_buf,
1628 bytes_consumed = 0, err = 0;
1629 err == 0 && output_size == 0
1630 && (bytes_consumed == 0 || byte_read != EOF);
1631 bytes_consumed++)
1632 {
1633 char *input;
1634 size_t input_left, output_left, done;
1635
1636 byte_read = scm_get_byte_or_eof_unlocked (port);
1637 if (byte_read == EOF)
1638 {
1639 if (bytes_consumed == 0)
1640 {
1641 *codepoint = (scm_t_wchar) EOF;
1642 *len = 0;
1643 return 0;
1644 }
1645 else
1646 continue;
1647 }
1648
1649 buf[bytes_consumed] = byte_read;
1650
1651 input = buf;
1652 input_left = bytes_consumed + 1;
1653 output_left = sizeof (utf8_buf);
1654
1655 done = iconv (pt->input_cd, &input, &input_left,
1656 &output, &output_left);
1657 if (done == (size_t) -1)
1658 {
1659 err = errno;
1660 if (err == EINVAL)
1661 /* Missing input: keep trying. */
1662 err = 0;
1663 }
1664 else
1665 output_size = sizeof (utf8_buf) - output_left;
1666 }
1667
1668 if (SCM_UNLIKELY (output_size == 0))
1669 /* An unterminated sequence. */
1670 err = EILSEQ;
1671 else if (SCM_LIKELY (err == 0))
1672 {
1673 /* Convert the UTF8_BUF sequence to a Unicode code point. */
1674 *codepoint = utf8_to_codepoint (utf8_buf, output_size);
1675 *len = bytes_consumed;
1676 }
1677
1678 return err;
1679 }
1680
1681 /* Read a codepoint from PORT and return it in *CODEPOINT. Fill BUF
1682 with the byte representation of the codepoint in PORT's encoding, and
1683 set *LEN to the length in bytes of that representation. Return 0 on
1684 success and an errno value on error. */
1685 static int
1686 get_codepoint (SCM port, scm_t_wchar *codepoint,
1687 char buf[SCM_MBCHAR_BUF_SIZE], size_t *len)
1688 {
1689 int err;
1690 scm_t_port *pt = SCM_PTAB_ENTRY (port);
1691
1692 if (pt->input_cd == (iconv_t) -1)
1693 /* Initialize the conversion descriptors, if needed. */
1694 scm_i_set_port_encoding_x (port, pt->encoding);
1695
1696 /* FIXME: In 2.1, add a flag to determine whether a port is UTF-8. */
1697 if (pt->input_cd == (iconv_t) -1)
1698 err = get_utf8_codepoint (port, codepoint, (scm_t_uint8 *) buf, len);
1699 else
1700 err = get_iconv_codepoint (port, codepoint, buf, len);
1701
1702 if (SCM_LIKELY (err == 0))
1703 update_port_lf (*codepoint, port);
1704 else if (pt->ilseq_handler == SCM_ICONVEH_QUESTION_MARK)
1705 {
1706 *codepoint = '?';
1707 err = 0;
1708 update_port_lf (*codepoint, port);
1709 }
1710
1711 return err;
1712 }
1713
1714 /* Read a codepoint from PORT and return it. */
1715 scm_t_wchar
1716 scm_getc_unlocked (SCM port)
1717 #define FUNC_NAME "scm_getc"
1718 {
1719 int err;
1720 size_t len;
1721 scm_t_wchar codepoint;
1722 char buf[SCM_MBCHAR_BUF_SIZE];
1723
1724 err = get_codepoint (port, &codepoint, buf, &len);
1725 if (SCM_UNLIKELY (err != 0))
1726 /* At this point PORT should point past the invalid encoding, as per
1727 R6RS-lib Section 8.2.4. */
1728 scm_decoding_error (FUNC_NAME, err, "input decoding error", port);
1729
1730 return codepoint;
1731 }
1732 #undef FUNC_NAME
1733
1734 scm_t_wchar
1735 scm_getc (SCM port)
1736 {
1737 scm_i_pthread_mutex_t *lock;
1738 scm_t_wchar ret;
1739
1740 scm_c_lock_port (port, &lock);
1741 ret = scm_getc_unlocked (port);
1742 if (lock)
1743 scm_i_pthread_mutex_unlock (lock);
1744
1745
1746 return ret;
1747 }
1748
1749 SCM_DEFINE (scm_read_char, "read-char", 0, 1, 0,
1750 (SCM port),
1751 "Return the next character available from @var{port}, updating\n"
1752 "@var{port} to point to the following character. If no more\n"
1753 "characters are available, the end-of-file object is returned.\n"
1754 "\n"
1755 "When @var{port}'s data cannot be decoded according to its\n"
1756 "character encoding, a @code{decoding-error} is raised and\n"
1757 "@var{port} points past the erroneous byte sequence.\n")
1758 #define FUNC_NAME s_scm_read_char
1759 {
1760 scm_t_wchar c;
1761 if (SCM_UNBNDP (port))
1762 port = scm_current_input_port ();
1763 SCM_VALIDATE_OPINPORT (1, port);
1764 c = scm_getc_unlocked (port);
1765 if (EOF == c)
1766 return SCM_EOF_VAL;
1767 return SCM_MAKE_CHAR (c);
1768 }
1769 #undef FUNC_NAME
1770
1771
1772 \f
1773
1774 /* Pushback. */
1775
1776 void
1777 scm_unget_byte_unlocked (int c, SCM port)
1778 #define FUNC_NAME "scm_unget_byte"
1779 {
1780 scm_t_port *pt = SCM_PTAB_ENTRY (port);
1781
1782 if (pt->read_buf == pt->putback_buf)
1783 /* already using the put-back buffer. */
1784 {
1785 /* enlarge putback_buf if necessary. */
1786 if (pt->read_end == pt->read_buf + pt->read_buf_size
1787 && pt->read_buf == pt->read_pos)
1788 {
1789 size_t new_size = pt->read_buf_size * 2;
1790 unsigned char *tmp = (unsigned char *)
1791 scm_gc_realloc (pt->putback_buf, pt->read_buf_size, new_size,
1792 "putback buffer");
1793
1794 pt->read_pos = pt->read_buf = pt->putback_buf = tmp;
1795 pt->read_end = pt->read_buf + pt->read_buf_size;
1796 pt->read_buf_size = pt->putback_buf_size = new_size;
1797 }
1798
1799 /* shift any existing bytes to buffer + 1. */
1800 if (pt->read_pos == pt->read_end)
1801 pt->read_end = pt->read_buf + 1;
1802 else if (pt->read_pos != pt->read_buf + 1)
1803 {
1804 int count = pt->read_end - pt->read_pos;
1805
1806 memmove (pt->read_buf + 1, pt->read_pos, count);
1807 pt->read_end = pt->read_buf + 1 + count;
1808 }
1809
1810 pt->read_pos = pt->read_buf;
1811 }
1812 else
1813 /* switch to the put-back buffer. */
1814 {
1815 if (pt->putback_buf == NULL)
1816 {
1817 pt->putback_buf
1818 = (unsigned char *) scm_gc_malloc_pointerless
1819 (SCM_INITIAL_PUTBACK_BUF_SIZE, "putback buffer");
1820 pt->putback_buf_size = SCM_INITIAL_PUTBACK_BUF_SIZE;
1821 }
1822
1823 pt->saved_read_buf = pt->read_buf;
1824 pt->saved_read_pos = pt->read_pos;
1825 pt->saved_read_end = pt->read_end;
1826 pt->saved_read_buf_size = pt->read_buf_size;
1827
1828 pt->read_pos = pt->read_buf = pt->putback_buf;
1829 pt->read_end = pt->read_buf + 1;
1830 pt->read_buf_size = pt->putback_buf_size;
1831 }
1832
1833 *pt->read_buf = c;
1834
1835 if (pt->rw_random)
1836 pt->rw_active = SCM_PORT_READ;
1837 }
1838 #undef FUNC_NAME
1839
1840 void
1841 scm_unget_byte (int c, SCM port)
1842 {
1843 scm_i_pthread_mutex_t *lock;
1844 scm_c_lock_port (port, &lock);
1845 scm_unget_byte_unlocked (c, port);
1846 if (lock)
1847 scm_i_pthread_mutex_unlock (lock);
1848
1849 }
1850
1851 void
1852 scm_ungetc_unlocked (scm_t_wchar c, SCM port)
1853 #define FUNC_NAME "scm_ungetc"
1854 {
1855 scm_t_port *pt = SCM_PTAB_ENTRY (port);
1856 char *result;
1857 char result_buf[10];
1858 const char *encoding;
1859 size_t len;
1860 int i;
1861
1862 if (pt->encoding != NULL)
1863 encoding = pt->encoding;
1864 else
1865 encoding = "ISO-8859-1";
1866
1867 len = sizeof (result_buf);
1868 result = u32_conv_to_encoding (encoding,
1869 (enum iconv_ilseq_handler) pt->ilseq_handler,
1870 (uint32_t *) &c, 1, NULL,
1871 result_buf, &len);
1872
1873 if (SCM_UNLIKELY (result == NULL || len == 0))
1874 scm_encoding_error (FUNC_NAME, errno,
1875 "conversion to port encoding failed",
1876 SCM_BOOL_F, SCM_MAKE_CHAR (c));
1877
1878 for (i = len - 1; i >= 0; i--)
1879 scm_unget_byte_unlocked (result[i], port);
1880
1881 if (SCM_UNLIKELY (result != result_buf))
1882 free (result);
1883
1884 if (c == '\n')
1885 {
1886 /* What should col be in this case?
1887 * We'll leave it at -1.
1888 */
1889 SCM_LINUM (port) -= 1;
1890 }
1891 else
1892 SCM_COL(port) -= 1;
1893 }
1894 #undef FUNC_NAME
1895
1896 void
1897 scm_ungetc (scm_t_wchar c, SCM port)
1898 {
1899 scm_i_pthread_mutex_t *lock;
1900 scm_c_lock_port (port, &lock);
1901 scm_ungetc_unlocked (c, port);
1902 if (lock)
1903 scm_i_pthread_mutex_unlock (lock);
1904
1905 }
1906
1907 void
1908 scm_ungets_unlocked (const char *s, int n, SCM port)
1909 {
1910 /* This is simple minded and inefficient, but unreading strings is
1911 * probably not a common operation, and remember that line and
1912 * column numbers have to be handled...
1913 *
1914 * Please feel free to write an optimized version!
1915 */
1916 while (n--)
1917 scm_ungetc_unlocked (s[n], port);
1918 }
1919
1920 void
1921 scm_ungets (const char *s, int n, SCM port)
1922 {
1923 scm_i_pthread_mutex_t *lock;
1924 scm_c_lock_port (port, &lock);
1925 scm_ungets_unlocked (s, n, port);
1926 if (lock)
1927 scm_i_pthread_mutex_unlock (lock);
1928
1929 }
1930
1931 SCM_DEFINE (scm_peek_char, "peek-char", 0, 1, 0,
1932 (SCM port),
1933 "Return the next character available from @var{port},\n"
1934 "@emph{without} updating @var{port} to point to the following\n"
1935 "character. If no more characters are available, the\n"
1936 "end-of-file object is returned.\n"
1937 "\n"
1938 "The value returned by\n"
1939 "a call to @code{peek-char} is the same as the value that would\n"
1940 "have been returned by a call to @code{read-char} on the same\n"
1941 "port. The only difference is that the very next call to\n"
1942 "@code{read-char} or @code{peek-char} on that @var{port} will\n"
1943 "return the value returned by the preceding call to\n"
1944 "@code{peek-char}. In particular, a call to @code{peek-char} on\n"
1945 "an interactive port will hang waiting for input whenever a call\n"
1946 "to @code{read-char} would have hung.\n"
1947 "\n"
1948 "As for @code{read-char}, a @code{decoding-error} may be raised\n"
1949 "if such a situation occurs. However, unlike with @code{read-char},\n"
1950 "@var{port} still points at the beginning of the erroneous byte\n"
1951 "sequence when the error is raised.\n")
1952 #define FUNC_NAME s_scm_peek_char
1953 {
1954 int err;
1955 SCM result;
1956 scm_t_wchar c;
1957 char bytes[SCM_MBCHAR_BUF_SIZE];
1958 long column, line, i;
1959 size_t len;
1960
1961 if (SCM_UNBNDP (port))
1962 port = scm_current_input_port ();
1963 SCM_VALIDATE_OPINPORT (1, port);
1964
1965 column = SCM_COL (port);
1966 line = SCM_LINUM (port);
1967
1968 err = get_codepoint (port, &c, bytes, &len);
1969
1970 for (i = len - 1; i >= 0; i--)
1971 scm_unget_byte_unlocked (bytes[i], port);
1972
1973 SCM_COL (port) = column;
1974 SCM_LINUM (port) = line;
1975
1976 if (SCM_UNLIKELY (err != 0))
1977 {
1978 scm_decoding_error (FUNC_NAME, err, "input decoding error", port);
1979
1980 /* Shouldn't happen since `catch' always aborts to prompt. */
1981 result = SCM_BOOL_F;
1982 }
1983 else if (c == EOF)
1984 result = SCM_EOF_VAL;
1985 else
1986 result = SCM_MAKE_CHAR (c);
1987
1988 return result;
1989 }
1990 #undef FUNC_NAME
1991
1992 SCM_DEFINE (scm_unread_char, "unread-char", 1, 1, 0,
1993 (SCM cobj, SCM port),
1994 "Place character @var{cobj} in @var{port} so that it will be\n"
1995 "read by the next read operation. If called multiple times, the\n"
1996 "unread characters will be read again in last-in first-out\n"
1997 "order. If @var{port} is not supplied, the current input port\n"
1998 "is used.")
1999 #define FUNC_NAME s_scm_unread_char
2000 {
2001 int c;
2002
2003 SCM_VALIDATE_CHAR (1, cobj);
2004 if (SCM_UNBNDP (port))
2005 port = scm_current_input_port ();
2006 SCM_VALIDATE_OPINPORT (2, port);
2007
2008 c = SCM_CHAR (cobj);
2009
2010 scm_ungetc_unlocked (c, port);
2011 return cobj;
2012 }
2013 #undef FUNC_NAME
2014
2015 SCM_DEFINE (scm_unread_string, "unread-string", 2, 0, 0,
2016 (SCM str, SCM port),
2017 "Place the string @var{str} in @var{port} so that its characters will be\n"
2018 "read in subsequent read operations. If called multiple times, the\n"
2019 "unread characters will be read again in last-in first-out order. If\n"
2020 "@var{port} is not supplied, the current-input-port is used.")
2021 #define FUNC_NAME s_scm_unread_string
2022 {
2023 int n;
2024 SCM_VALIDATE_STRING (1, str);
2025 if (SCM_UNBNDP (port))
2026 port = scm_current_input_port ();
2027 SCM_VALIDATE_OPINPORT (2, port);
2028
2029 n = scm_i_string_length (str);
2030
2031 while (n--)
2032 scm_ungetc_unlocked (scm_i_string_ref (str, n), port);
2033
2034 return str;
2035 }
2036 #undef FUNC_NAME
2037
2038
2039 \f
2040
2041 /* Manipulating the buffers. */
2042
2043 /* This routine does not take any locks, as it is usually called as part
2044 of a port implementation. */
2045 void
2046 scm_port_non_buffer (scm_t_port *pt)
2047 {
2048 pt->read_pos = pt->read_buf = pt->read_end = &pt->shortbuf;
2049 pt->write_buf = pt->write_pos = &pt->shortbuf;
2050 pt->read_buf_size = pt->write_buf_size = 1;
2051 pt->write_end = pt->write_buf + pt->write_buf_size;
2052 }
2053
2054 /* this should only be called when the read buffer is empty. it
2055 tries to refill the read buffer. it returns the first char from
2056 the port, which is either EOF or *(pt->read_pos). */
2057 int
2058 scm_fill_input_unlocked (SCM port)
2059 {
2060 scm_t_port *pt = SCM_PTAB_ENTRY (port);
2061
2062 assert (pt->read_pos == pt->read_end);
2063
2064 if (pt->read_buf == pt->putback_buf)
2065 {
2066 /* finished reading put-back chars. */
2067 pt->read_buf = pt->saved_read_buf;
2068 pt->read_pos = pt->saved_read_pos;
2069 pt->read_end = pt->saved_read_end;
2070 pt->read_buf_size = pt->saved_read_buf_size;
2071 if (pt->read_pos < pt->read_end)
2072 return *(pt->read_pos);
2073 }
2074 return SCM_PORT_DESCRIPTOR (port)->fill_input (port);
2075 }
2076
2077 int
2078 scm_fill_input (SCM port)
2079 {
2080 scm_i_pthread_mutex_t *lock;
2081 int ret;
2082
2083 scm_c_lock_port (port, &lock);
2084 ret = scm_fill_input_unlocked (port);
2085 if (lock)
2086 scm_i_pthread_mutex_unlock (lock);
2087
2088
2089 return ret;
2090 }
2091
2092 /* move up to read_len chars from port's putback and/or read buffers
2093 into memory starting at dest. returns the number of chars moved. */
2094 size_t
2095 scm_take_from_input_buffers (SCM port, char *dest, size_t read_len)
2096 {
2097 scm_t_port *pt = SCM_PTAB_ENTRY (port);
2098 size_t chars_read = 0;
2099 size_t from_buf = min (pt->read_end - pt->read_pos, read_len);
2100
2101 if (from_buf > 0)
2102 {
2103 memcpy (dest, pt->read_pos, from_buf);
2104 pt->read_pos += from_buf;
2105 chars_read += from_buf;
2106 read_len -= from_buf;
2107 dest += from_buf;
2108 }
2109
2110 /* if putback was active, try the real input buffer too. */
2111 if (pt->read_buf == pt->putback_buf)
2112 {
2113 from_buf = min (pt->saved_read_end - pt->saved_read_pos, read_len);
2114 if (from_buf > 0)
2115 {
2116 memcpy (dest, pt->saved_read_pos, from_buf);
2117 pt->saved_read_pos += from_buf;
2118 chars_read += from_buf;
2119 }
2120 }
2121 return chars_read;
2122 }
2123
2124 /* Clear a port's read buffers, returning the contents. */
2125 SCM_DEFINE (scm_drain_input, "drain-input", 1, 0, 0,
2126 (SCM port),
2127 "This procedure clears a port's input buffers, similar\n"
2128 "to the way that force-output clears the output buffer. The\n"
2129 "contents of the buffers are returned as a single string, e.g.,\n"
2130 "\n"
2131 "@lisp\n"
2132 "(define p (open-input-file ...))\n"
2133 "(drain-input p) => empty string, nothing buffered yet.\n"
2134 "(unread-char (read-char p) p)\n"
2135 "(drain-input p) => initial chars from p, up to the buffer size.\n"
2136 "@end lisp\n\n"
2137 "Draining the buffers may be useful for cleanly finishing\n"
2138 "buffered I/O so that the file descriptor can be used directly\n"
2139 "for further input.")
2140 #define FUNC_NAME s_scm_drain_input
2141 {
2142 SCM result;
2143 char *data;
2144 scm_t_port *pt;
2145 long count;
2146
2147 SCM_VALIDATE_OPINPORT (1, port);
2148 pt = SCM_PTAB_ENTRY (port);
2149
2150 count = pt->read_end - pt->read_pos;
2151 if (pt->read_buf == pt->putback_buf)
2152 count += pt->saved_read_end - pt->saved_read_pos;
2153
2154 if (count)
2155 {
2156 result = scm_i_make_string (count, &data, 0);
2157 scm_take_from_input_buffers (port, data, count);
2158 }
2159 else
2160 result = scm_nullstr;
2161
2162 return result;
2163 }
2164 #undef FUNC_NAME
2165
2166 void
2167 scm_end_input_unlocked (SCM port)
2168 {
2169 long offset;
2170 scm_t_port *pt = SCM_PTAB_ENTRY (port);
2171
2172 if (pt->read_buf == pt->putback_buf)
2173 {
2174 offset = pt->read_end - pt->read_pos;
2175 pt->read_buf = pt->saved_read_buf;
2176 pt->read_pos = pt->saved_read_pos;
2177 pt->read_end = pt->saved_read_end;
2178 pt->read_buf_size = pt->saved_read_buf_size;
2179 }
2180 else
2181 offset = 0;
2182
2183 SCM_PORT_DESCRIPTOR (port)->end_input (port, offset);
2184 }
2185
2186 void
2187 scm_end_input (SCM port)
2188 {
2189 scm_i_pthread_mutex_t *lock;
2190 scm_c_lock_port (port, &lock);
2191 scm_end_input_unlocked (port);
2192 if (lock)
2193 scm_i_pthread_mutex_unlock (lock);
2194
2195 }
2196
2197 SCM_DEFINE (scm_force_output, "force-output", 0, 1, 0,
2198 (SCM port),
2199 "Flush the specified output port, or the current output port if @var{port}\n"
2200 "is omitted. The current output buffer contents are passed to the\n"
2201 "underlying port implementation (e.g., in the case of fports, the\n"
2202 "data will be written to the file and the output buffer will be cleared.)\n"
2203 "It has no effect on an unbuffered port.\n\n"
2204 "The return value is unspecified.")
2205 #define FUNC_NAME s_scm_force_output
2206 {
2207 if (SCM_UNBNDP (port))
2208 port = scm_current_output_port ();
2209 else
2210 {
2211 port = SCM_COERCE_OUTPORT (port);
2212 SCM_VALIDATE_OPOUTPORT (1, port);
2213 }
2214 scm_flush_unlocked (port);
2215 return SCM_UNSPECIFIED;
2216 }
2217 #undef FUNC_NAME
2218
2219 void
2220 scm_flush_unlocked (SCM port)
2221 {
2222 SCM_PORT_DESCRIPTOR (port)->flush (port);
2223 }
2224
2225 void
2226 scm_flush (SCM port)
2227 {
2228 scm_i_pthread_mutex_t *lock;
2229 scm_c_lock_port (port, &lock);
2230 scm_flush_unlocked (port);
2231 if (lock)
2232 scm_i_pthread_mutex_unlock (lock);
2233
2234 }
2235
2236
2237 \f
2238
2239 /* Output. */
2240
2241 void
2242 scm_putc (char c, SCM port)
2243 {
2244 scm_i_pthread_mutex_t *lock;
2245 scm_c_lock_port (port, &lock);
2246 scm_putc_unlocked (c, port);
2247 if (lock)
2248 scm_i_pthread_mutex_unlock (lock);
2249
2250 }
2251
2252 void
2253 scm_puts (const char *s, SCM port)
2254 {
2255 scm_i_pthread_mutex_t *lock;
2256 scm_c_lock_port (port, &lock);
2257 scm_puts_unlocked (s, port);
2258 if (lock)
2259 scm_i_pthread_mutex_unlock (lock);
2260
2261 }
2262
2263 /* scm_c_write
2264 *
2265 * Used by an application to write arbitrary number of bytes to an SCM
2266 * port. Similar semantics as libc write. However, unlike libc
2267 * write, scm_c_write writes the requested number of bytes and has no
2268 * return value.
2269 *
2270 * Warning: Doesn't update port line and column counts!
2271 */
2272 void
2273 scm_c_write_unlocked (SCM port, const void *ptr, size_t size)
2274 #define FUNC_NAME "scm_c_write"
2275 {
2276 scm_t_port *pt;
2277 scm_t_ptob_descriptor *ptob;
2278
2279 SCM_VALIDATE_OPOUTPORT (1, port);
2280
2281 pt = SCM_PTAB_ENTRY (port);
2282 ptob = SCM_PORT_DESCRIPTOR (port);
2283
2284 if (pt->rw_active == SCM_PORT_READ)
2285 scm_end_input_unlocked (port);
2286
2287 ptob->write (port, ptr, size);
2288
2289 if (pt->rw_random)
2290 pt->rw_active = SCM_PORT_WRITE;
2291 }
2292 #undef FUNC_NAME
2293
2294 void
2295 scm_c_write (SCM port, const void *ptr, size_t size)
2296 {
2297 scm_i_pthread_mutex_t *lock;
2298 scm_c_lock_port (port, &lock);
2299 scm_c_write_unlocked (port, ptr, size);
2300 if (lock)
2301 scm_i_pthread_mutex_unlock (lock);
2302
2303 }
2304
2305 /* scm_lfwrite
2306 *
2307 * This function differs from scm_c_write; it updates port line and
2308 * column. */
2309 void
2310 scm_lfwrite_unlocked (const char *ptr, size_t size, SCM port)
2311 {
2312 scm_t_port *pt = SCM_PTAB_ENTRY (port);
2313 scm_t_ptob_descriptor *ptob = SCM_PORT_DESCRIPTOR (port);
2314
2315 if (pt->rw_active == SCM_PORT_READ)
2316 scm_end_input_unlocked (port);
2317
2318 ptob->write (port, ptr, size);
2319
2320 for (; size; ptr++, size--)
2321 update_port_lf ((scm_t_wchar) (unsigned char) *ptr, port);
2322
2323 if (pt->rw_random)
2324 pt->rw_active = SCM_PORT_WRITE;
2325 }
2326
2327 void
2328 scm_lfwrite (const char *ptr, size_t size, SCM port)
2329 {
2330 scm_i_pthread_mutex_t *lock;
2331 scm_c_lock_port (port, &lock);
2332 scm_lfwrite_unlocked (ptr, size, port);
2333 if (lock)
2334 scm_i_pthread_mutex_unlock (lock);
2335
2336 }
2337
2338 /* Write STR to PORT from START inclusive to END exclusive. */
2339 void
2340 scm_lfwrite_substr (SCM str, size_t start, size_t end, SCM port)
2341 {
2342 scm_t_port *pt = SCM_PTAB_ENTRY (port);
2343
2344 if (pt->rw_active == SCM_PORT_READ)
2345 scm_end_input_unlocked (port);
2346
2347 if (end == (size_t) -1)
2348 end = scm_i_string_length (str);
2349
2350 scm_display (scm_c_substring (str, start, end), port);
2351
2352 if (pt->rw_random)
2353 pt->rw_active = SCM_PORT_WRITE;
2354 }
2355
2356
2357 \f
2358
2359 /* Querying and setting positions, and character availability. */
2360
2361 SCM_DEFINE (scm_char_ready_p, "char-ready?", 0, 1, 0,
2362 (SCM port),
2363 "Return @code{#t} if a character is ready on input @var{port}\n"
2364 "and return @code{#f} otherwise. If @code{char-ready?} returns\n"
2365 "@code{#t} then the next @code{read-char} operation on\n"
2366 "@var{port} is guaranteed not to hang. If @var{port} is a file\n"
2367 "port at end of file then @code{char-ready?} returns @code{#t}.\n"
2368 "\n"
2369 "@code{char-ready?} exists to make it possible for a\n"
2370 "program to accept characters from interactive ports without\n"
2371 "getting stuck waiting for input. Any input editors associated\n"
2372 "with such ports must make sure that characters whose existence\n"
2373 "has been asserted by @code{char-ready?} cannot be rubbed out.\n"
2374 "If @code{char-ready?} were to return @code{#f} at end of file,\n"
2375 "a port at end of file would be indistinguishable from an\n"
2376 "interactive port that has no ready characters.")
2377 #define FUNC_NAME s_scm_char_ready_p
2378 {
2379 scm_t_port *pt;
2380
2381 if (SCM_UNBNDP (port))
2382 port = scm_current_input_port ();
2383 /* It's possible to close the current input port, so validate even in
2384 this case. */
2385 SCM_VALIDATE_OPINPORT (1, port);
2386
2387 pt = SCM_PTAB_ENTRY (port);
2388
2389 /* if the current read buffer is filled, or the
2390 last pushed-back char has been read and the saved buffer is
2391 filled, result is true. */
2392 if (pt->read_pos < pt->read_end
2393 || (pt->read_buf == pt->putback_buf
2394 && pt->saved_read_pos < pt->saved_read_end))
2395 return SCM_BOOL_T;
2396 else
2397 {
2398 scm_t_ptob_descriptor *ptob = SCM_PORT_DESCRIPTOR (port);
2399
2400 if (ptob->input_waiting)
2401 return scm_from_bool(ptob->input_waiting (port));
2402 else
2403 return SCM_BOOL_T;
2404 }
2405 }
2406 #undef FUNC_NAME
2407
2408 SCM_DEFINE (scm_seek, "seek", 3, 0, 0,
2409 (SCM fd_port, SCM offset, SCM whence),
2410 "Sets the current position of @var{fd_port} to the integer\n"
2411 "@var{offset}, which is interpreted according to the value of\n"
2412 "@var{whence}.\n"
2413 "\n"
2414 "One of the following variables should be supplied for\n"
2415 "@var{whence}:\n"
2416 "@defvar SEEK_SET\n"
2417 "Seek from the beginning of the file.\n"
2418 "@end defvar\n"
2419 "@defvar SEEK_CUR\n"
2420 "Seek from the current position.\n"
2421 "@end defvar\n"
2422 "@defvar SEEK_END\n"
2423 "Seek from the end of the file.\n"
2424 "@end defvar\n"
2425 "If @var{fd_port} is a file descriptor, the underlying system\n"
2426 "call is @code{lseek}. @var{port} may be a string port.\n"
2427 "\n"
2428 "The value returned is the new position in the file. This means\n"
2429 "that the current position of a port can be obtained using:\n"
2430 "@lisp\n"
2431 "(seek port 0 SEEK_CUR)\n"
2432 "@end lisp")
2433 #define FUNC_NAME s_scm_seek
2434 {
2435 int how;
2436
2437 fd_port = SCM_COERCE_OUTPORT (fd_port);
2438
2439 how = scm_to_int (whence);
2440 if (how != SEEK_SET && how != SEEK_CUR && how != SEEK_END)
2441 SCM_OUT_OF_RANGE (3, whence);
2442
2443 if (SCM_OPPORTP (fd_port))
2444 {
2445 scm_t_ptob_descriptor *ptob = SCM_PORT_DESCRIPTOR (fd_port);
2446 off_t_or_off64_t off = scm_to_off_t_or_off64_t (offset);
2447 off_t_or_off64_t rv;
2448
2449 if (!ptob->seek)
2450 SCM_MISC_ERROR ("port is not seekable",
2451 scm_cons (fd_port, SCM_EOL));
2452 else
2453 rv = ptob->seek (fd_port, off, how);
2454 return scm_from_off_t_or_off64_t (rv);
2455 }
2456 else /* file descriptor?. */
2457 {
2458 off_t_or_off64_t off = scm_to_off_t_or_off64_t (offset);
2459 off_t_or_off64_t rv;
2460 rv = lseek_or_lseek64 (scm_to_int (fd_port), off, how);
2461 if (rv == -1)
2462 SCM_SYSERROR;
2463 return scm_from_off_t_or_off64_t (rv);
2464 }
2465 }
2466 #undef FUNC_NAME
2467
2468 #ifndef O_BINARY
2469 #define O_BINARY 0
2470 #endif
2471
2472 /* Mingw has ftruncate(), perhaps implemented above using chsize, but
2473 doesn't have the filename version truncate(), hence this code. */
2474 #if HAVE_FTRUNCATE && ! HAVE_TRUNCATE
2475 static int
2476 truncate (const char *file, off_t length)
2477 {
2478 int ret, fdes;
2479
2480 fdes = open (file, O_BINARY | O_WRONLY);
2481 if (fdes == -1)
2482 return -1;
2483
2484 ret = ftruncate (fdes, length);
2485 if (ret == -1)
2486 {
2487 int save_errno = errno;
2488 close (fdes);
2489 errno = save_errno;
2490 return -1;
2491 }
2492
2493 return close (fdes);
2494 }
2495 #endif /* HAVE_FTRUNCATE && ! HAVE_TRUNCATE */
2496
2497 SCM_DEFINE (scm_truncate_file, "truncate-file", 1, 1, 0,
2498 (SCM object, SCM length),
2499 "Truncate file @var{object} to @var{length} bytes. @var{object}\n"
2500 "can be a filename string, a port object, or an integer file\n"
2501 "descriptor.\n"
2502 "The return value is unspecified.\n"
2503 "\n"
2504 "For a port or file descriptor @var{length} can be omitted, in\n"
2505 "which case the file is truncated at the current position (per\n"
2506 "@code{ftell} above).\n"
2507 "\n"
2508 "On most systems a file can be extended by giving a length\n"
2509 "greater than the current size, but this is not mandatory in the\n"
2510 "POSIX standard.")
2511 #define FUNC_NAME s_scm_truncate_file
2512 {
2513 int rv;
2514
2515 /* "object" can be a port, fdes or filename.
2516
2517 Negative "length" makes no sense, but it's left to truncate() or
2518 ftruncate() to give back an error for that (normally EINVAL).
2519 */
2520
2521 if (SCM_UNBNDP (length))
2522 {
2523 /* must supply length if object is a filename. */
2524 if (scm_is_string (object))
2525 SCM_MISC_ERROR("must supply length if OBJECT is a filename", SCM_EOL);
2526
2527 length = scm_seek (object, SCM_INUM0, scm_from_int (SEEK_CUR));
2528 }
2529
2530 object = SCM_COERCE_OUTPORT (object);
2531 if (scm_is_integer (object))
2532 {
2533 off_t_or_off64_t c_length = scm_to_off_t_or_off64_t (length);
2534 SCM_SYSCALL (rv = ftruncate_or_ftruncate64 (scm_to_int (object),
2535 c_length));
2536 }
2537 else if (SCM_OPOUTPORTP (object))
2538 {
2539 off_t_or_off64_t c_length = scm_to_off_t_or_off64_t (length);
2540 scm_t_port *pt = SCM_PTAB_ENTRY (object);
2541 scm_t_ptob_descriptor *ptob = SCM_PORT_DESCRIPTOR (object);
2542
2543 if (!ptob->truncate)
2544 SCM_MISC_ERROR ("port is not truncatable", SCM_EOL);
2545 if (pt->rw_active == SCM_PORT_READ)
2546 scm_end_input_unlocked (object);
2547 else if (pt->rw_active == SCM_PORT_WRITE)
2548 ptob->flush (object);
2549
2550 ptob->truncate (object, c_length);
2551 rv = 0;
2552 }
2553 else
2554 {
2555 off_t_or_off64_t c_length = scm_to_off_t_or_off64_t (length);
2556 char *str = scm_to_locale_string (object);
2557 int eno;
2558 SCM_SYSCALL (rv = truncate_or_truncate64 (str, c_length));
2559 eno = errno;
2560 free (str);
2561 errno = eno;
2562 }
2563 if (rv == -1)
2564 SCM_SYSERROR;
2565 return SCM_UNSPECIFIED;
2566 }
2567 #undef FUNC_NAME
2568
2569 SCM_DEFINE (scm_port_line, "port-line", 1, 0, 0,
2570 (SCM port),
2571 "Return the current line number for @var{port}.\n"
2572 "\n"
2573 "The first line of a file is 0. But you might want to add 1\n"
2574 "when printing line numbers, since starting from 1 is\n"
2575 "traditional in error messages, and likely to be more natural to\n"
2576 "non-programmers.")
2577 #define FUNC_NAME s_scm_port_line
2578 {
2579 port = SCM_COERCE_OUTPORT (port);
2580 SCM_VALIDATE_OPENPORT (1, port);
2581 return scm_from_long (SCM_LINUM (port));
2582 }
2583 #undef FUNC_NAME
2584
2585 SCM_DEFINE (scm_set_port_line_x, "set-port-line!", 2, 0, 0,
2586 (SCM port, SCM line),
2587 "Set the current line number for @var{port} to @var{line}. The\n"
2588 "first line of a file is 0.")
2589 #define FUNC_NAME s_scm_set_port_line_x
2590 {
2591 port = SCM_COERCE_OUTPORT (port);
2592 SCM_VALIDATE_OPENPORT (1, port);
2593 SCM_PTAB_ENTRY (port)->line_number = scm_to_long (line);
2594 return SCM_UNSPECIFIED;
2595 }
2596 #undef FUNC_NAME
2597
2598 SCM_DEFINE (scm_port_column, "port-column", 1, 0, 0,
2599 (SCM port),
2600 "Return the current column number of @var{port}.\n"
2601 "If the number is\n"
2602 "unknown, the result is #f. Otherwise, the result is a 0-origin integer\n"
2603 "- i.e. the first character of the first line is line 0, column 0.\n"
2604 "(However, when you display a file position, for example in an error\n"
2605 "message, we recommend you add 1 to get 1-origin integers. This is\n"
2606 "because lines and column numbers traditionally start with 1, and that is\n"
2607 "what non-programmers will find most natural.)")
2608 #define FUNC_NAME s_scm_port_column
2609 {
2610 port = SCM_COERCE_OUTPORT (port);
2611 SCM_VALIDATE_OPENPORT (1, port);
2612 return scm_from_int (SCM_COL (port));
2613 }
2614 #undef FUNC_NAME
2615
2616 SCM_DEFINE (scm_set_port_column_x, "set-port-column!", 2, 0, 0,
2617 (SCM port, SCM column),
2618 "Set the current column of @var{port}. Before reading the first\n"
2619 "character on a line the column should be 0.")
2620 #define FUNC_NAME s_scm_set_port_column_x
2621 {
2622 port = SCM_COERCE_OUTPORT (port);
2623 SCM_VALIDATE_OPENPORT (1, port);
2624 SCM_PTAB_ENTRY (port)->column_number = scm_to_int (column);
2625 return SCM_UNSPECIFIED;
2626 }
2627 #undef FUNC_NAME
2628
2629 SCM_DEFINE (scm_port_filename, "port-filename", 1, 0, 0,
2630 (SCM port),
2631 "Return the filename associated with @var{port}, or @code{#f}\n"
2632 "if no filename is associated with the port.")
2633 #define FUNC_NAME s_scm_port_filename
2634 {
2635 port = SCM_COERCE_OUTPORT (port);
2636 SCM_VALIDATE_OPENPORT (1, port);
2637 return SCM_FILENAME (port);
2638 }
2639 #undef FUNC_NAME
2640
2641 SCM_DEFINE (scm_set_port_filename_x, "set-port-filename!", 2, 0, 0,
2642 (SCM port, SCM filename),
2643 "Change the filename associated with @var{port}, using the current input\n"
2644 "port if none is specified. Note that this does not change the port's\n"
2645 "source of data, but only the value that is returned by\n"
2646 "@code{port-filename} and reported in diagnostic output.")
2647 #define FUNC_NAME s_scm_set_port_filename_x
2648 {
2649 port = SCM_COERCE_OUTPORT (port);
2650 SCM_VALIDATE_OPENPORT (1, port);
2651 /* We allow the user to set the filename to whatever he likes. */
2652 SCM_SET_FILENAME (port, filename);
2653 return SCM_UNSPECIFIED;
2654 }
2655 #undef FUNC_NAME
2656
2657
2658 \f
2659
2660 /* Implementation helpers for port printing functions. */
2661
2662 void
2663 scm_print_port_mode (SCM exp, SCM port)
2664 {
2665 scm_puts_unlocked (SCM_CLOSEDP (exp)
2666 ? "closed: "
2667 : (SCM_RDNG & SCM_CELL_WORD_0 (exp)
2668 ? (SCM_WRTNG & SCM_CELL_WORD_0 (exp)
2669 ? "input-output: "
2670 : "input: ")
2671 : (SCM_WRTNG & SCM_CELL_WORD_0 (exp)
2672 ? "output: "
2673 : "bogus: ")),
2674 port);
2675 }
2676
2677 int
2678 scm_port_print (SCM exp, SCM port, scm_print_state *pstate SCM_UNUSED)
2679 {
2680 char *type = SCM_PTOBNAME (SCM_PTOBNUM (exp));
2681 if (!type)
2682 type = "port";
2683 scm_puts_unlocked ("#<", port);
2684 scm_print_port_mode (exp, port);
2685 scm_puts_unlocked (type, port);
2686 scm_putc_unlocked (' ', port);
2687 scm_uintprint (SCM_CELL_WORD_1 (exp), 16, port);
2688 scm_putc_unlocked ('>', port);
2689 return 1;
2690 }
2691
2692
2693 \f
2694
2695 /* Iterating over all ports. */
2696
2697 struct for_each_data
2698 {
2699 void (*proc) (void *data, SCM p);
2700 void *data;
2701 };
2702
2703 static SCM
2704 for_each_trampoline (void *data, SCM port, SCM result)
2705 {
2706 struct for_each_data *d = data;
2707
2708 d->proc (d->data, port);
2709
2710 return result;
2711 }
2712
2713 void
2714 scm_c_port_for_each (void (*proc)(void *data, SCM p), void *data)
2715 {
2716 struct for_each_data d;
2717
2718 d.proc = proc;
2719 d.data = data;
2720
2721 scm_c_weak_set_fold (for_each_trampoline, &d, SCM_EOL,
2722 scm_i_port_weak_set);
2723 }
2724
2725 static void
2726 scm_for_each_trampoline (void *data, SCM port)
2727 {
2728 scm_call_1 (SCM_PACK_POINTER (data), port);
2729 }
2730
2731 SCM_DEFINE (scm_port_for_each, "port-for-each", 1, 0, 0,
2732 (SCM proc),
2733 "Apply @var{proc} to each port in the Guile port table\n"
2734 "in turn. The return value is unspecified. More specifically,\n"
2735 "@var{proc} is applied exactly once to every port that exists\n"
2736 "in the system at the time @code{port-for-each} is invoked.\n"
2737 "Changes to the port table while @code{port-for-each} is running\n"
2738 "have no effect as far as @code{port-for-each} is concerned.")
2739 #define FUNC_NAME s_scm_port_for_each
2740 {
2741 SCM_VALIDATE_PROC (1, proc);
2742
2743 scm_c_port_for_each (scm_for_each_trampoline, SCM_UNPACK_POINTER (proc));
2744
2745 return SCM_UNSPECIFIED;
2746 }
2747 #undef FUNC_NAME
2748
2749 static void
2750 flush_output_port (void *closure, SCM port)
2751 {
2752 if (SCM_OPOUTPORTP (port))
2753 scm_flush_unlocked (port);
2754 }
2755
2756 SCM_DEFINE (scm_flush_all_ports, "flush-all-ports", 0, 0, 0,
2757 (),
2758 "Equivalent to calling @code{force-output} on\n"
2759 "all open output ports. The return value is unspecified.")
2760 #define FUNC_NAME s_scm_flush_all_ports
2761 {
2762 scm_c_port_for_each (&flush_output_port, NULL);
2763 return SCM_UNSPECIFIED;
2764 }
2765 #undef FUNC_NAME
2766
2767
2768 \f
2769
2770 /* Void ports. */
2771
2772 scm_t_bits scm_tc16_void_port = 0;
2773
2774 static int fill_input_void_port (SCM port SCM_UNUSED)
2775 {
2776 return EOF;
2777 }
2778
2779 static void
2780 write_void_port (SCM port SCM_UNUSED,
2781 const void *data SCM_UNUSED,
2782 size_t size SCM_UNUSED)
2783 {
2784 }
2785
2786 static SCM
2787 scm_i_void_port (long mode_bits)
2788 {
2789 SCM ret;
2790
2791 ret = scm_c_make_port (scm_tc16_void_port, mode_bits, 0);
2792
2793 scm_port_non_buffer (SCM_PTAB_ENTRY (ret));
2794
2795 return ret;
2796 }
2797
2798 SCM
2799 scm_void_port (char *mode_str)
2800 {
2801 return scm_i_void_port (scm_mode_bits (mode_str));
2802 }
2803
2804 SCM_DEFINE (scm_sys_make_void_port, "%make-void-port", 1, 0, 0,
2805 (SCM mode),
2806 "Create and return a new void port. A void port acts like\n"
2807 "@file{/dev/null}. The @var{mode} argument\n"
2808 "specifies the input/output modes for this port: see the\n"
2809 "documentation for @code{open-file} in @ref{File Ports}.")
2810 #define FUNC_NAME s_scm_sys_make_void_port
2811 {
2812 return scm_i_void_port (scm_i_mode_bits (mode));
2813 }
2814 #undef FUNC_NAME
2815
2816
2817 \f
2818
2819 /* Initialization. */
2820
2821 void
2822 scm_init_ports ()
2823 {
2824 /* lseek() symbols. */
2825 scm_c_define ("SEEK_SET", scm_from_int (SEEK_SET));
2826 scm_c_define ("SEEK_CUR", scm_from_int (SEEK_CUR));
2827 scm_c_define ("SEEK_END", scm_from_int (SEEK_END));
2828
2829 scm_tc16_void_port = scm_make_port_type ("void", fill_input_void_port,
2830 write_void_port);
2831
2832 cur_inport_fluid = scm_make_fluid ();
2833 cur_outport_fluid = scm_make_fluid ();
2834 cur_errport_fluid = scm_make_fluid ();
2835 cur_loadport_fluid = scm_make_fluid ();
2836
2837 scm_i_port_weak_set = scm_c_make_weak_set (31);
2838
2839 #include "libguile/ports.x"
2840
2841 /* Use Latin-1 as the default port encoding. */
2842 SCM_VARIABLE_SET (default_port_encoding_var,
2843 scm_make_fluid_with_default (SCM_BOOL_F));
2844 scm_port_encoding_init = 1;
2845
2846 SCM_VARIABLE_SET (scm_conversion_strategy,
2847 scm_make_fluid_with_default
2848 (scm_from_int ((int) SCM_FAILED_CONVERSION_QUESTION_MARK)));
2849 scm_conversion_strategy_init = 1;
2850
2851 /* These bindings are used when boot-9 turns `current-input-port' et
2852 al into parameters. They are then removed from the guile module. */
2853 scm_c_define ("%current-input-port-fluid", cur_inport_fluid);
2854 scm_c_define ("%current-output-port-fluid", cur_outport_fluid);
2855 scm_c_define ("%current-error-port-fluid", cur_errport_fluid);
2856 }
2857
2858 /*
2859 Local Variables:
2860 c-file-style: "gnu"
2861 End:
2862 */