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