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