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