1 /* Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2006,
2 * 2007, 2008, 2009, 2010, 2011, 2012, 2013 Free Software Foundation, Inc.
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.
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.
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
24 #define _LARGEFILE64_SOURCE /* ask for stat64 etc */
32 #include <fcntl.h> /* for chsize on mingw */
37 #include <striconveh.h>
38 #include <c-strcase.h>
42 #include "libguile/_scm.h"
43 #include "libguile/async.h"
44 #include "libguile/deprecation.h"
45 #include "libguile/eval.h"
46 #include "libguile/fports.h" /* direct access for seek and truncate */
47 #include "libguile/goops.h"
48 #include "libguile/smob.h"
49 #include "libguile/chars.h"
50 #include "libguile/dynwind.h"
52 #include "libguile/keywords.h"
53 #include "libguile/hashtab.h"
54 #include "libguile/root.h"
55 #include "libguile/strings.h"
56 #include "libguile/mallocs.h"
57 #include "libguile/validate.h"
58 #include "libguile/ports.h"
59 #include "libguile/ports-internal.h"
60 #include "libguile/vectors.h"
61 #include "libguile/weaks.h"
62 #include "libguile/fluids.h"
63 #include "libguile/eq.h"
77 #ifdef HAVE_SYS_IOCTL_H
78 #include <sys/ioctl.h>
81 /* Mingw (version 3.4.5, circa 2006) has ftruncate as an alias for chsize
82 already, but have this code here in case that wasn't so in past versions,
83 or perhaps to help other minimal DOS environments.
85 gnulib ftruncate.c has code using fcntl F_CHSIZE and F_FREESP, which
86 might be possibilities if we've got other systems without ftruncate. */
88 #if defined HAVE_CHSIZE && ! defined HAVE_FTRUNCATE
89 #define ftruncate(fd, size) chsize (fd, size)
91 #define HAVE_FTRUNCATE 1
95 /* The port kind table --- a dynamically resized array of port types. */
98 /* scm_ptobs scm_numptob
99 * implement a dynamically resized array of ptob records.
100 * Indexes into this table are used when generating type
101 * tags for smobjects (if you know a tag you can get an index and conversely).
103 scm_t_ptob_descriptor
*scm_ptobs
= NULL
;
104 long scm_numptob
= 0;
106 /* GC marker for a port with stream of SCM type. */
108 scm_markstream (SCM ptr
)
111 openp
= SCM_CELL_WORD_0 (ptr
) & SCM_OPN
;
113 return SCM_PACK (SCM_STREAM (ptr
));
119 * We choose to use an interface similar to the smob interface with
120 * fill_input and write as standard fields, passed to the port
121 * type constructor, and optional fields set by setters.
125 flush_port_default (SCM port SCM_UNUSED
)
130 end_input_default (SCM port SCM_UNUSED
, int offset SCM_UNUSED
)
135 scm_make_port_type (char *name
,
136 int (*fill_input
) (SCM port
),
137 void (*write
) (SCM port
, const void *data
, size_t size
))
140 if (SCM_I_MAX_PORT_TYPE_COUNT
- 1 <= scm_numptob
)
142 SCM_CRITICAL_SECTION_START
;
143 tmp
= (char *) scm_gc_realloc ((char *) scm_ptobs
,
144 scm_numptob
* sizeof (scm_t_ptob_descriptor
),
146 * sizeof (scm_t_ptob_descriptor
),
150 scm_ptobs
= (scm_t_ptob_descriptor
*) tmp
;
152 scm_ptobs
[scm_numptob
].name
= name
;
153 scm_ptobs
[scm_numptob
].mark
= 0;
154 scm_ptobs
[scm_numptob
].free
= NULL
;
155 scm_ptobs
[scm_numptob
].print
= scm_port_print
;
156 scm_ptobs
[scm_numptob
].equalp
= 0;
157 scm_ptobs
[scm_numptob
].close
= 0;
159 scm_ptobs
[scm_numptob
].write
= write
;
160 scm_ptobs
[scm_numptob
].flush
= flush_port_default
;
162 scm_ptobs
[scm_numptob
].end_input
= end_input_default
;
163 scm_ptobs
[scm_numptob
].fill_input
= fill_input
;
164 scm_ptobs
[scm_numptob
].input_waiting
= 0;
166 scm_ptobs
[scm_numptob
].seek
= 0;
167 scm_ptobs
[scm_numptob
].truncate
= 0;
171 SCM_CRITICAL_SECTION_END
;
175 scm_memory_error ("scm_make_port_type");
177 /* Make a class object if Goops is present */
178 if (SCM_UNPACK (scm_port_class
[0]) != 0)
179 scm_make_port_classes (scm_numptob
- 1, SCM_PTOBNAME (scm_numptob
- 1));
180 return scm_tc7_port
+ (scm_numptob
- 1) * 256;
184 scm_set_port_mark (scm_t_bits tc
, SCM (*mark
) (SCM
))
186 scm_ptobs
[SCM_TC2PTOBNUM (tc
)].mark
= mark
;
190 scm_set_port_free (scm_t_bits tc
, size_t (*free
) (SCM
))
192 scm_ptobs
[SCM_TC2PTOBNUM (tc
)].free
= free
;
196 scm_set_port_print (scm_t_bits tc
, int (*print
) (SCM exp
, SCM port
,
197 scm_print_state
*pstate
))
199 scm_ptobs
[SCM_TC2PTOBNUM (tc
)].print
= print
;
203 scm_set_port_equalp (scm_t_bits tc
, SCM (*equalp
) (SCM
, SCM
))
205 scm_ptobs
[SCM_TC2PTOBNUM (tc
)].equalp
= equalp
;
209 scm_set_port_flush (scm_t_bits tc
, void (*flush
) (SCM port
))
211 scm_ptobs
[SCM_TC2PTOBNUM (tc
)].flush
= flush
;
215 scm_set_port_end_input (scm_t_bits tc
, void (*end_input
) (SCM port
, int offset
))
217 scm_ptobs
[SCM_TC2PTOBNUM (tc
)].end_input
= end_input
;
221 scm_set_port_close (scm_t_bits tc
, int (*close
) (SCM
))
223 scm_ptobs
[SCM_TC2PTOBNUM (tc
)].close
= close
;
227 scm_set_port_seek (scm_t_bits tc
,
228 scm_t_off (*seek
) (SCM
, scm_t_off
, int))
230 scm_ptobs
[SCM_TC2PTOBNUM (tc
)].seek
= seek
;
234 scm_set_port_truncate (scm_t_bits tc
, void (*truncate
) (SCM
, scm_t_off
))
236 scm_ptobs
[SCM_TC2PTOBNUM (tc
)].truncate
= truncate
;
240 scm_set_port_input_waiting (scm_t_bits tc
, int (*input_waiting
) (SCM
))
242 scm_ptobs
[SCM_TC2PTOBNUM (tc
)].input_waiting
= input_waiting
;
246 scm_i_set_pending_eof (SCM port
)
248 SCM_PORT_GET_INTERNAL (port
)->pending_eof
= 1;
252 scm_i_clear_pending_eof (SCM port
)
254 SCM_PORT_GET_INTERNAL (port
)->pending_eof
= 0;
258 scm_i_port_alist (SCM port
)
260 return SCM_PORT_GET_INTERNAL (port
)->alist
;
264 scm_i_set_port_alist_x (SCM port
, SCM alist
)
266 SCM_PORT_GET_INTERNAL (port
)->alist
= alist
;
271 SCM_DEFINE (scm_char_ready_p
, "char-ready?", 0, 1, 0,
273 "Return @code{#t} if a character is ready on input @var{port}\n"
274 "and return @code{#f} otherwise. If @code{char-ready?} returns\n"
275 "@code{#t} then the next @code{read-char} operation on\n"
276 "@var{port} is guaranteed not to hang. If @var{port} is a file\n"
277 "port at end of file then @code{char-ready?} returns @code{#t}.\n"
279 "@code{char-ready?} exists to make it possible for a\n"
280 "program to accept characters from interactive ports without\n"
281 "getting stuck waiting for input. Any input editors associated\n"
282 "with such ports must make sure that characters whose existence\n"
283 "has been asserted by @code{char-ready?} cannot be rubbed out.\n"
284 "If @code{char-ready?} were to return @code{#f} at end of file,\n"
285 "a port at end of file would be indistinguishable from an\n"
286 "interactive port that has no ready characters.")
287 #define FUNC_NAME s_scm_char_ready_p
291 if (SCM_UNBNDP (port
))
292 port
= scm_current_input_port ();
293 /* It's possible to close the current input port, so validate even in
295 SCM_VALIDATE_OPINPORT (1, port
);
297 pt
= SCM_PTAB_ENTRY (port
);
299 /* if the current read buffer is filled, or the
300 last pushed-back char has been read and the saved buffer is
301 filled, result is true. */
302 if (pt
->read_pos
< pt
->read_end
303 || (pt
->read_buf
== pt
->putback_buf
304 && pt
->saved_read_pos
< pt
->saved_read_end
))
308 scm_t_ptob_descriptor
*ptob
= &scm_ptobs
[SCM_PTOBNUM (port
)];
310 if (ptob
->input_waiting
)
311 return scm_from_bool(ptob
->input_waiting (port
));
318 /* Move up to READ_LEN bytes from PORT's putback and/or read buffers
319 into memory starting at DEST. Return the number of bytes moved.
320 PORT's line/column numbers are left unchanged. */
322 scm_take_from_input_buffers (SCM port
, char *dest
, size_t read_len
)
324 scm_t_port
*pt
= SCM_PTAB_ENTRY (port
);
325 size_t bytes_read
= 0;
326 size_t from_buf
= min (pt
->read_end
- pt
->read_pos
, read_len
);
330 memcpy (dest
, pt
->read_pos
, from_buf
);
331 pt
->read_pos
+= from_buf
;
332 bytes_read
+= from_buf
;
333 read_len
-= from_buf
;
337 /* if putback was active, try the real input buffer too. */
338 if (pt
->read_buf
== pt
->putback_buf
)
340 from_buf
= min (pt
->saved_read_end
- pt
->saved_read_pos
, read_len
);
343 memcpy (dest
, pt
->saved_read_pos
, from_buf
);
344 pt
->saved_read_pos
+= from_buf
;
345 bytes_read
+= from_buf
;
352 /* Clear a port's read buffers, returning the contents. */
353 SCM_DEFINE (scm_drain_input
, "drain-input", 1, 0, 0,
355 "This procedure clears a port's input buffers, similar\n"
356 "to the way that force-output clears the output buffer. The\n"
357 "contents of the buffers are returned as a single string, e.g.,\n"
360 "(define p (open-input-file ...))\n"
361 "(drain-input p) => empty string, nothing buffered yet.\n"
362 "(unread-char (read-char p) p)\n"
363 "(drain-input p) => initial chars from p, up to the buffer size.\n"
365 "Draining the buffers may be useful for cleanly finishing\n"
366 "buffered I/O so that the file descriptor can be used directly\n"
367 "for further input.")
368 #define FUNC_NAME s_scm_drain_input
375 SCM_VALIDATE_OPINPORT (1, port
);
376 pt
= SCM_PTAB_ENTRY (port
);
378 count
= pt
->read_end
- pt
->read_pos
;
379 if (pt
->read_buf
== pt
->putback_buf
)
380 count
+= pt
->saved_read_end
- pt
->saved_read_pos
;
384 result
= scm_i_make_string (count
, &data
, 0);
385 scm_take_from_input_buffers (port
, data
, count
);
388 result
= scm_nullstr
;
395 /* Standard ports --- current input, output, error, and more(!). */
397 static SCM cur_inport_fluid
= SCM_BOOL_F
;
398 static SCM cur_outport_fluid
= SCM_BOOL_F
;
399 static SCM cur_errport_fluid
= SCM_BOOL_F
;
400 static SCM cur_loadport_fluid
= SCM_BOOL_F
;
402 SCM_DEFINE (scm_current_input_port
, "current-input-port", 0, 0, 0,
404 "Return the current input port. This is the default port used\n"
405 "by many input procedures. Initially, @code{current-input-port}\n"
406 "returns the @dfn{standard input} in Unix and C terminology.")
407 #define FUNC_NAME s_scm_current_input_port
409 if (scm_is_true (cur_inport_fluid
))
410 return scm_fluid_ref (cur_inport_fluid
);
416 SCM_DEFINE (scm_current_output_port
, "current-output-port", 0, 0, 0,
418 "Return the current output port. This is the default port used\n"
419 "by many output procedures. Initially,\n"
420 "@code{current-output-port} returns the @dfn{standard output} in\n"
421 "Unix and C terminology.")
422 #define FUNC_NAME s_scm_current_output_port
424 if (scm_is_true (cur_outport_fluid
))
425 return scm_fluid_ref (cur_outport_fluid
);
431 SCM_DEFINE (scm_current_error_port
, "current-error-port", 0, 0, 0,
433 "Return the port to which errors and warnings should be sent (the\n"
434 "@dfn{standard error} in Unix and C terminology).")
435 #define FUNC_NAME s_scm_current_error_port
437 if (scm_is_true (cur_errport_fluid
))
438 return scm_fluid_ref (cur_errport_fluid
);
445 scm_current_warning_port (void)
447 static SCM cwp_var
= SCM_UNDEFINED
;
448 static scm_i_pthread_mutex_t cwp_var_mutex
449 = SCM_I_PTHREAD_MUTEX_INITIALIZER
;
451 scm_i_scm_pthread_mutex_lock (&cwp_var_mutex
);
452 if (SCM_UNBNDP (cwp_var
))
453 cwp_var
= scm_c_private_variable ("guile", "current-warning-port");
454 scm_i_pthread_mutex_unlock (&cwp_var_mutex
);
456 return scm_call_0 (scm_variable_ref (cwp_var
));
459 SCM_DEFINE (scm_current_load_port
, "current-load-port", 0, 0, 0,
461 "Return the current-load-port.\n"
462 "The load port is used internally by @code{primitive-load}.")
463 #define FUNC_NAME s_scm_current_load_port
465 return scm_fluid_ref (cur_loadport_fluid
);
469 SCM_DEFINE (scm_set_current_input_port
, "set-current-input-port", 1, 0, 0,
471 "@deffnx {Scheme Procedure} set-current-output-port port\n"
472 "@deffnx {Scheme Procedure} set-current-error-port port\n"
473 "Change the ports returned by @code{current-input-port},\n"
474 "@code{current-output-port} and @code{current-error-port}, respectively,\n"
475 "so that they use the supplied @var{port} for input or output.")
476 #define FUNC_NAME s_scm_set_current_input_port
478 SCM oinp
= scm_fluid_ref (cur_inport_fluid
);
479 SCM_VALIDATE_OPINPORT (1, port
);
480 scm_fluid_set_x (cur_inport_fluid
, port
);
486 SCM_DEFINE (scm_set_current_output_port
, "set-current-output-port", 1, 0, 0,
488 "Set the current default output port to @var{port}.")
489 #define FUNC_NAME s_scm_set_current_output_port
491 SCM ooutp
= scm_fluid_ref (cur_outport_fluid
);
492 port
= SCM_COERCE_OUTPORT (port
);
493 SCM_VALIDATE_OPOUTPORT (1, port
);
494 scm_fluid_set_x (cur_outport_fluid
, port
);
500 SCM_DEFINE (scm_set_current_error_port
, "set-current-error-port", 1, 0, 0,
502 "Set the current default error port to @var{port}.")
503 #define FUNC_NAME s_scm_set_current_error_port
505 SCM oerrp
= scm_fluid_ref (cur_errport_fluid
);
506 port
= SCM_COERCE_OUTPORT (port
);
507 SCM_VALIDATE_OPOUTPORT (1, port
);
508 scm_fluid_set_x (cur_errport_fluid
, port
);
515 scm_set_current_warning_port (SCM port
)
517 static SCM cwp_var
= SCM_BOOL_F
;
519 if (scm_is_false (cwp_var
))
520 cwp_var
= scm_c_private_lookup ("guile", "current-warning-port");
522 return scm_call_1 (scm_variable_ref (cwp_var
), port
);
527 scm_dynwind_current_input_port (SCM port
)
528 #define FUNC_NAME NULL
530 SCM_VALIDATE_OPINPORT (1, port
);
531 scm_dynwind_fluid (cur_inport_fluid
, port
);
536 scm_dynwind_current_output_port (SCM port
)
537 #define FUNC_NAME NULL
539 port
= SCM_COERCE_OUTPORT (port
);
540 SCM_VALIDATE_OPOUTPORT (1, port
);
541 scm_dynwind_fluid (cur_outport_fluid
, port
);
546 scm_dynwind_current_error_port (SCM port
)
547 #define FUNC_NAME NULL
549 port
= SCM_COERCE_OUTPORT (port
);
550 SCM_VALIDATE_OPOUTPORT (1, port
);
551 scm_dynwind_fluid (cur_errport_fluid
, port
);
556 scm_i_dynwind_current_load_port (SCM port
)
558 scm_dynwind_fluid (cur_loadport_fluid
, port
);
562 /* The port table --- an array of pointers to ports. */
565 We need a global registry of ports to flush them all at exit, and to
566 get all the ports matching a file descriptor.
568 SCM scm_i_port_weak_hash
;
570 scm_i_pthread_mutex_t scm_i_port_table_mutex
= SCM_I_PTHREAD_MUTEX_INITIALIZER
;
573 /* Port finalization. */
576 static void finalize_port (void *, void *);
578 /* Register a finalizer for PORT. */
579 static SCM_C_INLINE_KEYWORD
void
580 register_finalizer_for_port (SCM port
)
582 /* Register a finalizer for PORT so that its
583 type's `free' function gets called. */
584 scm_i_set_finalizer (SCM2PTR (port
), finalize_port
, NULL
);
587 /* Finalize the object (a port) pointed to by PTR. */
589 finalize_port (void *ptr
, void *data
)
592 SCM port
= PTR2SCM (ptr
);
594 if (!SCM_PORTP (port
))
597 if (SCM_OPENP (port
))
599 if (SCM_REVEALED (port
) > 0)
600 /* Keep "revealed" ports alive and re-register a finalizer. */
601 register_finalizer_for_port (port
);
604 port_type
= SCM_TC2PTOBNUM (SCM_CELL_TYPE (port
));
605 if (port_type
>= scm_numptob
)
608 if (scm_ptobs
[port_type
].free
)
609 /* Yes, I really do mean `.free' rather than `.close'. `.close'
610 is for explicit `close-port' by user. */
611 scm_ptobs
[port_type
].free (port
);
613 SCM_SETSTREAM (port
, 0);
614 SCM_CLR_PORT_OPEN_FLAG (port
);
616 scm_gc_ports_collected
++;
625 /* This function is not and should not be thread safe. */
627 scm_new_port_table_entry (scm_t_bits tag
)
628 #define FUNC_NAME "scm_new_port_table_entry"
631 We initialize the cell to empty, this is in case scm_gc_calloc
632 triggers GC ; we don't want the GC to scan a half-finished Z.
635 SCM z
= scm_cons (SCM_EOL
, SCM_EOL
);
636 scm_t_port
*entry
= scm_gc_typed_calloc (scm_t_port
);
637 scm_t_port_internal
*pti
= scm_gc_typed_calloc (scm_t_port_internal
);
638 const char *encoding
;
640 entry
->file_name
= SCM_BOOL_F
;
641 entry
->rw_active
= SCM_PORT_NEITHER
;
644 /* Initialize this port with the thread's current default
646 encoding
= scm_i_default_port_encoding ();
647 entry
->ilseq_handler
= scm_i_default_port_conversion_handler ();
648 entry
->encoding
= encoding
? scm_gc_strdup (encoding
, "port") : NULL
;
649 if (encoding
&& c_strcasecmp (encoding
, "UTF-8") == 0)
650 pti
->encoding_mode
= SCM_PORT_ENCODING_MODE_UTF8
;
652 pti
->encoding_mode
= SCM_PORT_ENCODING_MODE_ICONV
;
653 pti
->iconv_descriptors
= NULL
;
655 pti
->at_stream_start_for_bom_read
= 1;
656 pti
->at_stream_start_for_bom_write
= 1;
658 /* XXX These fields are not what they seem. They have been
659 repurposed, but cannot safely be renamed in 2.0 without breaking
660 ABI compatibility. This will be cleaned up in 2.2. */
661 entry
->input_cd
= pti
; /* XXX pointer to the internal port structure */
662 entry
->output_cd
= NULL
; /* XXX unused */
664 pti
->pending_eof
= 0;
665 pti
->alist
= SCM_EOL
;
667 SCM_SET_CELL_TYPE (z
, tag
);
668 SCM_SETPTAB_ENTRY (z
, entry
);
670 scm_hashq_set_x (scm_i_port_weak_hash
, z
, SCM_BOOL_F
);
672 /* For each new port, register a finalizer so that it port type's free
673 function can be invoked eventually. */
674 register_finalizer_for_port (z
);
680 #if SCM_ENABLE_DEPRECATED==1
682 scm_add_to_port_table (SCM port
)
687 scm_c_issue_deprecation_warning ("scm_add_to_port_table is deprecated.");
689 scm_i_pthread_mutex_lock (&scm_i_port_table_mutex
);
690 z
= scm_new_port_table_entry (scm_tc7_port
);
691 pt
= SCM_PTAB_ENTRY(z
);
693 SCM_SETCAR (z
, SCM_EOL
);
694 SCM_SETCDR (z
, SCM_EOL
);
695 SCM_SETPTAB_ENTRY (port
, pt
);
696 scm_i_pthread_mutex_unlock (&scm_i_port_table_mutex
);
703 /* Remove a port from the table and destroy it. */
705 static void close_iconv_descriptors (scm_t_iconv_descriptors
*id
);
708 scm_i_remove_port (SCM port
)
709 #define FUNC_NAME "scm_remove_port"
712 scm_t_port_internal
*pti
;
714 scm_i_scm_pthread_mutex_lock (&scm_i_port_table_mutex
);
716 p
= SCM_PTAB_ENTRY (port
);
717 pti
= SCM_PORT_GET_INTERNAL (port
);
718 scm_port_non_buffer (p
);
719 p
->putback_buf
= NULL
;
720 p
->putback_buf_size
= 0;
722 if (pti
->iconv_descriptors
)
724 close_iconv_descriptors (pti
->iconv_descriptors
);
725 pti
->iconv_descriptors
= NULL
;
728 SCM_SETPTAB_ENTRY (port
, 0);
730 scm_hashq_remove_x (scm_i_port_weak_hash
, port
);
732 scm_i_pthread_mutex_unlock (&scm_i_port_table_mutex
);
737 /* Functions for debugging. */
739 SCM_DEFINE (scm_pt_size
, "pt-size", 0, 0, 0,
741 "Return the number of ports in the port table. @code{pt-size}\n"
742 "is only included in @code{--enable-guile-debug} builds.")
743 #define FUNC_NAME s_scm_pt_size
745 return scm_from_int (SCM_HASHTABLE_N_ITEMS (scm_i_port_weak_hash
));
751 scm_port_non_buffer (scm_t_port
*pt
)
753 pt
->read_pos
= pt
->read_buf
= pt
->read_end
= &pt
->shortbuf
;
754 pt
->write_buf
= pt
->write_pos
= &pt
->shortbuf
;
755 pt
->read_buf_size
= pt
->write_buf_size
= 1;
756 pt
->write_end
= pt
->write_buf
+ pt
->write_buf_size
;
760 /* Revealed counts --- an oddity inherited from SCSH. */
762 /* Find a port in the table and return its revealed count.
763 Also used by the garbage collector.
767 scm_revealed_count (SCM port
)
769 return SCM_REVEALED(port
);
774 /* Return the revealed count for a port. */
776 SCM_DEFINE (scm_port_revealed
, "port-revealed", 1, 0, 0,
778 "Return the revealed count for @var{port}.")
779 #define FUNC_NAME s_scm_port_revealed
781 port
= SCM_COERCE_OUTPORT (port
);
782 SCM_VALIDATE_OPENPORT (1, port
);
783 return scm_from_int (scm_revealed_count (port
));
787 /* Set the revealed count for a port. */
788 SCM_DEFINE (scm_set_port_revealed_x
, "set-port-revealed!", 2, 0, 0,
789 (SCM port
, SCM rcount
),
790 "Sets the revealed count for a port to a given value.\n"
791 "The return value is unspecified.")
792 #define FUNC_NAME s_scm_set_port_revealed_x
794 port
= SCM_COERCE_OUTPORT (port
);
795 SCM_VALIDATE_OPENPORT (1, port
);
796 SCM_REVEALED (port
) = scm_to_int (rcount
);
797 return SCM_UNSPECIFIED
;
803 /* Retrieving a port's mode. */
805 /* Return the flags that characterize a port based on the mode
806 * string used to open a file for that port.
808 * See PORT FLAGS in scm.h
812 scm_i_mode_bits_n (SCM modes
)
815 | (scm_i_string_contains_char (modes
, 'r')
816 || scm_i_string_contains_char (modes
, '+') ? SCM_RDNG
: 0)
817 | (scm_i_string_contains_char (modes
, 'w')
818 || scm_i_string_contains_char (modes
, 'a')
819 || scm_i_string_contains_char (modes
, '+') ? SCM_WRTNG
: 0)
820 | (scm_i_string_contains_char (modes
, '0') ? SCM_BUF0
: 0)
821 | (scm_i_string_contains_char (modes
, 'l') ? SCM_BUFLINE
: 0));
825 scm_mode_bits (char *modes
)
827 return scm_i_mode_bits (scm_from_locale_string (modes
));
831 scm_i_mode_bits (SCM modes
)
835 if (!scm_is_string (modes
))
836 scm_wrong_type_arg_msg (NULL
, 0, modes
, "string");
838 bits
= scm_i_mode_bits_n (modes
);
839 scm_remember_upto_here_1 (modes
);
843 /* Return the mode flags from an open port.
844 * Some modes such as "append" are only used when opening
845 * a file and are not returned here. */
847 SCM_DEFINE (scm_port_mode
, "port-mode", 1, 0, 0,
849 "Return the port modes associated with the open port @var{port}.\n"
850 "These will not necessarily be identical to the modes used when\n"
851 "the port was opened, since modes such as \"append\" which are\n"
852 "used only during port creation are not retained.")
853 #define FUNC_NAME s_scm_port_mode
858 port
= SCM_COERCE_OUTPORT (port
);
859 SCM_VALIDATE_OPPORT (1, port
);
860 if (SCM_CELL_WORD_0 (port
) & SCM_RDNG
) {
861 if (SCM_CELL_WORD_0 (port
) & SCM_WRTNG
)
862 strcpy (modes
, "r+");
866 else if (SCM_CELL_WORD_0 (port
) & SCM_WRTNG
)
868 if (SCM_CELL_WORD_0 (port
) & SCM_BUF0
)
870 return scm_from_locale_string (modes
);
879 * Call the close operation on a port object.
880 * see also scm_close.
882 SCM_DEFINE (scm_close_port
, "close-port", 1, 0, 0,
884 "Close the specified port object. Return @code{#t} if it\n"
885 "successfully closes a port or @code{#f} if it was already\n"
886 "closed. An exception may be raised if an error occurs, for\n"
887 "example when flushing buffered output. See also @ref{Ports and\n"
888 "File Descriptors, close}, for a procedure which can close file\n"
890 #define FUNC_NAME s_scm_close_port
895 port
= SCM_COERCE_OUTPORT (port
);
897 SCM_VALIDATE_PORT (1, port
);
898 if (SCM_CLOSEDP (port
))
900 i
= SCM_PTOBNUM (port
);
901 if (scm_ptobs
[i
].close
)
902 rv
= (scm_ptobs
[i
].close
) (port
);
905 scm_i_remove_port (port
);
906 SCM_CLR_PORT_OPEN_FLAG (port
);
907 return scm_from_bool (rv
>= 0);
911 SCM_DEFINE (scm_close_input_port
, "close-input-port", 1, 0, 0,
913 "Close the specified input port object. The routine has no effect if\n"
914 "the file has already been closed. An exception may be raised if an\n"
915 "error occurs. The value returned is unspecified.\n\n"
916 "See also @ref{Ports and File Descriptors, close}, for a procedure\n"
917 "which can close file descriptors.")
918 #define FUNC_NAME s_scm_close_input_port
920 SCM_VALIDATE_INPUT_PORT (1, port
);
921 scm_close_port (port
);
922 return SCM_UNSPECIFIED
;
926 SCM_DEFINE (scm_close_output_port
, "close-output-port", 1, 0, 0,
928 "Close the specified output port object. The routine has no effect if\n"
929 "the file has already been closed. An exception may be raised if an\n"
930 "error occurs. The value returned is unspecified.\n\n"
931 "See also @ref{Ports and File Descriptors, close}, for a procedure\n"
932 "which can close file descriptors.")
933 #define FUNC_NAME s_scm_close_output_port
935 port
= SCM_COERCE_OUTPORT (port
);
936 SCM_VALIDATE_OUTPUT_PORT (1, port
);
937 scm_close_port (port
);
938 return SCM_UNSPECIFIED
;
943 collect_keys (void *unused
, SCM key
, SCM value
, SCM result
)
945 return scm_cons (key
, result
);
949 scm_c_port_for_each (void (*proc
)(void *data
, SCM p
), void *data
)
953 /* Copy out the port table as a list so that we get strong references
954 to all the values. */
955 scm_i_pthread_mutex_lock (&scm_i_port_table_mutex
);
956 ports
= scm_internal_hash_fold (collect_keys
, NULL
,
957 SCM_EOL
, scm_i_port_weak_hash
);
958 scm_i_pthread_mutex_unlock (&scm_i_port_table_mutex
);
960 for (; scm_is_pair (ports
); ports
= scm_cdr (ports
))
962 SCM p
= scm_car (ports
);
968 SCM_DEFINE (scm_port_for_each
, "port-for-each", 1, 0, 0,
970 "Apply @var{proc} to each port in the Guile port table\n"
971 "in turn. The return value is unspecified. More specifically,\n"
972 "@var{proc} is applied exactly once to every port that exists\n"
973 "in the system at the time @code{port-for-each} is invoked.\n"
974 "Changes to the port table while @code{port-for-each} is running\n"
975 "have no effect as far as @code{port-for-each} is concerned.")
976 #define FUNC_NAME s_scm_port_for_each
980 SCM_VALIDATE_PROC (1, proc
);
982 /* Copy out the port table as a list so that we get strong references
983 to all the values. */
984 scm_i_pthread_mutex_lock (&scm_i_port_table_mutex
);
985 ports
= scm_internal_hash_fold (collect_keys
, NULL
,
986 SCM_EOL
, scm_i_port_weak_hash
);
987 scm_i_pthread_mutex_unlock (&scm_i_port_table_mutex
);
989 for (; scm_is_pair (ports
); ports
= scm_cdr (ports
))
990 if (SCM_PORTP (SCM_CAR (ports
)))
991 scm_call_1 (proc
, SCM_CAR (ports
));
993 return SCM_UNSPECIFIED
;
999 /* Utter miscellany. Gosh, we should clean this up some time. */
1001 SCM_DEFINE (scm_input_port_p
, "input-port?", 1, 0, 0,
1003 "Return @code{#t} if @var{x} is an input port, otherwise return\n"
1004 "@code{#f}. Any object satisfying this predicate also satisfies\n"
1006 #define FUNC_NAME s_scm_input_port_p
1008 return scm_from_bool (SCM_INPUT_PORT_P (x
));
1012 SCM_DEFINE (scm_output_port_p
, "output-port?", 1, 0, 0,
1014 "Return @code{#t} if @var{x} is an output port, otherwise return\n"
1015 "@code{#f}. Any object satisfying this predicate also satisfies\n"
1017 #define FUNC_NAME s_scm_output_port_p
1019 x
= SCM_COERCE_OUTPORT (x
);
1020 return scm_from_bool (SCM_OUTPUT_PORT_P (x
));
1024 SCM_DEFINE (scm_port_p
, "port?", 1, 0, 0,
1026 "Return a boolean indicating whether @var{x} is a port.\n"
1027 "Equivalent to @code{(or (input-port? @var{x}) (output-port?\n"
1029 #define FUNC_NAME s_scm_port_p
1031 return scm_from_bool (SCM_PORTP (x
));
1035 SCM_DEFINE (scm_port_closed_p
, "port-closed?", 1, 0, 0,
1037 "Return @code{#t} if @var{port} is closed or @code{#f} if it is\n"
1039 #define FUNC_NAME s_scm_port_closed_p
1041 SCM_VALIDATE_PORT (1, port
);
1042 return scm_from_bool (!SCM_OPPORTP (port
));
1046 SCM_DEFINE (scm_eof_object_p
, "eof-object?", 1, 0, 0,
1048 "Return @code{#t} if @var{x} is an end-of-file object; otherwise\n"
1049 "return @code{#f}.")
1050 #define FUNC_NAME s_scm_eof_object_p
1052 return scm_from_bool(SCM_EOF_OBJECT_P (x
));
1056 SCM_DEFINE (scm_force_output
, "force-output", 0, 1, 0,
1058 "Flush the specified output port, or the current output port if @var{port}\n"
1059 "is omitted. The current output buffer contents are passed to the\n"
1060 "underlying port implementation (e.g., in the case of fports, the\n"
1061 "data will be written to the file and the output buffer will be cleared.)\n"
1062 "It has no effect on an unbuffered port.\n\n"
1063 "The return value is unspecified.")
1064 #define FUNC_NAME s_scm_force_output
1066 if (SCM_UNBNDP (port
))
1067 port
= scm_current_output_port ();
1070 port
= SCM_COERCE_OUTPORT (port
);
1071 SCM_VALIDATE_OPOUTPORT (1, port
);
1074 return SCM_UNSPECIFIED
;
1080 flush_output_port (void *closure
, SCM port
)
1082 if (SCM_OPOUTPORTP (port
))
1086 SCM_DEFINE (scm_flush_all_ports
, "flush-all-ports", 0, 0, 0,
1088 "Equivalent to calling @code{force-output} on\n"
1089 "all open output ports. The return value is unspecified.")
1090 #define FUNC_NAME s_scm_flush_all_ports
1092 scm_c_port_for_each (&flush_output_port
, NULL
);
1093 return SCM_UNSPECIFIED
;
1097 SCM_DEFINE (scm_read_char
, "read-char", 0, 1, 0,
1099 "Return the next character available from @var{port}, updating\n"
1100 "@var{port} to point to the following character. If no more\n"
1101 "characters are available, the end-of-file object is returned.\n"
1103 "When @var{port}'s data cannot be decoded according to its\n"
1104 "character encoding, a @code{decoding-error} is raised and\n"
1105 "@var{port} points past the erroneous byte sequence.\n")
1106 #define FUNC_NAME s_scm_read_char
1109 if (SCM_UNBNDP (port
))
1110 port
= scm_current_input_port ();
1111 SCM_VALIDATE_OPINPORT (1, port
);
1112 c
= scm_getc (port
);
1115 return SCM_MAKE_CHAR (c
);
1119 /* Update the line and column number of PORT after consumption of C. */
1121 update_port_lf (scm_t_wchar c
, SCM port
)
1146 #define SCM_MBCHAR_BUF_SIZE (4)
1148 /* Convert the SIZE-byte UTF-8 sequence in UTF8_BUF to a codepoint.
1149 UTF8_BUF is assumed to contain a valid UTF-8 sequence. */
1151 utf8_to_codepoint (const scm_t_uint8
*utf8_buf
, size_t size
)
1153 scm_t_wchar codepoint
;
1155 if (utf8_buf
[0] <= 0x7f)
1158 codepoint
= utf8_buf
[0];
1160 else if ((utf8_buf
[0] & 0xe0) == 0xc0)
1163 codepoint
= ((scm_t_wchar
) utf8_buf
[0] & 0x1f) << 6UL
1164 | (utf8_buf
[1] & 0x3f);
1166 else if ((utf8_buf
[0] & 0xf0) == 0xe0)
1169 codepoint
= ((scm_t_wchar
) utf8_buf
[0] & 0x0f) << 12UL
1170 | ((scm_t_wchar
) utf8_buf
[1] & 0x3f) << 6UL
1171 | (utf8_buf
[2] & 0x3f);
1176 codepoint
= ((scm_t_wchar
) utf8_buf
[0] & 0x07) << 18UL
1177 | ((scm_t_wchar
) utf8_buf
[1] & 0x3f) << 12UL
1178 | ((scm_t_wchar
) utf8_buf
[2] & 0x3f) << 6UL
1179 | (utf8_buf
[3] & 0x3f);
1185 /* Read a UTF-8 sequence from PORT. On success, return 0 and set
1186 *CODEPOINT to the codepoint that was read, fill BUF with its UTF-8
1187 representation, and set *LEN to the length in bytes. Return
1188 `EILSEQ' on error. */
1190 get_utf8_codepoint (SCM port
, scm_t_wchar
*codepoint
,
1191 scm_t_uint8 buf
[SCM_MBCHAR_BUF_SIZE
], size_t *len
)
1193 #define ASSERT_NOT_EOF(b) \
1194 if (SCM_UNLIKELY ((b) == EOF)) \
1196 #define CONSUME_PEEKED_BYTE() \
1203 pt
= SCM_PTAB_ENTRY (port
);
1205 byte
= scm_get_byte_or_eof (port
);
1212 buf
[0] = (scm_t_uint8
) byte
;
1217 *codepoint
= buf
[0];
1218 else if (buf
[0] >= 0xc2 && buf
[0] <= 0xdf)
1221 byte
= scm_peek_byte_or_eof (port
);
1222 ASSERT_NOT_EOF (byte
);
1224 if (SCM_UNLIKELY ((byte
& 0xc0) != 0x80))
1227 CONSUME_PEEKED_BYTE ();
1228 buf
[1] = (scm_t_uint8
) byte
;
1231 *codepoint
= ((scm_t_wchar
) buf
[0] & 0x1f) << 6UL
1234 else if ((buf
[0] & 0xf0) == 0xe0)
1237 byte
= scm_peek_byte_or_eof (port
);
1238 ASSERT_NOT_EOF (byte
);
1240 if (SCM_UNLIKELY ((byte
& 0xc0) != 0x80
1241 || (buf
[0] == 0xe0 && byte
< 0xa0)
1242 || (buf
[0] == 0xed && byte
> 0x9f)))
1245 CONSUME_PEEKED_BYTE ();
1246 buf
[1] = (scm_t_uint8
) byte
;
1249 byte
= scm_peek_byte_or_eof (port
);
1250 ASSERT_NOT_EOF (byte
);
1252 if (SCM_UNLIKELY ((byte
& 0xc0) != 0x80))
1255 CONSUME_PEEKED_BYTE ();
1256 buf
[2] = (scm_t_uint8
) byte
;
1259 *codepoint
= ((scm_t_wchar
) buf
[0] & 0x0f) << 12UL
1260 | ((scm_t_wchar
) buf
[1] & 0x3f) << 6UL
1263 else if (buf
[0] >= 0xf0 && buf
[0] <= 0xf4)
1266 byte
= scm_peek_byte_or_eof (port
);
1267 ASSERT_NOT_EOF (byte
);
1269 if (SCM_UNLIKELY (((byte
& 0xc0) != 0x80)
1270 || (buf
[0] == 0xf0 && byte
< 0x90)
1271 || (buf
[0] == 0xf4 && byte
> 0x8f)))
1274 CONSUME_PEEKED_BYTE ();
1275 buf
[1] = (scm_t_uint8
) byte
;
1278 byte
= scm_peek_byte_or_eof (port
);
1279 ASSERT_NOT_EOF (byte
);
1281 if (SCM_UNLIKELY ((byte
& 0xc0) != 0x80))
1284 CONSUME_PEEKED_BYTE ();
1285 buf
[2] = (scm_t_uint8
) byte
;
1288 byte
= scm_peek_byte_or_eof (port
);
1289 ASSERT_NOT_EOF (byte
);
1291 if (SCM_UNLIKELY ((byte
& 0xc0) != 0x80))
1294 CONSUME_PEEKED_BYTE ();
1295 buf
[3] = (scm_t_uint8
) byte
;
1298 *codepoint
= ((scm_t_wchar
) buf
[0] & 0x07) << 18UL
1299 | ((scm_t_wchar
) buf
[1] & 0x3f) << 12UL
1300 | ((scm_t_wchar
) buf
[2] & 0x3f) << 6UL
1309 /* Here we could choose the consume the faulty byte when it's not a
1310 valid starting byte, but it's not a requirement. What Section 3.9
1311 of Unicode 6.0.0 mandates, though, is to not consume a byte that
1312 would otherwise be a valid starting byte. */
1316 #undef CONSUME_PEEKED_BYTE
1317 #undef ASSERT_NOT_EOF
1320 /* Likewise, read a byte sequence from PORT, passing it through its
1321 input conversion descriptor. */
1323 get_iconv_codepoint (SCM port
, scm_t_wchar
*codepoint
,
1324 char buf
[SCM_MBCHAR_BUF_SIZE
], size_t *len
)
1326 scm_t_iconv_descriptors
*id
;
1327 scm_t_uint8 utf8_buf
[SCM_MBCHAR_BUF_SIZE
];
1328 size_t input_size
= 0;
1330 id
= scm_i_port_iconv_descriptors (port
, SCM_PORT_READ
);
1335 char *input
, *output
;
1336 size_t input_left
, output_left
, done
;
1338 byte_read
= scm_get_byte_or_eof (port
);
1339 if (SCM_UNLIKELY (byte_read
== EOF
))
1341 if (SCM_LIKELY (input_size
== 0))
1343 *codepoint
= (scm_t_wchar
) EOF
;
1349 /* EOF found in the middle of a multibyte character. */
1350 scm_i_set_pending_eof (port
);
1355 buf
[input_size
++] = byte_read
;
1358 input_left
= input_size
;
1359 output
= (char *) utf8_buf
;
1360 output_left
= sizeof (utf8_buf
);
1362 done
= iconv (id
->input_cd
, &input
, &input_left
, &output
, &output_left
);
1364 if (done
== (size_t) -1)
1367 if (SCM_LIKELY (err
== EINVAL
))
1368 /* The input byte sequence did not form a complete
1369 character. Read another byte and try again. */
1376 size_t output_size
= sizeof (utf8_buf
) - output_left
;
1377 if (SCM_LIKELY (output_size
> 0))
1379 /* iconv generated output. Convert the UTF8_BUF sequence
1380 to a Unicode code point. */
1381 *codepoint
= utf8_to_codepoint (utf8_buf
, output_size
);
1387 /* iconv consumed some bytes without producing any output.
1388 Most likely this means that a Unicode byte-order mark
1389 (BOM) was consumed, which should not be included in the
1390 returned buf. Shift any remaining bytes to the beginning
1391 of buf, and continue the loop. */
1392 memmove (buf
, input
, input_left
);
1393 input_size
= input_left
;
1400 /* Read a codepoint from PORT and return it in *CODEPOINT. Fill BUF
1401 with the byte representation of the codepoint in PORT's encoding, and
1402 set *LEN to the length in bytes of that representation. Return 0 on
1403 success and an errno value on error. */
1405 get_codepoint (SCM port
, scm_t_wchar
*codepoint
,
1406 char buf
[SCM_MBCHAR_BUF_SIZE
], size_t *len
)
1409 scm_t_port
*pt
= SCM_PTAB_ENTRY (port
);
1410 scm_t_port_internal
*pti
= SCM_PORT_GET_INTERNAL (port
);
1412 if (pti
->encoding_mode
== SCM_PORT_ENCODING_MODE_UTF8
)
1413 err
= get_utf8_codepoint (port
, codepoint
, (scm_t_uint8
*) buf
, len
);
1415 err
= get_iconv_codepoint (port
, codepoint
, buf
, len
);
1417 if (SCM_LIKELY (err
== 0))
1419 if (SCM_UNLIKELY (pti
->at_stream_start_for_bom_read
))
1421 /* Record that we're no longer at stream start. */
1422 pti
->at_stream_start_for_bom_read
= 0;
1424 pti
->at_stream_start_for_bom_write
= 0;
1426 /* If we just read a BOM in an encoding that recognizes them,
1427 then silently consume it and read another code point. */
1429 (*codepoint
== SCM_UNICODE_BOM
1430 && (pti
->encoding_mode
== SCM_PORT_ENCODING_MODE_UTF8
1431 || c_strcasecmp (pt
->encoding
, "UTF-16") == 0
1432 || c_strcasecmp (pt
->encoding
, "UTF-32") == 0)))
1433 return get_codepoint (port
, codepoint
, buf
, len
);
1435 update_port_lf (*codepoint
, port
);
1437 else if (pt
->ilseq_handler
== SCM_ICONVEH_QUESTION_MARK
)
1441 update_port_lf (*codepoint
, port
);
1447 /* Read a codepoint from PORT and return it. */
1450 #define FUNC_NAME "scm_getc"
1454 scm_t_wchar codepoint
;
1455 char buf
[SCM_MBCHAR_BUF_SIZE
];
1457 err
= get_codepoint (port
, &codepoint
, buf
, &len
);
1458 if (SCM_UNLIKELY (err
!= 0))
1459 /* At this point PORT should point past the invalid encoding, as per
1460 R6RS-lib Section 8.2.4. */
1461 scm_decoding_error (FUNC_NAME
, err
, "input decoding error", port
);
1467 /* this should only be called when the read buffer is empty. it
1468 tries to refill the read buffer. it returns the first char from
1469 the port, which is either EOF or *(pt->read_pos). */
1471 scm_i_fill_input (SCM port
)
1473 scm_t_port
*pt
= SCM_PTAB_ENTRY (port
);
1474 scm_t_port_internal
*pti
= SCM_PORT_GET_INTERNAL (port
);
1476 assert (pt
->read_pos
== pt
->read_end
);
1478 if (pti
->pending_eof
)
1480 pti
->pending_eof
= 0;
1484 if (pt
->read_buf
== pt
->putback_buf
)
1486 /* finished reading put-back chars. */
1487 pt
->read_buf
= pt
->saved_read_buf
;
1488 pt
->read_pos
= pt
->saved_read_pos
;
1489 pt
->read_end
= pt
->saved_read_end
;
1490 pt
->read_buf_size
= pt
->saved_read_buf_size
;
1491 if (pt
->read_pos
< pt
->read_end
)
1492 return *(pt
->read_pos
);
1494 return scm_ptobs
[SCM_PTOBNUM (port
)].fill_input (port
);
1498 scm_fill_input (SCM port
)
1500 return scm_i_fill_input (port
);
1503 /* Slow-path fallback for 'scm_get_byte_or_eof' in inline.h */
1505 scm_slow_get_byte_or_eof (SCM port
)
1507 scm_t_port
*pt
= SCM_PTAB_ENTRY (port
);
1509 if (pt
->rw_active
== SCM_PORT_WRITE
)
1513 pt
->rw_active
= SCM_PORT_READ
;
1515 if (pt
->read_pos
>= pt
->read_end
)
1517 if (SCM_UNLIKELY (scm_i_fill_input (port
) == EOF
))
1521 return *pt
->read_pos
++;
1524 /* Slow-path fallback for 'scm_peek_byte_or_eof' in inline.h */
1526 scm_slow_peek_byte_or_eof (SCM port
)
1528 scm_t_port
*pt
= SCM_PTAB_ENTRY (port
);
1530 if (pt
->rw_active
== SCM_PORT_WRITE
)
1534 pt
->rw_active
= SCM_PORT_READ
;
1536 if (pt
->read_pos
>= pt
->read_end
)
1538 if (SCM_UNLIKELY (scm_i_fill_input (port
) == EOF
))
1540 scm_i_set_pending_eof (port
);
1545 return *pt
->read_pos
;
1551 * This function differs from scm_c_write; it updates port line and
1555 scm_lfwrite (const char *ptr
, size_t size
, SCM port
)
1557 scm_t_port
*pt
= SCM_PTAB_ENTRY (port
);
1558 scm_t_ptob_descriptor
*ptob
= &scm_ptobs
[SCM_PTOBNUM (port
)];
1560 if (pt
->rw_active
== SCM_PORT_READ
)
1561 scm_end_input (port
);
1563 ptob
->write (port
, ptr
, size
);
1565 for (; size
; ptr
++, size
--)
1566 update_port_lf ((scm_t_wchar
) (unsigned char) *ptr
, port
);
1569 pt
->rw_active
= SCM_PORT_WRITE
;
1572 /* Write STR to PORT from START inclusive to END exclusive. */
1574 scm_lfwrite_substr (SCM str
, size_t start
, size_t end
, SCM port
)
1576 scm_t_port
*pt
= SCM_PTAB_ENTRY (port
);
1578 if (pt
->rw_active
== SCM_PORT_READ
)
1579 scm_end_input (port
);
1581 if (end
== (size_t) -1)
1582 end
= scm_i_string_length (str
);
1584 scm_i_display_substring (str
, start
, end
, port
);
1587 pt
->rw_active
= SCM_PORT_WRITE
;
1592 * Used by an application to read arbitrary number of bytes from an
1593 * SCM port. Same semantics as libc read, except that scm_c_read only
1594 * returns less than SIZE bytes if at end-of-file.
1596 * Warning: Doesn't update port line and column counts! */
1598 /* This structure, and the following swap_buffer function, are used
1599 for temporarily swapping a port's own read buffer, and the buffer
1600 that the caller of scm_c_read provides. */
1601 struct port_and_swap_buffer
1604 unsigned char *buffer
;
1609 swap_buffer (void *data
)
1611 struct port_and_swap_buffer
*psb
= (struct port_and_swap_buffer
*) data
;
1612 unsigned char *old_buf
= psb
->pt
->read_buf
;
1613 size_t old_size
= psb
->pt
->read_buf_size
;
1615 /* Make the port use (buffer, size) from the struct. */
1616 psb
->pt
->read_pos
= psb
->pt
->read_buf
= psb
->pt
->read_end
= psb
->buffer
;
1617 psb
->pt
->read_buf_size
= psb
->size
;
1619 /* Save the port's old (buffer, size) in the struct. */
1620 psb
->buffer
= old_buf
;
1621 psb
->size
= old_size
;
1625 scm_c_read (SCM port
, void *buffer
, size_t size
)
1626 #define FUNC_NAME "scm_c_read"
1629 size_t n_read
= 0, n_available
;
1630 struct port_and_swap_buffer psb
;
1632 SCM_VALIDATE_OPINPORT (1, port
);
1634 pt
= SCM_PTAB_ENTRY (port
);
1635 if (pt
->rw_active
== SCM_PORT_WRITE
)
1636 scm_ptobs
[SCM_PTOBNUM (port
)].flush (port
);
1639 pt
->rw_active
= SCM_PORT_READ
;
1641 /* Take bytes first from the port's read buffer. */
1642 if (pt
->read_pos
< pt
->read_end
)
1644 n_available
= min (size
, pt
->read_end
- pt
->read_pos
);
1645 memcpy (buffer
, pt
->read_pos
, n_available
);
1646 buffer
= (char *) buffer
+ n_available
;
1647 pt
->read_pos
+= n_available
;
1648 n_read
+= n_available
;
1649 size
-= n_available
;
1652 /* Avoid the scm_dynwind_* costs if we now have enough data. */
1656 /* Now we will call scm_i_fill_input repeatedly until we have read the
1657 requested number of bytes. (Note that a single scm_i_fill_input
1658 call does not guarantee to fill the whole of the port's read
1660 if (pt
->read_buf_size
<= 1 &&
1661 (pt
->encoding
== NULL
1662 || c_strcasecmp (pt
->encoding
, "ISO-8859-1") == 0))
1664 /* The port that we are reading from is unbuffered - i.e. does
1665 not have its own persistent buffer - but we have a buffer,
1666 provided by our caller, that is the right size for the data
1667 that is wanted. For the following scm_i_fill_input calls,
1668 therefore, we use the buffer in hand as the port's read
1671 We need to make sure that the port's normal (1 byte) buffer
1672 is reinstated in case one of the scm_i_fill_input () calls
1673 throws an exception; we use the scm_dynwind_* API to achieve
1676 A consequence of this optimization is that the fill_input
1677 functions can't unget characters. That'll push data to the
1678 pushback buffer instead of this psb buffer. */
1680 unsigned char *pback
= pt
->putback_buf
;
1683 psb
.buffer
= buffer
;
1685 scm_dynwind_begin (SCM_F_DYNWIND_REWINDABLE
);
1686 scm_dynwind_rewind_handler (swap_buffer
, &psb
, SCM_F_WIND_EXPLICITLY
);
1687 scm_dynwind_unwind_handler (swap_buffer
, &psb
, SCM_F_WIND_EXPLICITLY
);
1689 /* Call scm_i_fill_input until we have all the bytes that we need,
1691 while (pt
->read_buf_size
&& (scm_i_fill_input (port
) != EOF
))
1693 pt
->read_buf_size
-= (pt
->read_end
- pt
->read_pos
);
1694 pt
->read_pos
= pt
->read_buf
= pt
->read_end
;
1697 if (pback
!= pt
->putback_buf
1698 || pt
->read_buf
- (unsigned char *) buffer
< 0)
1699 scm_misc_error (FUNC_NAME
,
1700 "scm_c_read must not call a fill function that pushes "
1701 "back characters onto an unbuffered port", SCM_EOL
);
1703 n_read
+= pt
->read_buf
- (unsigned char *) buffer
;
1705 /* Reinstate the port's normal buffer. */
1710 /* The port has its own buffer. It is important that we use it,
1711 even if it happens to be smaller than our caller's buffer, so
1712 that a custom port implementation's entry points (in
1713 particular, fill_input) can rely on the buffer always being
1714 the same as they first set up. */
1715 while (size
&& (scm_i_fill_input (port
) != EOF
))
1717 n_available
= min (size
, pt
->read_end
- pt
->read_pos
);
1718 memcpy (buffer
, pt
->read_pos
, n_available
);
1719 buffer
= (char *) buffer
+ n_available
;
1720 pt
->read_pos
+= n_available
;
1721 n_read
+= n_available
;
1722 size
-= n_available
;
1732 * Used by an application to write arbitrary number of bytes to an SCM
1733 * port. Similar semantics as libc write. However, unlike libc
1734 * write, scm_c_write writes the requested number of bytes and has no
1737 * Warning: Doesn't update port line and column counts!
1741 scm_c_write (SCM port
, const void *ptr
, size_t size
)
1742 #define FUNC_NAME "scm_c_write"
1745 scm_t_ptob_descriptor
*ptob
;
1747 SCM_VALIDATE_OPOUTPORT (1, port
);
1749 pt
= SCM_PTAB_ENTRY (port
);
1750 ptob
= &scm_ptobs
[SCM_PTOBNUM (port
)];
1752 if (pt
->rw_active
== SCM_PORT_READ
)
1753 scm_end_input (port
);
1755 ptob
->write (port
, ptr
, size
);
1758 pt
->rw_active
= SCM_PORT_WRITE
;
1763 scm_flush (SCM port
)
1765 long i
= SCM_PTOBNUM (port
);
1767 (scm_ptobs
[i
].flush
) (port
);
1771 scm_end_input (SCM port
)
1774 scm_t_port
*pt
= SCM_PTAB_ENTRY (port
);
1776 scm_i_clear_pending_eof (port
);
1777 if (pt
->read_buf
== pt
->putback_buf
)
1779 offset
= pt
->read_end
- pt
->read_pos
;
1780 pt
->read_buf
= pt
->saved_read_buf
;
1781 pt
->read_pos
= pt
->saved_read_pos
;
1782 pt
->read_end
= pt
->saved_read_end
;
1783 pt
->read_buf_size
= pt
->saved_read_buf_size
;
1788 scm_ptobs
[SCM_PTOBNUM (port
)].end_input (port
, offset
);
1795 scm_i_unget_bytes (const unsigned char *buf
, size_t len
, SCM port
)
1796 #define FUNC_NAME "scm_unget_bytes"
1798 scm_t_port
*pt
= SCM_PTAB_ENTRY (port
);
1799 size_t old_len
, new_len
;
1801 scm_i_clear_pending_eof (port
);
1803 if (pt
->read_buf
!= pt
->putback_buf
)
1804 /* switch to the put-back buffer. */
1806 if (pt
->putback_buf
== NULL
)
1808 pt
->putback_buf_size
= (len
> SCM_INITIAL_PUTBACK_BUF_SIZE
1809 ? len
: SCM_INITIAL_PUTBACK_BUF_SIZE
);
1811 = (unsigned char *) scm_gc_malloc_pointerless
1812 (pt
->putback_buf_size
, "putback buffer");
1815 pt
->saved_read_buf
= pt
->read_buf
;
1816 pt
->saved_read_pos
= pt
->read_pos
;
1817 pt
->saved_read_end
= pt
->read_end
;
1818 pt
->saved_read_buf_size
= pt
->read_buf_size
;
1820 /* Put read_pos at the end of the buffer, so that ungets will not
1821 have to shift the buffer contents each time. */
1822 pt
->read_buf
= pt
->putback_buf
;
1823 pt
->read_pos
= pt
->read_end
= pt
->putback_buf
+ pt
->putback_buf_size
;
1824 pt
->read_buf_size
= pt
->putback_buf_size
;
1827 old_len
= pt
->read_end
- pt
->read_pos
;
1828 new_len
= old_len
+ len
;
1830 if (new_len
> pt
->read_buf_size
)
1831 /* The putback buffer needs to be enlarged. */
1833 size_t new_buf_size
;
1834 unsigned char *new_buf
, *new_end
, *new_pos
;
1836 new_buf_size
= pt
->read_buf_size
* 2;
1837 if (new_buf_size
< new_len
)
1838 new_buf_size
= new_len
;
1840 new_buf
= (unsigned char *)
1841 scm_gc_malloc_pointerless (new_buf_size
, "putback buffer");
1843 /* Put the bytes at the end of the buffer, so that future
1844 ungets won't need to shift the buffer. */
1845 new_end
= new_buf
+ new_buf_size
;
1846 new_pos
= new_end
- old_len
;
1847 memcpy (new_pos
, pt
->read_pos
, old_len
);
1849 pt
->read_buf
= pt
->putback_buf
= new_buf
;
1850 pt
->read_pos
= new_pos
;
1851 pt
->read_end
= new_end
;
1852 pt
->read_buf_size
= pt
->putback_buf_size
= new_buf_size
;
1854 else if (pt
->read_buf
+ len
< pt
->read_pos
)
1855 /* If needed, shift the existing buffer contents up.
1856 This should not happen unless some external code
1857 manipulates the putback buffer pointers. */
1859 unsigned char *new_end
= pt
->read_buf
+ pt
->read_buf_size
;
1860 unsigned char *new_pos
= new_end
- old_len
;
1862 memmove (new_pos
, pt
->read_pos
, old_len
);
1863 pt
->read_pos
= new_pos
;
1864 pt
->read_end
= new_end
;
1867 /* Move read_pos back and copy the bytes there. */
1868 pt
->read_pos
-= len
;
1869 memcpy (pt
->read_buf
+ (pt
->read_pos
- pt
->read_buf
), buf
, len
);
1871 if (pt
->rw_active
== SCM_PORT_WRITE
)
1875 pt
->rw_active
= SCM_PORT_READ
;
1880 scm_unget_bytes (const unsigned char *buf
, size_t len
, SCM port
)
1882 scm_i_unget_bytes (buf
, len
, port
);
1886 scm_unget_byte (int c
, SCM port
)
1891 scm_i_unget_bytes (&byte
, 1, port
);
1895 scm_ungetc (scm_t_wchar c
, SCM port
)
1896 #define FUNC_NAME "scm_ungetc"
1898 scm_t_port
*pt
= SCM_PTAB_ENTRY (port
);
1900 char result_buf
[10];
1901 const char *encoding
;
1904 if (pt
->encoding
!= NULL
)
1905 encoding
= pt
->encoding
;
1907 encoding
= "ISO-8859-1";
1909 len
= sizeof (result_buf
);
1910 result
= u32_conv_to_encoding (encoding
,
1911 (enum iconv_ilseq_handler
) pt
->ilseq_handler
,
1912 (uint32_t *) &c
, 1, NULL
,
1915 if (SCM_UNLIKELY (result
== NULL
|| len
== 0))
1916 scm_encoding_error (FUNC_NAME
, errno
,
1917 "conversion to port encoding failed",
1918 SCM_BOOL_F
, SCM_MAKE_CHAR (c
));
1920 scm_i_unget_bytes ((unsigned char *) result
, len
, port
);
1922 if (SCM_UNLIKELY (result
!= result_buf
))
1927 /* What should col be in this case?
1928 * We'll leave it at -1.
1930 SCM_LINUM (port
) -= 1;
1939 scm_ungets (const char *s
, int n
, SCM port
)
1941 /* This is simple minded and inefficient, but unreading strings is
1942 * probably not a common operation, and remember that line and
1943 * column numbers have to be handled...
1945 * Please feel free to write an optimized version!
1948 scm_ungetc (s
[n
], port
);
1952 SCM_DEFINE (scm_peek_char
, "peek-char", 0, 1, 0,
1954 "Return the next character available from @var{port},\n"
1955 "@emph{without} updating @var{port} to point to the following\n"
1956 "character. If no more characters are available, the\n"
1957 "end-of-file object is returned.\n"
1959 "The value returned by\n"
1960 "a call to @code{peek-char} is the same as the value that would\n"
1961 "have been returned by a call to @code{read-char} on the same\n"
1962 "port. The only difference is that the very next call to\n"
1963 "@code{read-char} or @code{peek-char} on that @var{port} will\n"
1964 "return the value returned by the preceding call to\n"
1965 "@code{peek-char}. In particular, a call to @code{peek-char} on\n"
1966 "an interactive port will hang waiting for input whenever a call\n"
1967 "to @code{read-char} would have hung.\n"
1969 "As for @code{read-char}, a @code{decoding-error} may be raised\n"
1970 "if such a situation occurs. However, unlike with @code{read-char},\n"
1971 "@var{port} still points at the beginning of the erroneous byte\n"
1972 "sequence when the error is raised.\n")
1973 #define FUNC_NAME s_scm_peek_char
1978 char bytes
[SCM_MBCHAR_BUF_SIZE
];
1982 if (SCM_UNBNDP (port
))
1983 port
= scm_current_input_port ();
1984 SCM_VALIDATE_OPINPORT (1, port
);
1986 column
= SCM_COL (port
);
1987 line
= SCM_LINUM (port
);
1989 err
= get_codepoint (port
, &c
, bytes
, &len
);
1991 scm_i_unget_bytes ((unsigned char *) bytes
, len
, port
);
1993 SCM_COL (port
) = column
;
1994 SCM_LINUM (port
) = line
;
1996 if (SCM_UNLIKELY (err
!= 0))
1998 scm_decoding_error (FUNC_NAME
, err
, "input decoding error", port
);
2000 /* Shouldn't happen since `catch' always aborts to prompt. */
2001 result
= SCM_BOOL_F
;
2005 scm_i_set_pending_eof (port
);
2006 result
= SCM_EOF_VAL
;
2009 result
= SCM_MAKE_CHAR (c
);
2015 SCM_DEFINE (scm_unread_char
, "unread-char", 1, 1, 0,
2016 (SCM cobj
, SCM port
),
2017 "Place character @var{cobj} in @var{port} so that it will be\n"
2018 "read by the next read operation. If called multiple times, the\n"
2019 "unread characters will be read again in last-in first-out\n"
2020 "order. If @var{port} is not supplied, the current input port\n"
2022 #define FUNC_NAME s_scm_unread_char
2026 SCM_VALIDATE_CHAR (1, cobj
);
2027 if (SCM_UNBNDP (port
))
2028 port
= scm_current_input_port ();
2029 SCM_VALIDATE_OPINPORT (2, port
);
2031 c
= SCM_CHAR (cobj
);
2033 scm_ungetc (c
, port
);
2038 SCM_DEFINE (scm_unread_string
, "unread-string", 2, 0, 0,
2039 (SCM str
, SCM port
),
2040 "Place the string @var{str} in @var{port} so that its characters will be\n"
2041 "read in subsequent read operations. If called multiple times, the\n"
2042 "unread characters will be read again in last-in first-out order. If\n"
2043 "@var{port} is not supplied, the current-input-port is used.")
2044 #define FUNC_NAME s_scm_unread_string
2047 SCM_VALIDATE_STRING (1, str
);
2048 if (SCM_UNBNDP (port
))
2049 port
= scm_current_input_port ();
2050 SCM_VALIDATE_OPINPORT (2, port
);
2052 n
= scm_i_string_length (str
);
2055 scm_ungetc (scm_i_string_ref (str
, n
), port
);
2061 SCM_DEFINE (scm_seek
, "seek", 3, 0, 0,
2062 (SCM fd_port
, SCM offset
, SCM whence
),
2063 "Sets the current position of @var{fd_port} to the integer\n"
2064 "@var{offset}, which is interpreted according to the value of\n"
2067 "One of the following variables should be supplied for\n"
2069 "@defvar SEEK_SET\n"
2070 "Seek from the beginning of the file.\n"
2072 "@defvar SEEK_CUR\n"
2073 "Seek from the current position.\n"
2075 "@defvar SEEK_END\n"
2076 "Seek from the end of the file.\n"
2078 "If @var{fd_port} is a file descriptor, the underlying system\n"
2079 "call is @code{lseek}. @var{port} may be a string port.\n"
2081 "The value returned is the new position in the file. This means\n"
2082 "that the current position of a port can be obtained using:\n"
2084 "(seek port 0 SEEK_CUR)\n"
2086 #define FUNC_NAME s_scm_seek
2090 fd_port
= SCM_COERCE_OUTPORT (fd_port
);
2092 how
= scm_to_int (whence
);
2093 if (how
!= SEEK_SET
&& how
!= SEEK_CUR
&& how
!= SEEK_END
)
2094 SCM_OUT_OF_RANGE (3, whence
);
2096 if (SCM_OPPORTP (fd_port
))
2098 scm_t_port_internal
*pti
= SCM_PORT_GET_INTERNAL (fd_port
);
2099 scm_t_ptob_descriptor
*ptob
= scm_ptobs
+ SCM_PTOBNUM (fd_port
);
2100 off_t_or_off64_t off
= scm_to_off_t_or_off64_t (offset
);
2101 off_t_or_off64_t rv
;
2104 SCM_MISC_ERROR ("port is not seekable",
2105 scm_cons (fd_port
, SCM_EOL
));
2107 rv
= ptob
->seek (fd_port
, off
, how
);
2109 /* Set stream-start flags according to new position. */
2110 pti
->at_stream_start_for_bom_read
= (rv
== 0);
2111 pti
->at_stream_start_for_bom_write
= (rv
== 0);
2113 scm_i_clear_pending_eof (fd_port
);
2115 return scm_from_off_t_or_off64_t (rv
);
2117 else /* file descriptor?. */
2119 off_t_or_off64_t off
= scm_to_off_t_or_off64_t (offset
);
2120 off_t_or_off64_t rv
;
2121 rv
= lseek_or_lseek64 (scm_to_int (fd_port
), off
, how
);
2124 return scm_from_off_t_or_off64_t (rv
);
2133 /* Mingw has ftruncate(), perhaps implemented above using chsize, but
2134 doesn't have the filename version truncate(), hence this code. */
2135 #if HAVE_FTRUNCATE && ! HAVE_TRUNCATE
2137 truncate (const char *file
, off_t length
)
2141 fdes
= open (file
, O_BINARY
| O_WRONLY
);
2145 ret
= ftruncate (fdes
, length
);
2148 int save_errno
= errno
;
2154 return close (fdes
);
2156 #endif /* HAVE_FTRUNCATE && ! HAVE_TRUNCATE */
2158 SCM_DEFINE (scm_truncate_file
, "truncate-file", 1, 1, 0,
2159 (SCM object
, SCM length
),
2160 "Truncate file @var{object} to @var{length} bytes. @var{object}\n"
2161 "can be a filename string, a port object, or an integer file\n"
2163 "The return value is unspecified.\n"
2165 "For a port or file descriptor @var{length} can be omitted, in\n"
2166 "which case the file is truncated at the current position (per\n"
2167 "@code{ftell} above).\n"
2169 "On most systems a file can be extended by giving a length\n"
2170 "greater than the current size, but this is not mandatory in the\n"
2172 #define FUNC_NAME s_scm_truncate_file
2176 /* "object" can be a port, fdes or filename.
2178 Negative "length" makes no sense, but it's left to truncate() or
2179 ftruncate() to give back an error for that (normally EINVAL).
2182 if (SCM_UNBNDP (length
))
2184 /* must supply length if object is a filename. */
2185 if (scm_is_string (object
))
2186 SCM_MISC_ERROR("must supply length if OBJECT is a filename", SCM_EOL
);
2188 length
= scm_seek (object
, SCM_INUM0
, scm_from_int (SEEK_CUR
));
2191 object
= SCM_COERCE_OUTPORT (object
);
2192 if (scm_is_integer (object
))
2194 off_t_or_off64_t c_length
= scm_to_off_t_or_off64_t (length
);
2195 SCM_SYSCALL (rv
= ftruncate_or_ftruncate64 (scm_to_int (object
),
2198 else if (SCM_OPOUTPORTP (object
))
2200 off_t_or_off64_t c_length
= scm_to_off_t_or_off64_t (length
);
2201 scm_t_port
*pt
= SCM_PTAB_ENTRY (object
);
2202 scm_t_ptob_descriptor
*ptob
= scm_ptobs
+ SCM_PTOBNUM (object
);
2204 if (!ptob
->truncate
)
2205 SCM_MISC_ERROR ("port is not truncatable", SCM_EOL
);
2207 scm_i_clear_pending_eof (object
);
2208 if (pt
->rw_active
== SCM_PORT_READ
)
2209 scm_end_input (object
);
2210 else if (pt
->rw_active
== SCM_PORT_WRITE
)
2211 ptob
->flush (object
);
2213 ptob
->truncate (object
, c_length
);
2218 off_t_or_off64_t c_length
= scm_to_off_t_or_off64_t (length
);
2219 char *str
= scm_to_locale_string (object
);
2221 SCM_SYSCALL (rv
= truncate_or_truncate64 (str
, c_length
));
2228 return SCM_UNSPECIFIED
;
2232 SCM_DEFINE (scm_port_line
, "port-line", 1, 0, 0,
2234 "Return the current line number for @var{port}.\n"
2236 "The first line of a file is 0. But you might want to add 1\n"
2237 "when printing line numbers, since starting from 1 is\n"
2238 "traditional in error messages, and likely to be more natural to\n"
2240 #define FUNC_NAME s_scm_port_line
2242 port
= SCM_COERCE_OUTPORT (port
);
2243 SCM_VALIDATE_OPENPORT (1, port
);
2244 return scm_from_long (SCM_LINUM (port
));
2248 SCM_DEFINE (scm_set_port_line_x
, "set-port-line!", 2, 0, 0,
2249 (SCM port
, SCM line
),
2250 "Set the current line number for @var{port} to @var{line}. The\n"
2251 "first line of a file is 0.")
2252 #define FUNC_NAME s_scm_set_port_line_x
2254 port
= SCM_COERCE_OUTPORT (port
);
2255 SCM_VALIDATE_OPENPORT (1, port
);
2256 SCM_PTAB_ENTRY (port
)->line_number
= scm_to_long (line
);
2257 return SCM_UNSPECIFIED
;
2261 SCM_DEFINE (scm_port_column
, "port-column", 1, 0, 0,
2263 "Return the current column number of @var{port}.\n"
2264 "If the number is\n"
2265 "unknown, the result is #f. Otherwise, the result is a 0-origin integer\n"
2266 "- i.e. the first character of the first line is line 0, column 0.\n"
2267 "(However, when you display a file position, for example in an error\n"
2268 "message, we recommend you add 1 to get 1-origin integers. This is\n"
2269 "because lines and column numbers traditionally start with 1, and that is\n"
2270 "what non-programmers will find most natural.)")
2271 #define FUNC_NAME s_scm_port_column
2273 port
= SCM_COERCE_OUTPORT (port
);
2274 SCM_VALIDATE_OPENPORT (1, port
);
2275 return scm_from_int (SCM_COL (port
));
2279 SCM_DEFINE (scm_set_port_column_x
, "set-port-column!", 2, 0, 0,
2280 (SCM port
, SCM column
),
2281 "Set the current column of @var{port}. Before reading the first\n"
2282 "character on a line the column should be 0.")
2283 #define FUNC_NAME s_scm_set_port_column_x
2285 port
= SCM_COERCE_OUTPORT (port
);
2286 SCM_VALIDATE_OPENPORT (1, port
);
2287 SCM_PTAB_ENTRY (port
)->column_number
= scm_to_int (column
);
2288 return SCM_UNSPECIFIED
;
2292 SCM_DEFINE (scm_port_filename
, "port-filename", 1, 0, 0,
2294 "Return the filename associated with @var{port}, or @code{#f}\n"
2295 "if no filename is associated with the port.")
2296 #define FUNC_NAME s_scm_port_filename
2298 port
= SCM_COERCE_OUTPORT (port
);
2299 SCM_VALIDATE_OPENPORT (1, port
);
2300 return SCM_FILENAME (port
);
2304 SCM_DEFINE (scm_set_port_filename_x
, "set-port-filename!", 2, 0, 0,
2305 (SCM port
, SCM filename
),
2306 "Change the filename associated with @var{port}, using the current input\n"
2307 "port if none is specified. Note that this does not change the port's\n"
2308 "source of data, but only the value that is returned by\n"
2309 "@code{port-filename} and reported in diagnostic output.")
2310 #define FUNC_NAME s_scm_set_port_filename_x
2312 port
= SCM_COERCE_OUTPORT (port
);
2313 SCM_VALIDATE_OPENPORT (1, port
);
2314 /* We allow the user to set the filename to whatever he likes. */
2315 SCM_SET_FILENAME (port
, filename
);
2316 return SCM_UNSPECIFIED
;
2320 /* A fluid specifying the default encoding for newly created ports. If it is
2321 a string, that is the encoding. If it is #f, it is in the "native"
2322 (Latin-1) encoding. */
2323 SCM_VARIABLE (default_port_encoding_var
, "%default-port-encoding");
2325 static int scm_port_encoding_init
= 0;
2327 /* Use ENCODING as the default encoding for future ports. */
2329 scm_i_set_default_port_encoding (const char *encoding
)
2331 if (!scm_port_encoding_init
2332 || !scm_is_fluid (SCM_VARIABLE_REF (default_port_encoding_var
)))
2333 scm_misc_error (NULL
, "tried to set port encoding fluid before it is initialized",
2336 if (encoding
== NULL
2337 || c_strcasecmp (encoding
, "ASCII") == 0
2338 || c_strcasecmp (encoding
, "ANSI_X3.4-1968") == 0
2339 || c_strcasecmp (encoding
, "ISO-8859-1") == 0)
2340 scm_fluid_set_x (SCM_VARIABLE_REF (default_port_encoding_var
), SCM_BOOL_F
);
2342 scm_fluid_set_x (SCM_VARIABLE_REF (default_port_encoding_var
),
2343 scm_from_locale_string (encoding
));
2346 /* Return the name of the default encoding for newly created ports; a
2347 return value of NULL means "ISO-8859-1". */
2349 scm_i_default_port_encoding (void)
2351 if (!scm_port_encoding_init
)
2353 else if (!scm_is_fluid (SCM_VARIABLE_REF (default_port_encoding_var
)))
2359 encoding
= scm_fluid_ref (SCM_VARIABLE_REF (default_port_encoding_var
));
2360 if (!scm_is_string (encoding
))
2363 return scm_i_string_chars (encoding
);
2367 /* If the next LEN bytes from PORT are equal to those in BYTES, then
2368 return 1, else return 0. Leave the port position unchanged. */
2370 looking_at_bytes (SCM port
, const unsigned char *bytes
, int len
)
2372 scm_t_port
*pt
= SCM_PTAB_ENTRY (port
);
2375 while (i
< len
&& scm_peek_byte_or_eof (port
) == bytes
[i
])
2380 scm_i_unget_bytes (bytes
, i
, port
);
2384 static const unsigned char scm_utf8_bom
[3] = {0xEF, 0xBB, 0xBF};
2385 static const unsigned char scm_utf16be_bom
[2] = {0xFE, 0xFF};
2386 static const unsigned char scm_utf16le_bom
[2] = {0xFF, 0xFE};
2387 static const unsigned char scm_utf32be_bom
[4] = {0x00, 0x00, 0xFE, 0xFF};
2388 static const unsigned char scm_utf32le_bom
[4] = {0xFF, 0xFE, 0x00, 0x00};
2390 /* Decide what byte order to use for a UTF-16 port. Return "UTF-16BE"
2391 or "UTF-16LE". MODE must be either SCM_PORT_READ or SCM_PORT_WRITE,
2392 and specifies which operation is about to be done. The MODE
2393 determines how we will decide the byte order. We deliberately avoid
2394 reading from the port unless the user is about to do so. If the user
2395 is about to read, then we look for a BOM, and if present, we use it
2396 to determine the byte order. Otherwise we choose big endian, as
2397 recommended by the Unicode Standard. Note that the BOM (if any) is
2398 not consumed here. */
2400 decide_utf16_encoding (SCM port
, scm_t_port_rw_active mode
)
2402 if (mode
== SCM_PORT_READ
2403 && SCM_PORT_GET_INTERNAL (port
)->at_stream_start_for_bom_read
2404 && looking_at_bytes (port
, scm_utf16le_bom
, sizeof scm_utf16le_bom
))
2410 /* Decide what byte order to use for a UTF-32 port. Return "UTF-32BE"
2411 or "UTF-32LE". See the comment above 'decide_utf16_encoding' for
2414 decide_utf32_encoding (SCM port
, scm_t_port_rw_active mode
)
2416 if (mode
== SCM_PORT_READ
2417 && SCM_PORT_GET_INTERNAL (port
)->at_stream_start_for_bom_read
2418 && looking_at_bytes (port
, scm_utf32le_bom
, sizeof scm_utf32le_bom
))
2425 finalize_iconv_descriptors (void *ptr
, void *data
)
2427 close_iconv_descriptors (ptr
);
2430 static scm_t_iconv_descriptors
*
2431 open_iconv_descriptors (const char *encoding
, int reading
, int writing
)
2433 scm_t_iconv_descriptors
*id
;
2434 iconv_t input_cd
, output_cd
;
2436 input_cd
= (iconv_t
) -1;
2437 output_cd
= (iconv_t
) -1;
2440 /* Open an input iconv conversion descriptor, from ENCODING
2441 to UTF-8. We choose UTF-8, not UTF-32, because iconv
2442 implementations can typically convert from anything to
2443 UTF-8, but not to UTF-32 (see
2444 <http://lists.gnu.org/archive/html/bug-libunistring/2010-09/msg00007.html>). */
2446 /* Assume opening an iconv descriptor causes about 16 KB of
2448 scm_gc_register_allocation (16 * 1024);
2450 input_cd
= iconv_open ("UTF-8", encoding
);
2451 if (input_cd
== (iconv_t
) -1)
2452 goto invalid_encoding
;
2457 /* Assume opening an iconv descriptor causes about 16 KB of
2459 scm_gc_register_allocation (16 * 1024);
2461 output_cd
= iconv_open (encoding
, "UTF-8");
2462 if (output_cd
== (iconv_t
) -1)
2464 if (input_cd
!= (iconv_t
) -1)
2465 iconv_close (input_cd
);
2466 goto invalid_encoding
;
2470 id
= scm_gc_malloc_pointerless (sizeof (*id
), "iconv descriptors");
2471 id
->input_cd
= input_cd
;
2472 id
->output_cd
= output_cd
;
2474 /* Register a finalizer to close the descriptors. */
2475 scm_i_set_finalizer (id
, finalize_iconv_descriptors
, NULL
);
2482 err
= scm_from_locale_string (encoding
);
2483 scm_misc_error ("open_iconv_descriptors",
2484 "invalid or unknown character encoding ~s",
2490 close_iconv_descriptors (scm_t_iconv_descriptors
*id
)
2492 if (id
->input_cd
!= (iconv_t
) -1)
2493 iconv_close (id
->input_cd
);
2494 if (id
->output_cd
!= (iconv_t
) -1)
2495 iconv_close (id
->output_cd
);
2496 id
->input_cd
= (void *) -1;
2497 id
->output_cd
= (void *) -1;
2500 /* Return the iconv_descriptors, initializing them if necessary. MODE
2501 must be either SCM_PORT_READ or SCM_PORT_WRITE, and specifies which
2502 operation is about to be done. We deliberately avoid reading from
2503 the port unless the user was about to do so. */
2504 scm_t_iconv_descriptors
*
2505 scm_i_port_iconv_descriptors (SCM port
, scm_t_port_rw_active mode
)
2507 scm_t_port_internal
*pti
= SCM_PORT_GET_INTERNAL (port
);
2509 assert (pti
->encoding_mode
== SCM_PORT_ENCODING_MODE_ICONV
);
2511 if (!pti
->iconv_descriptors
)
2513 scm_t_port
*pt
= SCM_PTAB_ENTRY (port
);
2514 const char *precise_encoding
;
2517 pt
->encoding
= "ISO-8859-1";
2519 /* If the specified encoding is UTF-16 or UTF-32, then make
2520 that more precise by deciding what byte order to use. */
2521 if (c_strcasecmp (pt
->encoding
, "UTF-16") == 0)
2522 precise_encoding
= decide_utf16_encoding (port
, mode
);
2523 else if (c_strcasecmp (pt
->encoding
, "UTF-32") == 0)
2524 precise_encoding
= decide_utf32_encoding (port
, mode
);
2526 precise_encoding
= pt
->encoding
;
2528 pti
->iconv_descriptors
=
2529 open_iconv_descriptors (precise_encoding
,
2530 SCM_INPUT_PORT_P (port
),
2531 SCM_OUTPUT_PORT_P (port
));
2534 return pti
->iconv_descriptors
;
2538 scm_i_set_port_encoding_x (SCM port
, const char *encoding
)
2541 scm_t_port_internal
*pti
;
2542 scm_t_iconv_descriptors
*prev
;
2544 /* Set the character encoding for this port. */
2545 pt
= SCM_PTAB_ENTRY (port
);
2546 pti
= SCM_PORT_GET_INTERNAL (port
);
2547 prev
= pti
->iconv_descriptors
;
2549 /* In order to handle cases where the encoding changes mid-stream
2550 (e.g. within an HTTP stream, or within a file that is composed of
2551 segments with different encodings), we consider this to be "stream
2552 start" for purposes of BOM handling, regardless of our actual file
2554 pti
->at_stream_start_for_bom_read
= 1;
2555 pti
->at_stream_start_for_bom_write
= 1;
2557 if (encoding
== NULL
)
2558 encoding
= "ISO-8859-1";
2560 /* If ENCODING is UTF-8, then no conversion descriptor is opened
2561 because we do I/O ourselves. This saves 100+ KiB for each
2563 pt
->encoding
= scm_gc_strdup (encoding
, "port");
2564 if (c_strcasecmp (encoding
, "UTF-8") == 0)
2565 pti
->encoding_mode
= SCM_PORT_ENCODING_MODE_UTF8
;
2567 pti
->encoding_mode
= SCM_PORT_ENCODING_MODE_ICONV
;
2569 pti
->iconv_descriptors
= NULL
;
2571 close_iconv_descriptors (prev
);
2574 SCM_DEFINE (scm_port_encoding
, "port-encoding", 1, 0, 0,
2576 "Returns, as a string, the character encoding that @var{port}\n"
2577 "uses to interpret its input and output.\n")
2578 #define FUNC_NAME s_scm_port_encoding
2583 SCM_VALIDATE_PORT (1, port
);
2585 pt
= SCM_PTAB_ENTRY (port
);
2588 return scm_from_locale_string (pt
->encoding
);
2594 SCM_DEFINE (scm_set_port_encoding_x
, "set-port-encoding!", 2, 0, 0,
2595 (SCM port
, SCM enc
),
2596 "Sets the character encoding that will be used to interpret all\n"
2597 "port I/O. New ports are created with the encoding\n"
2598 "appropriate for the current locale if @code{setlocale} has \n"
2599 "been called or ISO-8859-1 otherwise\n"
2600 "and this procedure can be used to modify that encoding.\n")
2601 #define FUNC_NAME s_scm_set_port_encoding_x
2605 SCM_VALIDATE_PORT (1, port
);
2606 SCM_VALIDATE_STRING (2, enc
);
2608 enc_str
= scm_to_locale_string (enc
);
2609 scm_i_set_port_encoding_x (port
, enc_str
);
2612 return SCM_UNSPECIFIED
;
2617 /* A fluid specifying the default conversion handler for newly created
2618 ports. Its value should be one of the symbols below. */
2619 SCM_VARIABLE (default_conversion_strategy_var
,
2620 "%default-port-conversion-strategy");
2622 /* Whether the above fluid is initialized. */
2623 static int scm_conversion_strategy_init
= 0;
2625 /* The possible conversion strategies. */
2626 SCM_SYMBOL (sym_error
, "error");
2627 SCM_SYMBOL (sym_substitute
, "substitute");
2628 SCM_SYMBOL (sym_escape
, "escape");
2630 /* Return the default failed encoding conversion policy for new created
2632 scm_t_string_failed_conversion_handler
2633 scm_i_default_port_conversion_handler (void)
2635 scm_t_string_failed_conversion_handler handler
;
2637 if (!scm_conversion_strategy_init
2638 || !scm_is_fluid (SCM_VARIABLE_REF (default_conversion_strategy_var
)))
2639 handler
= SCM_FAILED_CONVERSION_QUESTION_MARK
;
2644 fluid
= SCM_VARIABLE_REF (default_conversion_strategy_var
);
2645 value
= scm_fluid_ref (fluid
);
2647 if (scm_is_eq (sym_substitute
, value
))
2648 handler
= SCM_FAILED_CONVERSION_QUESTION_MARK
;
2649 else if (scm_is_eq (sym_escape
, value
))
2650 handler
= SCM_FAILED_CONVERSION_ESCAPE_SEQUENCE
;
2652 /* Default to 'error also when the fluid's value is not one of
2653 the valid symbols. */
2654 handler
= SCM_FAILED_CONVERSION_ERROR
;
2660 /* Use HANDLER as the default conversion strategy for future ports. */
2662 scm_i_set_default_port_conversion_handler (scm_t_string_failed_conversion_handler
2667 if (!scm_conversion_strategy_init
2668 || !scm_is_fluid (SCM_VARIABLE_REF (default_conversion_strategy_var
)))
2669 scm_misc_error (NULL
, "tried to set conversion strategy fluid before it is initialized",
2674 case SCM_FAILED_CONVERSION_ERROR
:
2675 strategy
= sym_error
;
2678 case SCM_FAILED_CONVERSION_ESCAPE_SEQUENCE
:
2679 strategy
= sym_escape
;
2682 case SCM_FAILED_CONVERSION_QUESTION_MARK
:
2683 strategy
= sym_substitute
;
2690 scm_fluid_set_x (SCM_VARIABLE_REF (default_conversion_strategy_var
),
2694 SCM_DEFINE (scm_port_conversion_strategy
, "port-conversion-strategy",
2695 1, 0, 0, (SCM port
),
2696 "Returns the behavior of the port when handling a character that\n"
2697 "is not representable in the port's current encoding.\n"
2698 "It returns the symbol @code{error} if unrepresentable characters\n"
2699 "should cause exceptions, @code{substitute} if the port should\n"
2700 "try to replace unrepresentable characters with question marks or\n"
2701 "approximate characters, or @code{escape} if unrepresentable\n"
2702 "characters should be converted to string escapes.\n"
2704 "If @var{port} is @code{#f}, then the current default behavior\n"
2705 "will be returned. New ports will have this default behavior\n"
2706 "when they are created.\n")
2707 #define FUNC_NAME s_scm_port_conversion_strategy
2709 scm_t_string_failed_conversion_handler h
;
2711 if (scm_is_false (port
))
2712 h
= scm_i_default_port_conversion_handler ();
2717 SCM_VALIDATE_OPPORT (1, port
);
2718 pt
= SCM_PTAB_ENTRY (port
);
2720 h
= pt
->ilseq_handler
;
2723 if (h
== SCM_FAILED_CONVERSION_ERROR
)
2724 return scm_from_latin1_symbol ("error");
2725 else if (h
== SCM_FAILED_CONVERSION_QUESTION_MARK
)
2726 return scm_from_latin1_symbol ("substitute");
2727 else if (h
== SCM_FAILED_CONVERSION_ESCAPE_SEQUENCE
)
2728 return scm_from_latin1_symbol ("escape");
2732 /* Never gets here. */
2733 return SCM_UNDEFINED
;
2737 SCM_DEFINE (scm_set_port_conversion_strategy_x
, "set-port-conversion-strategy!",
2739 (SCM port
, SCM sym
),
2740 "Sets the behavior of the interpreter when outputting a character\n"
2741 "that is not representable in the port's current encoding.\n"
2742 "@var{sym} can be either @code{'error}, @code{'substitute}, or\n"
2743 "@code{'escape}. If it is @code{'error}, an error will be thrown\n"
2744 "when an unconvertible character is encountered. If it is\n"
2745 "@code{'substitute}, then unconvertible characters will \n"
2746 "be replaced with approximate characters, or with question marks\n"
2747 "if no approximately correct character is available.\n"
2748 "If it is @code{'escape},\n"
2749 "it will appear as a hex escape when output.\n"
2751 "If @var{port} is an open port, the conversion error behavior\n"
2752 "is set for that port. If it is @code{#f}, it is set as the\n"
2753 "default behavior for any future ports that get created in\n"
2755 #define FUNC_NAME s_scm_set_port_conversion_strategy_x
2757 scm_t_string_failed_conversion_handler handler
;
2759 if (scm_is_eq (sym
, sym_error
))
2760 handler
= SCM_FAILED_CONVERSION_ERROR
;
2761 else if (scm_is_eq (sym
, sym_substitute
))
2762 handler
= SCM_FAILED_CONVERSION_QUESTION_MARK
;
2763 else if (scm_is_eq (sym
, sym_escape
))
2764 handler
= SCM_FAILED_CONVERSION_ESCAPE_SEQUENCE
;
2766 SCM_MISC_ERROR ("unknown conversion strategy ~s", scm_list_1 (sym
));
2768 if (scm_is_false (port
))
2769 scm_i_set_default_port_conversion_handler (handler
);
2772 SCM_VALIDATE_OPPORT (1, port
);
2773 SCM_PTAB_ENTRY (port
)->ilseq_handler
= handler
;
2776 return SCM_UNSPECIFIED
;
2783 scm_print_port_mode (SCM exp
, SCM port
)
2785 scm_puts (SCM_CLOSEDP (exp
)
2787 : (SCM_RDNG
& SCM_CELL_WORD_0 (exp
)
2788 ? (SCM_WRTNG
& SCM_CELL_WORD_0 (exp
)
2791 : (SCM_WRTNG
& SCM_CELL_WORD_0 (exp
)
2798 scm_port_print (SCM exp
, SCM port
, scm_print_state
*pstate SCM_UNUSED
)
2800 char *type
= SCM_PTOBNAME (SCM_PTOBNUM (exp
));
2803 scm_puts ("#<", port
);
2804 scm_print_port_mode (exp
, port
);
2805 scm_puts (type
, port
);
2806 scm_putc (' ', port
);
2807 scm_uintprint (SCM_CELL_WORD_1 (exp
), 16, port
);
2808 scm_putc ('>', port
);
2816 scm_t_bits scm_tc16_void_port
= 0;
2818 static int fill_input_void_port (SCM port SCM_UNUSED
)
2824 write_void_port (SCM port SCM_UNUSED
,
2825 const void *data SCM_UNUSED
,
2826 size_t size SCM_UNUSED
)
2831 scm_i_void_port (long mode_bits
)
2833 scm_i_scm_pthread_mutex_lock (&scm_i_port_table_mutex
);
2835 SCM answer
= scm_new_port_table_entry (scm_tc16_void_port
);
2836 scm_t_port
* pt
= SCM_PTAB_ENTRY(answer
);
2838 scm_port_non_buffer (pt
);
2840 SCM_SETSTREAM (answer
, 0);
2841 SCM_SET_CELL_TYPE (answer
, scm_tc16_void_port
| mode_bits
);
2842 scm_i_pthread_mutex_unlock (&scm_i_port_table_mutex
);
2848 scm_void_port (char *mode_str
)
2850 return scm_i_void_port (scm_mode_bits (mode_str
));
2853 SCM_DEFINE (scm_sys_make_void_port
, "%make-void-port", 1, 0, 0,
2855 "Create and return a new void port. A void port acts like\n"
2856 "@file{/dev/null}. The @var{mode} argument\n"
2857 "specifies the input/output modes for this port: see the\n"
2858 "documentation for @code{open-file} in @ref{File Ports}.")
2859 #define FUNC_NAME s_scm_sys_make_void_port
2861 return scm_i_void_port (scm_i_mode_bits (mode
));
2866 /* Initialization. */
2871 /* lseek() symbols. */
2872 scm_c_define ("SEEK_SET", scm_from_int (SEEK_SET
));
2873 scm_c_define ("SEEK_CUR", scm_from_int (SEEK_CUR
));
2874 scm_c_define ("SEEK_END", scm_from_int (SEEK_END
));
2876 scm_tc16_void_port
= scm_make_port_type ("void", fill_input_void_port
,
2879 cur_inport_fluid
= scm_make_fluid ();
2880 cur_outport_fluid
= scm_make_fluid ();
2881 cur_errport_fluid
= scm_make_fluid ();
2882 cur_loadport_fluid
= scm_make_fluid ();
2884 scm_i_port_weak_hash
= scm_make_weak_key_hash_table (SCM_I_MAKINUM(31));
2886 #include "libguile/ports.x"
2888 /* Use Latin-1 as the default port encoding. */
2889 SCM_VARIABLE_SET (default_port_encoding_var
,
2890 scm_make_fluid_with_default (SCM_BOOL_F
));
2891 scm_port_encoding_init
= 1;
2893 SCM_VARIABLE_SET (default_conversion_strategy_var
,
2894 scm_make_fluid_with_default (sym_substitute
));
2895 scm_conversion_strategy_init
= 1;
2897 /* These bindings are used when boot-9 turns `current-input-port' et
2898 al into parameters. They are then removed from the guile module. */
2899 scm_c_define ("%current-input-port-fluid", cur_inport_fluid
);
2900 scm_c_define ("%current-output-port-fluid", cur_outport_fluid
);
2901 scm_c_define ("%current-error-port-fluid", cur_errport_fluid
);