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