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 && pt
->encoding
== NULL
)
1662 /* The port that we are reading from is unbuffered - i.e. does
1663 not have its own persistent buffer - but we have a buffer,
1664 provided by our caller, that is the right size for the data
1665 that is wanted. For the following scm_i_fill_input calls,
1666 therefore, we use the buffer in hand as the port's read
1669 We need to make sure that the port's normal (1 byte) buffer
1670 is reinstated in case one of the scm_i_fill_input () calls
1671 throws an exception; we use the scm_dynwind_* API to achieve
1674 A consequence of this optimization is that the fill_input
1675 functions can't unget characters. That'll push data to the
1676 pushback buffer instead of this psb buffer. */
1678 unsigned char *pback
= pt
->putback_buf
;
1681 psb
.buffer
= buffer
;
1683 scm_dynwind_begin (SCM_F_DYNWIND_REWINDABLE
);
1684 scm_dynwind_rewind_handler (swap_buffer
, &psb
, SCM_F_WIND_EXPLICITLY
);
1685 scm_dynwind_unwind_handler (swap_buffer
, &psb
, SCM_F_WIND_EXPLICITLY
);
1687 /* Call scm_i_fill_input until we have all the bytes that we need,
1689 while (pt
->read_buf_size
&& (scm_i_fill_input (port
) != EOF
))
1691 pt
->read_buf_size
-= (pt
->read_end
- pt
->read_pos
);
1692 pt
->read_pos
= pt
->read_buf
= pt
->read_end
;
1695 if (pback
!= pt
->putback_buf
1696 || pt
->read_buf
- (unsigned char *) buffer
< 0)
1697 scm_misc_error (FUNC_NAME
,
1698 "scm_c_read must not call a fill function that pushes "
1699 "back characters onto an unbuffered port", SCM_EOL
);
1701 n_read
+= pt
->read_buf
- (unsigned char *) buffer
;
1703 /* Reinstate the port's normal buffer. */
1708 /* The port has its own buffer. It is important that we use it,
1709 even if it happens to be smaller than our caller's buffer, so
1710 that a custom port implementation's entry points (in
1711 particular, fill_input) can rely on the buffer always being
1712 the same as they first set up. */
1713 while (size
&& (scm_i_fill_input (port
) != EOF
))
1715 n_available
= min (size
, pt
->read_end
- pt
->read_pos
);
1716 memcpy (buffer
, pt
->read_pos
, n_available
);
1717 buffer
= (char *) buffer
+ n_available
;
1718 pt
->read_pos
+= n_available
;
1719 n_read
+= n_available
;
1720 size
-= n_available
;
1730 * Used by an application to write arbitrary number of bytes to an SCM
1731 * port. Similar semantics as libc write. However, unlike libc
1732 * write, scm_c_write writes the requested number of bytes and has no
1735 * Warning: Doesn't update port line and column counts!
1739 scm_c_write (SCM port
, const void *ptr
, size_t size
)
1740 #define FUNC_NAME "scm_c_write"
1743 scm_t_ptob_descriptor
*ptob
;
1745 SCM_VALIDATE_OPOUTPORT (1, port
);
1747 pt
= SCM_PTAB_ENTRY (port
);
1748 ptob
= &scm_ptobs
[SCM_PTOBNUM (port
)];
1750 if (pt
->rw_active
== SCM_PORT_READ
)
1751 scm_end_input (port
);
1753 ptob
->write (port
, ptr
, size
);
1756 pt
->rw_active
= SCM_PORT_WRITE
;
1761 scm_flush (SCM port
)
1763 long i
= SCM_PTOBNUM (port
);
1765 (scm_ptobs
[i
].flush
) (port
);
1769 scm_end_input (SCM port
)
1772 scm_t_port
*pt
= SCM_PTAB_ENTRY (port
);
1774 scm_i_clear_pending_eof (port
);
1775 if (pt
->read_buf
== pt
->putback_buf
)
1777 offset
= pt
->read_end
- pt
->read_pos
;
1778 pt
->read_buf
= pt
->saved_read_buf
;
1779 pt
->read_pos
= pt
->saved_read_pos
;
1780 pt
->read_end
= pt
->saved_read_end
;
1781 pt
->read_buf_size
= pt
->saved_read_buf_size
;
1786 scm_ptobs
[SCM_PTOBNUM (port
)].end_input (port
, offset
);
1793 scm_i_unget_bytes (const unsigned char *buf
, size_t len
, SCM port
)
1794 #define FUNC_NAME "scm_unget_bytes"
1796 scm_t_port
*pt
= SCM_PTAB_ENTRY (port
);
1797 size_t old_len
, new_len
;
1799 scm_i_clear_pending_eof (port
);
1801 if (pt
->read_buf
!= pt
->putback_buf
)
1802 /* switch to the put-back buffer. */
1804 if (pt
->putback_buf
== NULL
)
1806 pt
->putback_buf_size
= (len
> SCM_INITIAL_PUTBACK_BUF_SIZE
1807 ? len
: SCM_INITIAL_PUTBACK_BUF_SIZE
);
1809 = (unsigned char *) scm_gc_malloc_pointerless
1810 (pt
->putback_buf_size
, "putback buffer");
1813 pt
->saved_read_buf
= pt
->read_buf
;
1814 pt
->saved_read_pos
= pt
->read_pos
;
1815 pt
->saved_read_end
= pt
->read_end
;
1816 pt
->saved_read_buf_size
= pt
->read_buf_size
;
1818 /* Put read_pos at the end of the buffer, so that ungets will not
1819 have to shift the buffer contents each time. */
1820 pt
->read_buf
= pt
->putback_buf
;
1821 pt
->read_pos
= pt
->read_end
= pt
->putback_buf
+ pt
->putback_buf_size
;
1822 pt
->read_buf_size
= pt
->putback_buf_size
;
1825 old_len
= pt
->read_end
- pt
->read_pos
;
1826 new_len
= old_len
+ len
;
1828 if (new_len
> pt
->read_buf_size
)
1829 /* The putback buffer needs to be enlarged. */
1831 size_t new_buf_size
;
1832 unsigned char *new_buf
, *new_end
, *new_pos
;
1834 new_buf_size
= pt
->read_buf_size
* 2;
1835 if (new_buf_size
< new_len
)
1836 new_buf_size
= new_len
;
1838 new_buf
= (unsigned char *)
1839 scm_gc_malloc_pointerless (new_buf_size
, "putback buffer");
1841 /* Put the bytes at the end of the buffer, so that future
1842 ungets won't need to shift the buffer. */
1843 new_end
= new_buf
+ new_buf_size
;
1844 new_pos
= new_end
- old_len
;
1845 memcpy (new_pos
, pt
->read_pos
, old_len
);
1847 pt
->read_buf
= pt
->putback_buf
= new_buf
;
1848 pt
->read_pos
= new_pos
;
1849 pt
->read_end
= new_end
;
1850 pt
->read_buf_size
= pt
->putback_buf_size
= new_buf_size
;
1852 else if (pt
->read_buf
+ len
< pt
->read_pos
)
1853 /* If needed, shift the existing buffer contents up.
1854 This should not happen unless some external code
1855 manipulates the putback buffer pointers. */
1857 unsigned char *new_end
= pt
->read_buf
+ pt
->read_buf_size
;
1858 unsigned char *new_pos
= new_end
- old_len
;
1860 memmove (new_pos
, pt
->read_pos
, old_len
);
1861 pt
->read_pos
= new_pos
;
1862 pt
->read_end
= new_end
;
1865 /* Move read_pos back and copy the bytes there. */
1866 pt
->read_pos
-= len
;
1867 memcpy (pt
->read_buf
+ (pt
->read_pos
- pt
->read_buf
), buf
, len
);
1869 if (pt
->rw_active
== SCM_PORT_WRITE
)
1873 pt
->rw_active
= SCM_PORT_READ
;
1878 scm_unget_bytes (const unsigned char *buf
, size_t len
, SCM port
)
1880 scm_i_unget_bytes (buf
, len
, port
);
1884 scm_unget_byte (int c
, SCM port
)
1889 scm_i_unget_bytes (&byte
, 1, port
);
1893 scm_ungetc (scm_t_wchar c
, SCM port
)
1894 #define FUNC_NAME "scm_ungetc"
1896 scm_t_port
*pt
= SCM_PTAB_ENTRY (port
);
1898 char result_buf
[10];
1899 const char *encoding
;
1902 if (pt
->encoding
!= NULL
)
1903 encoding
= pt
->encoding
;
1905 encoding
= "ISO-8859-1";
1907 len
= sizeof (result_buf
);
1908 result
= u32_conv_to_encoding (encoding
,
1909 (enum iconv_ilseq_handler
) pt
->ilseq_handler
,
1910 (uint32_t *) &c
, 1, NULL
,
1913 if (SCM_UNLIKELY (result
== NULL
|| len
== 0))
1914 scm_encoding_error (FUNC_NAME
, errno
,
1915 "conversion to port encoding failed",
1916 SCM_BOOL_F
, SCM_MAKE_CHAR (c
));
1918 scm_i_unget_bytes ((unsigned char *) result
, len
, port
);
1920 if (SCM_UNLIKELY (result
!= result_buf
))
1925 /* What should col be in this case?
1926 * We'll leave it at -1.
1928 SCM_LINUM (port
) -= 1;
1937 scm_ungets (const char *s
, int n
, SCM port
)
1939 /* This is simple minded and inefficient, but unreading strings is
1940 * probably not a common operation, and remember that line and
1941 * column numbers have to be handled...
1943 * Please feel free to write an optimized version!
1946 scm_ungetc (s
[n
], port
);
1950 SCM_DEFINE (scm_peek_char
, "peek-char", 0, 1, 0,
1952 "Return the next character available from @var{port},\n"
1953 "@emph{without} updating @var{port} to point to the following\n"
1954 "character. If no more characters are available, the\n"
1955 "end-of-file object is returned.\n"
1957 "The value returned by\n"
1958 "a call to @code{peek-char} is the same as the value that would\n"
1959 "have been returned by a call to @code{read-char} on the same\n"
1960 "port. The only difference is that the very next call to\n"
1961 "@code{read-char} or @code{peek-char} on that @var{port} will\n"
1962 "return the value returned by the preceding call to\n"
1963 "@code{peek-char}. In particular, a call to @code{peek-char} on\n"
1964 "an interactive port will hang waiting for input whenever a call\n"
1965 "to @code{read-char} would have hung.\n"
1967 "As for @code{read-char}, a @code{decoding-error} may be raised\n"
1968 "if such a situation occurs. However, unlike with @code{read-char},\n"
1969 "@var{port} still points at the beginning of the erroneous byte\n"
1970 "sequence when the error is raised.\n")
1971 #define FUNC_NAME s_scm_peek_char
1976 char bytes
[SCM_MBCHAR_BUF_SIZE
];
1980 if (SCM_UNBNDP (port
))
1981 port
= scm_current_input_port ();
1982 SCM_VALIDATE_OPINPORT (1, port
);
1984 column
= SCM_COL (port
);
1985 line
= SCM_LINUM (port
);
1987 err
= get_codepoint (port
, &c
, bytes
, &len
);
1989 scm_i_unget_bytes ((unsigned char *) bytes
, len
, port
);
1991 SCM_COL (port
) = column
;
1992 SCM_LINUM (port
) = line
;
1994 if (SCM_UNLIKELY (err
!= 0))
1996 scm_decoding_error (FUNC_NAME
, err
, "input decoding error", port
);
1998 /* Shouldn't happen since `catch' always aborts to prompt. */
1999 result
= SCM_BOOL_F
;
2003 scm_i_set_pending_eof (port
);
2004 result
= SCM_EOF_VAL
;
2007 result
= SCM_MAKE_CHAR (c
);
2013 SCM_DEFINE (scm_unread_char
, "unread-char", 1, 1, 0,
2014 (SCM cobj
, SCM port
),
2015 "Place character @var{cobj} in @var{port} so that it will be\n"
2016 "read by the next read operation. If called multiple times, the\n"
2017 "unread characters will be read again in last-in first-out\n"
2018 "order. If @var{port} is not supplied, the current input port\n"
2020 #define FUNC_NAME s_scm_unread_char
2024 SCM_VALIDATE_CHAR (1, cobj
);
2025 if (SCM_UNBNDP (port
))
2026 port
= scm_current_input_port ();
2027 SCM_VALIDATE_OPINPORT (2, port
);
2029 c
= SCM_CHAR (cobj
);
2031 scm_ungetc (c
, port
);
2036 SCM_DEFINE (scm_unread_string
, "unread-string", 2, 0, 0,
2037 (SCM str
, SCM port
),
2038 "Place the string @var{str} in @var{port} so that its characters will be\n"
2039 "read in subsequent read operations. If called multiple times, the\n"
2040 "unread characters will be read again in last-in first-out order. If\n"
2041 "@var{port} is not supplied, the current-input-port is used.")
2042 #define FUNC_NAME s_scm_unread_string
2045 SCM_VALIDATE_STRING (1, str
);
2046 if (SCM_UNBNDP (port
))
2047 port
= scm_current_input_port ();
2048 SCM_VALIDATE_OPINPORT (2, port
);
2050 n
= scm_i_string_length (str
);
2053 scm_ungetc (scm_i_string_ref (str
, n
), port
);
2059 SCM_DEFINE (scm_seek
, "seek", 3, 0, 0,
2060 (SCM fd_port
, SCM offset
, SCM whence
),
2061 "Sets the current position of @var{fd_port} to the integer\n"
2062 "@var{offset}, which is interpreted according to the value of\n"
2065 "One of the following variables should be supplied for\n"
2067 "@defvar SEEK_SET\n"
2068 "Seek from the beginning of the file.\n"
2070 "@defvar SEEK_CUR\n"
2071 "Seek from the current position.\n"
2073 "@defvar SEEK_END\n"
2074 "Seek from the end of the file.\n"
2076 "If @var{fd_port} is a file descriptor, the underlying system\n"
2077 "call is @code{lseek}. @var{port} may be a string port.\n"
2079 "The value returned is the new position in the file. This means\n"
2080 "that the current position of a port can be obtained using:\n"
2082 "(seek port 0 SEEK_CUR)\n"
2084 #define FUNC_NAME s_scm_seek
2088 fd_port
= SCM_COERCE_OUTPORT (fd_port
);
2090 how
= scm_to_int (whence
);
2091 if (how
!= SEEK_SET
&& how
!= SEEK_CUR
&& how
!= SEEK_END
)
2092 SCM_OUT_OF_RANGE (3, whence
);
2094 if (SCM_OPPORTP (fd_port
))
2096 scm_t_port_internal
*pti
= SCM_PORT_GET_INTERNAL (fd_port
);
2097 scm_t_ptob_descriptor
*ptob
= scm_ptobs
+ SCM_PTOBNUM (fd_port
);
2098 off_t_or_off64_t off
= scm_to_off_t_or_off64_t (offset
);
2099 off_t_or_off64_t rv
;
2102 SCM_MISC_ERROR ("port is not seekable",
2103 scm_cons (fd_port
, SCM_EOL
));
2105 rv
= ptob
->seek (fd_port
, off
, how
);
2107 /* Set stream-start flags according to new position. */
2108 pti
->at_stream_start_for_bom_read
= (rv
== 0);
2109 pti
->at_stream_start_for_bom_write
= (rv
== 0);
2111 scm_i_clear_pending_eof (fd_port
);
2113 return scm_from_off_t_or_off64_t (rv
);
2115 else /* file descriptor?. */
2117 off_t_or_off64_t off
= scm_to_off_t_or_off64_t (offset
);
2118 off_t_or_off64_t rv
;
2119 rv
= lseek_or_lseek64 (scm_to_int (fd_port
), off
, how
);
2122 return scm_from_off_t_or_off64_t (rv
);
2131 /* Mingw has ftruncate(), perhaps implemented above using chsize, but
2132 doesn't have the filename version truncate(), hence this code. */
2133 #if HAVE_FTRUNCATE && ! HAVE_TRUNCATE
2135 truncate (const char *file
, off_t length
)
2139 fdes
= open (file
, O_BINARY
| O_WRONLY
);
2143 ret
= ftruncate (fdes
, length
);
2146 int save_errno
= errno
;
2152 return close (fdes
);
2154 #endif /* HAVE_FTRUNCATE && ! HAVE_TRUNCATE */
2156 SCM_DEFINE (scm_truncate_file
, "truncate-file", 1, 1, 0,
2157 (SCM object
, SCM length
),
2158 "Truncate file @var{object} to @var{length} bytes. @var{object}\n"
2159 "can be a filename string, a port object, or an integer file\n"
2161 "The return value is unspecified.\n"
2163 "For a port or file descriptor @var{length} can be omitted, in\n"
2164 "which case the file is truncated at the current position (per\n"
2165 "@code{ftell} above).\n"
2167 "On most systems a file can be extended by giving a length\n"
2168 "greater than the current size, but this is not mandatory in the\n"
2170 #define FUNC_NAME s_scm_truncate_file
2174 /* "object" can be a port, fdes or filename.
2176 Negative "length" makes no sense, but it's left to truncate() or
2177 ftruncate() to give back an error for that (normally EINVAL).
2180 if (SCM_UNBNDP (length
))
2182 /* must supply length if object is a filename. */
2183 if (scm_is_string (object
))
2184 SCM_MISC_ERROR("must supply length if OBJECT is a filename", SCM_EOL
);
2186 length
= scm_seek (object
, SCM_INUM0
, scm_from_int (SEEK_CUR
));
2189 object
= SCM_COERCE_OUTPORT (object
);
2190 if (scm_is_integer (object
))
2192 off_t_or_off64_t c_length
= scm_to_off_t_or_off64_t (length
);
2193 SCM_SYSCALL (rv
= ftruncate_or_ftruncate64 (scm_to_int (object
),
2196 else if (SCM_OPOUTPORTP (object
))
2198 off_t_or_off64_t c_length
= scm_to_off_t_or_off64_t (length
);
2199 scm_t_port
*pt
= SCM_PTAB_ENTRY (object
);
2200 scm_t_ptob_descriptor
*ptob
= scm_ptobs
+ SCM_PTOBNUM (object
);
2202 if (!ptob
->truncate
)
2203 SCM_MISC_ERROR ("port is not truncatable", SCM_EOL
);
2205 scm_i_clear_pending_eof (object
);
2206 if (pt
->rw_active
== SCM_PORT_READ
)
2207 scm_end_input (object
);
2208 else if (pt
->rw_active
== SCM_PORT_WRITE
)
2209 ptob
->flush (object
);
2211 ptob
->truncate (object
, c_length
);
2216 off_t_or_off64_t c_length
= scm_to_off_t_or_off64_t (length
);
2217 char *str
= scm_to_locale_string (object
);
2219 SCM_SYSCALL (rv
= truncate_or_truncate64 (str
, c_length
));
2226 return SCM_UNSPECIFIED
;
2230 SCM_DEFINE (scm_port_line
, "port-line", 1, 0, 0,
2232 "Return the current line number for @var{port}.\n"
2234 "The first line of a file is 0. But you might want to add 1\n"
2235 "when printing line numbers, since starting from 1 is\n"
2236 "traditional in error messages, and likely to be more natural to\n"
2238 #define FUNC_NAME s_scm_port_line
2240 port
= SCM_COERCE_OUTPORT (port
);
2241 SCM_VALIDATE_OPENPORT (1, port
);
2242 return scm_from_long (SCM_LINUM (port
));
2246 SCM_DEFINE (scm_set_port_line_x
, "set-port-line!", 2, 0, 0,
2247 (SCM port
, SCM line
),
2248 "Set the current line number for @var{port} to @var{line}. The\n"
2249 "first line of a file is 0.")
2250 #define FUNC_NAME s_scm_set_port_line_x
2252 port
= SCM_COERCE_OUTPORT (port
);
2253 SCM_VALIDATE_OPENPORT (1, port
);
2254 SCM_PTAB_ENTRY (port
)->line_number
= scm_to_long (line
);
2255 return SCM_UNSPECIFIED
;
2259 SCM_DEFINE (scm_port_column
, "port-column", 1, 0, 0,
2261 "Return the current column number of @var{port}.\n"
2262 "If the number is\n"
2263 "unknown, the result is #f. Otherwise, the result is a 0-origin integer\n"
2264 "- i.e. the first character of the first line is line 0, column 0.\n"
2265 "(However, when you display a file position, for example in an error\n"
2266 "message, we recommend you add 1 to get 1-origin integers. This is\n"
2267 "because lines and column numbers traditionally start with 1, and that is\n"
2268 "what non-programmers will find most natural.)")
2269 #define FUNC_NAME s_scm_port_column
2271 port
= SCM_COERCE_OUTPORT (port
);
2272 SCM_VALIDATE_OPENPORT (1, port
);
2273 return scm_from_int (SCM_COL (port
));
2277 SCM_DEFINE (scm_set_port_column_x
, "set-port-column!", 2, 0, 0,
2278 (SCM port
, SCM column
),
2279 "Set the current column of @var{port}. Before reading the first\n"
2280 "character on a line the column should be 0.")
2281 #define FUNC_NAME s_scm_set_port_column_x
2283 port
= SCM_COERCE_OUTPORT (port
);
2284 SCM_VALIDATE_OPENPORT (1, port
);
2285 SCM_PTAB_ENTRY (port
)->column_number
= scm_to_int (column
);
2286 return SCM_UNSPECIFIED
;
2290 SCM_DEFINE (scm_port_filename
, "port-filename", 1, 0, 0,
2292 "Return the filename associated with @var{port}, or @code{#f}\n"
2293 "if no filename is associated with the port.")
2294 #define FUNC_NAME s_scm_port_filename
2296 port
= SCM_COERCE_OUTPORT (port
);
2297 SCM_VALIDATE_OPENPORT (1, port
);
2298 return SCM_FILENAME (port
);
2302 SCM_DEFINE (scm_set_port_filename_x
, "set-port-filename!", 2, 0, 0,
2303 (SCM port
, SCM filename
),
2304 "Change the filename associated with @var{port}, using the current input\n"
2305 "port if none is specified. Note that this does not change the port's\n"
2306 "source of data, but only the value that is returned by\n"
2307 "@code{port-filename} and reported in diagnostic output.")
2308 #define FUNC_NAME s_scm_set_port_filename_x
2310 port
= SCM_COERCE_OUTPORT (port
);
2311 SCM_VALIDATE_OPENPORT (1, port
);
2312 /* We allow the user to set the filename to whatever he likes. */
2313 SCM_SET_FILENAME (port
, filename
);
2314 return SCM_UNSPECIFIED
;
2318 /* A fluid specifying the default encoding for newly created ports. If it is
2319 a string, that is the encoding. If it is #f, it is in the "native"
2320 (Latin-1) encoding. */
2321 SCM_VARIABLE (default_port_encoding_var
, "%default-port-encoding");
2323 static int scm_port_encoding_init
= 0;
2325 /* Use ENCODING as the default encoding for future ports. */
2327 scm_i_set_default_port_encoding (const char *encoding
)
2329 if (!scm_port_encoding_init
2330 || !scm_is_fluid (SCM_VARIABLE_REF (default_port_encoding_var
)))
2331 scm_misc_error (NULL
, "tried to set port encoding fluid before it is initialized",
2334 if (encoding
== NULL
2335 || c_strcasecmp (encoding
, "ASCII") == 0
2336 || c_strcasecmp (encoding
, "ANSI_X3.4-1968") == 0
2337 || c_strcasecmp (encoding
, "ISO-8859-1") == 0)
2338 scm_fluid_set_x (SCM_VARIABLE_REF (default_port_encoding_var
), SCM_BOOL_F
);
2340 scm_fluid_set_x (SCM_VARIABLE_REF (default_port_encoding_var
),
2341 scm_from_locale_string (encoding
));
2344 /* Return the name of the default encoding for newly created ports; a
2345 return value of NULL means "ISO-8859-1". */
2347 scm_i_default_port_encoding (void)
2349 if (!scm_port_encoding_init
)
2351 else if (!scm_is_fluid (SCM_VARIABLE_REF (default_port_encoding_var
)))
2357 encoding
= scm_fluid_ref (SCM_VARIABLE_REF (default_port_encoding_var
));
2358 if (!scm_is_string (encoding
))
2361 return scm_i_string_chars (encoding
);
2365 /* If the next LEN bytes from PORT are equal to those in BYTES, then
2366 return 1, else return 0. Leave the port position unchanged. */
2368 looking_at_bytes (SCM port
, const unsigned char *bytes
, int len
)
2370 scm_t_port
*pt
= SCM_PTAB_ENTRY (port
);
2373 while (i
< len
&& scm_peek_byte_or_eof (port
) == bytes
[i
])
2378 scm_i_unget_bytes (bytes
, i
, port
);
2382 static const unsigned char scm_utf8_bom
[3] = {0xEF, 0xBB, 0xBF};
2383 static const unsigned char scm_utf16be_bom
[2] = {0xFE, 0xFF};
2384 static const unsigned char scm_utf16le_bom
[2] = {0xFF, 0xFE};
2385 static const unsigned char scm_utf32be_bom
[4] = {0x00, 0x00, 0xFE, 0xFF};
2386 static const unsigned char scm_utf32le_bom
[4] = {0xFF, 0xFE, 0x00, 0x00};
2388 /* Decide what byte order to use for a UTF-16 port. Return "UTF-16BE"
2389 or "UTF-16LE". MODE must be either SCM_PORT_READ or SCM_PORT_WRITE,
2390 and specifies which operation is about to be done. The MODE
2391 determines how we will decide the byte order. We deliberately avoid
2392 reading from the port unless the user is about to do so. If the user
2393 is about to read, then we look for a BOM, and if present, we use it
2394 to determine the byte order. Otherwise we choose big endian, as
2395 recommended by the Unicode Standard. Note that the BOM (if any) is
2396 not consumed here. */
2398 decide_utf16_encoding (SCM port
, scm_t_port_rw_active mode
)
2400 if (mode
== SCM_PORT_READ
2401 && SCM_PORT_GET_INTERNAL (port
)->at_stream_start_for_bom_read
2402 && looking_at_bytes (port
, scm_utf16le_bom
, sizeof scm_utf16le_bom
))
2408 /* Decide what byte order to use for a UTF-32 port. Return "UTF-32BE"
2409 or "UTF-32LE". See the comment above 'decide_utf16_encoding' for
2412 decide_utf32_encoding (SCM port
, scm_t_port_rw_active mode
)
2414 if (mode
== SCM_PORT_READ
2415 && SCM_PORT_GET_INTERNAL (port
)->at_stream_start_for_bom_read
2416 && looking_at_bytes (port
, scm_utf32le_bom
, sizeof scm_utf32le_bom
))
2423 finalize_iconv_descriptors (void *ptr
, void *data
)
2425 close_iconv_descriptors (ptr
);
2428 static scm_t_iconv_descriptors
*
2429 open_iconv_descriptors (const char *encoding
, int reading
, int writing
)
2431 scm_t_iconv_descriptors
*id
;
2432 iconv_t input_cd
, output_cd
;
2434 input_cd
= (iconv_t
) -1;
2435 output_cd
= (iconv_t
) -1;
2438 /* Open an input iconv conversion descriptor, from ENCODING
2439 to UTF-8. We choose UTF-8, not UTF-32, because iconv
2440 implementations can typically convert from anything to
2441 UTF-8, but not to UTF-32 (see
2442 <http://lists.gnu.org/archive/html/bug-libunistring/2010-09/msg00007.html>). */
2444 /* Assume opening an iconv descriptor causes about 16 KB of
2446 scm_gc_register_allocation (16 * 1024);
2448 input_cd
= iconv_open ("UTF-8", encoding
);
2449 if (input_cd
== (iconv_t
) -1)
2450 goto invalid_encoding
;
2455 /* Assume opening an iconv descriptor causes about 16 KB of
2457 scm_gc_register_allocation (16 * 1024);
2459 output_cd
= iconv_open (encoding
, "UTF-8");
2460 if (output_cd
== (iconv_t
) -1)
2462 if (input_cd
!= (iconv_t
) -1)
2463 iconv_close (input_cd
);
2464 goto invalid_encoding
;
2468 id
= scm_gc_malloc_pointerless (sizeof (*id
), "iconv descriptors");
2469 id
->input_cd
= input_cd
;
2470 id
->output_cd
= output_cd
;
2472 /* Register a finalizer to close the descriptors. */
2473 scm_i_set_finalizer (id
, finalize_iconv_descriptors
, NULL
);
2480 err
= scm_from_locale_string (encoding
);
2481 scm_misc_error ("open_iconv_descriptors",
2482 "invalid or unknown character encoding ~s",
2488 close_iconv_descriptors (scm_t_iconv_descriptors
*id
)
2490 if (id
->input_cd
!= (iconv_t
) -1)
2491 iconv_close (id
->input_cd
);
2492 if (id
->output_cd
!= (iconv_t
) -1)
2493 iconv_close (id
->output_cd
);
2494 id
->input_cd
= (void *) -1;
2495 id
->output_cd
= (void *) -1;
2498 /* Return the iconv_descriptors, initializing them if necessary. MODE
2499 must be either SCM_PORT_READ or SCM_PORT_WRITE, and specifies which
2500 operation is about to be done. We deliberately avoid reading from
2501 the port unless the user was about to do so. */
2502 scm_t_iconv_descriptors
*
2503 scm_i_port_iconv_descriptors (SCM port
, scm_t_port_rw_active mode
)
2505 scm_t_port_internal
*pti
= SCM_PORT_GET_INTERNAL (port
);
2507 assert (pti
->encoding_mode
== SCM_PORT_ENCODING_MODE_ICONV
);
2509 if (!pti
->iconv_descriptors
)
2511 scm_t_port
*pt
= SCM_PTAB_ENTRY (port
);
2512 const char *precise_encoding
;
2515 pt
->encoding
= "ISO-8859-1";
2517 /* If the specified encoding is UTF-16 or UTF-32, then make
2518 that more precise by deciding what byte order to use. */
2519 if (c_strcasecmp (pt
->encoding
, "UTF-16") == 0)
2520 precise_encoding
= decide_utf16_encoding (port
, mode
);
2521 else if (c_strcasecmp (pt
->encoding
, "UTF-32") == 0)
2522 precise_encoding
= decide_utf32_encoding (port
, mode
);
2524 precise_encoding
= pt
->encoding
;
2526 pti
->iconv_descriptors
=
2527 open_iconv_descriptors (precise_encoding
,
2528 SCM_INPUT_PORT_P (port
),
2529 SCM_OUTPUT_PORT_P (port
));
2532 return pti
->iconv_descriptors
;
2536 scm_i_set_port_encoding_x (SCM port
, const char *encoding
)
2539 scm_t_port_internal
*pti
;
2540 scm_t_iconv_descriptors
*prev
;
2542 /* Set the character encoding for this port. */
2543 pt
= SCM_PTAB_ENTRY (port
);
2544 pti
= SCM_PORT_GET_INTERNAL (port
);
2545 prev
= pti
->iconv_descriptors
;
2547 /* In order to handle cases where the encoding changes mid-stream
2548 (e.g. within an HTTP stream, or within a file that is composed of
2549 segments with different encodings), we consider this to be "stream
2550 start" for purposes of BOM handling, regardless of our actual file
2552 pti
->at_stream_start_for_bom_read
= 1;
2553 pti
->at_stream_start_for_bom_write
= 1;
2555 if (encoding
== NULL
)
2556 encoding
= "ISO-8859-1";
2558 /* If ENCODING is UTF-8, then no conversion descriptor is opened
2559 because we do I/O ourselves. This saves 100+ KiB for each
2561 pt
->encoding
= scm_gc_strdup (encoding
, "port");
2562 if (c_strcasecmp (encoding
, "UTF-8") == 0)
2563 pti
->encoding_mode
= SCM_PORT_ENCODING_MODE_UTF8
;
2565 pti
->encoding_mode
= SCM_PORT_ENCODING_MODE_ICONV
;
2567 pti
->iconv_descriptors
= NULL
;
2569 close_iconv_descriptors (prev
);
2572 SCM_DEFINE (scm_port_encoding
, "port-encoding", 1, 0, 0,
2574 "Returns, as a string, the character encoding that @var{port}\n"
2575 "uses to interpret its input and output.\n")
2576 #define FUNC_NAME s_scm_port_encoding
2581 SCM_VALIDATE_PORT (1, port
);
2583 pt
= SCM_PTAB_ENTRY (port
);
2586 return scm_from_locale_string (pt
->encoding
);
2592 SCM_DEFINE (scm_set_port_encoding_x
, "set-port-encoding!", 2, 0, 0,
2593 (SCM port
, SCM enc
),
2594 "Sets the character encoding that will be used to interpret all\n"
2595 "port I/O. New ports are created with the encoding\n"
2596 "appropriate for the current locale if @code{setlocale} has \n"
2597 "been called or ISO-8859-1 otherwise\n"
2598 "and this procedure can be used to modify that encoding.\n")
2599 #define FUNC_NAME s_scm_set_port_encoding_x
2603 SCM_VALIDATE_PORT (1, port
);
2604 SCM_VALIDATE_STRING (2, enc
);
2606 enc_str
= scm_to_locale_string (enc
);
2607 scm_i_set_port_encoding_x (port
, enc_str
);
2610 return SCM_UNSPECIFIED
;
2615 /* A fluid specifying the default conversion handler for newly created
2616 ports. Its value should be one of the symbols below. */
2617 SCM_VARIABLE (default_conversion_strategy_var
,
2618 "%default-port-conversion-strategy");
2620 /* Whether the above fluid is initialized. */
2621 static int scm_conversion_strategy_init
= 0;
2623 /* The possible conversion strategies. */
2624 SCM_SYMBOL (sym_error
, "error");
2625 SCM_SYMBOL (sym_substitute
, "substitute");
2626 SCM_SYMBOL (sym_escape
, "escape");
2628 /* Return the default failed encoding conversion policy for new created
2630 scm_t_string_failed_conversion_handler
2631 scm_i_default_port_conversion_handler (void)
2633 scm_t_string_failed_conversion_handler handler
;
2635 if (!scm_conversion_strategy_init
2636 || !scm_is_fluid (SCM_VARIABLE_REF (default_conversion_strategy_var
)))
2637 handler
= SCM_FAILED_CONVERSION_QUESTION_MARK
;
2642 fluid
= SCM_VARIABLE_REF (default_conversion_strategy_var
);
2643 value
= scm_fluid_ref (fluid
);
2645 if (scm_is_eq (sym_substitute
, value
))
2646 handler
= SCM_FAILED_CONVERSION_QUESTION_MARK
;
2647 else if (scm_is_eq (sym_escape
, value
))
2648 handler
= SCM_FAILED_CONVERSION_ESCAPE_SEQUENCE
;
2650 /* Default to 'error also when the fluid's value is not one of
2651 the valid symbols. */
2652 handler
= SCM_FAILED_CONVERSION_ERROR
;
2658 /* Use HANDLER as the default conversion strategy for future ports. */
2660 scm_i_set_default_port_conversion_handler (scm_t_string_failed_conversion_handler
2665 if (!scm_conversion_strategy_init
2666 || !scm_is_fluid (SCM_VARIABLE_REF (default_conversion_strategy_var
)))
2667 scm_misc_error (NULL
, "tried to set conversion strategy fluid before it is initialized",
2672 case SCM_FAILED_CONVERSION_ERROR
:
2673 strategy
= sym_error
;
2676 case SCM_FAILED_CONVERSION_ESCAPE_SEQUENCE
:
2677 strategy
= sym_escape
;
2680 case SCM_FAILED_CONVERSION_QUESTION_MARK
:
2681 strategy
= sym_substitute
;
2688 scm_fluid_set_x (SCM_VARIABLE_REF (default_conversion_strategy_var
),
2692 SCM_DEFINE (scm_port_conversion_strategy
, "port-conversion-strategy",
2693 1, 0, 0, (SCM port
),
2694 "Returns the behavior of the port when handling a character that\n"
2695 "is not representable in the port's current encoding.\n"
2696 "It returns the symbol @code{error} if unrepresentable characters\n"
2697 "should cause exceptions, @code{substitute} if the port should\n"
2698 "try to replace unrepresentable characters with question marks or\n"
2699 "approximate characters, or @code{escape} if unrepresentable\n"
2700 "characters should be converted to string escapes.\n"
2702 "If @var{port} is @code{#f}, then the current default behavior\n"
2703 "will be returned. New ports will have this default behavior\n"
2704 "when they are created.\n")
2705 #define FUNC_NAME s_scm_port_conversion_strategy
2707 scm_t_string_failed_conversion_handler h
;
2709 if (scm_is_false (port
))
2710 h
= scm_i_default_port_conversion_handler ();
2715 SCM_VALIDATE_OPPORT (1, port
);
2716 pt
= SCM_PTAB_ENTRY (port
);
2718 h
= pt
->ilseq_handler
;
2721 if (h
== SCM_FAILED_CONVERSION_ERROR
)
2722 return scm_from_latin1_symbol ("error");
2723 else if (h
== SCM_FAILED_CONVERSION_QUESTION_MARK
)
2724 return scm_from_latin1_symbol ("substitute");
2725 else if (h
== SCM_FAILED_CONVERSION_ESCAPE_SEQUENCE
)
2726 return scm_from_latin1_symbol ("escape");
2730 /* Never gets here. */
2731 return SCM_UNDEFINED
;
2735 SCM_DEFINE (scm_set_port_conversion_strategy_x
, "set-port-conversion-strategy!",
2737 (SCM port
, SCM sym
),
2738 "Sets the behavior of the interpreter when outputting a character\n"
2739 "that is not representable in the port's current encoding.\n"
2740 "@var{sym} can be either @code{'error}, @code{'substitute}, or\n"
2741 "@code{'escape}. If it is @code{'error}, an error will be thrown\n"
2742 "when an unconvertible character is encountered. If it is\n"
2743 "@code{'substitute}, then unconvertible characters will \n"
2744 "be replaced with approximate characters, or with question marks\n"
2745 "if no approximately correct character is available.\n"
2746 "If it is @code{'escape},\n"
2747 "it will appear as a hex escape when output.\n"
2749 "If @var{port} is an open port, the conversion error behavior\n"
2750 "is set for that port. If it is @code{#f}, it is set as the\n"
2751 "default behavior for any future ports that get created in\n"
2753 #define FUNC_NAME s_scm_set_port_conversion_strategy_x
2755 scm_t_string_failed_conversion_handler handler
;
2757 if (scm_is_eq (sym
, sym_error
))
2758 handler
= SCM_FAILED_CONVERSION_ERROR
;
2759 else if (scm_is_eq (sym
, sym_substitute
))
2760 handler
= SCM_FAILED_CONVERSION_QUESTION_MARK
;
2761 else if (scm_is_eq (sym
, sym_escape
))
2762 handler
= SCM_FAILED_CONVERSION_ESCAPE_SEQUENCE
;
2764 SCM_MISC_ERROR ("unknown conversion strategy ~s", scm_list_1 (sym
));
2766 if (scm_is_false (port
))
2767 scm_i_set_default_port_conversion_handler (handler
);
2770 SCM_VALIDATE_OPPORT (1, port
);
2771 SCM_PTAB_ENTRY (port
)->ilseq_handler
= handler
;
2774 return SCM_UNSPECIFIED
;
2781 scm_print_port_mode (SCM exp
, SCM port
)
2783 scm_puts (SCM_CLOSEDP (exp
)
2785 : (SCM_RDNG
& SCM_CELL_WORD_0 (exp
)
2786 ? (SCM_WRTNG
& SCM_CELL_WORD_0 (exp
)
2789 : (SCM_WRTNG
& SCM_CELL_WORD_0 (exp
)
2796 scm_port_print (SCM exp
, SCM port
, scm_print_state
*pstate SCM_UNUSED
)
2798 char *type
= SCM_PTOBNAME (SCM_PTOBNUM (exp
));
2801 scm_puts ("#<", port
);
2802 scm_print_port_mode (exp
, port
);
2803 scm_puts (type
, port
);
2804 scm_putc (' ', port
);
2805 scm_uintprint (SCM_CELL_WORD_1 (exp
), 16, port
);
2806 scm_putc ('>', port
);
2814 scm_t_bits scm_tc16_void_port
= 0;
2816 static int fill_input_void_port (SCM port SCM_UNUSED
)
2822 write_void_port (SCM port SCM_UNUSED
,
2823 const void *data SCM_UNUSED
,
2824 size_t size SCM_UNUSED
)
2829 scm_i_void_port (long mode_bits
)
2831 scm_i_scm_pthread_mutex_lock (&scm_i_port_table_mutex
);
2833 SCM answer
= scm_new_port_table_entry (scm_tc16_void_port
);
2834 scm_t_port
* pt
= SCM_PTAB_ENTRY(answer
);
2836 scm_port_non_buffer (pt
);
2838 SCM_SETSTREAM (answer
, 0);
2839 SCM_SET_CELL_TYPE (answer
, scm_tc16_void_port
| mode_bits
);
2840 scm_i_pthread_mutex_unlock (&scm_i_port_table_mutex
);
2846 scm_void_port (char *mode_str
)
2848 return scm_i_void_port (scm_mode_bits (mode_str
));
2851 SCM_DEFINE (scm_sys_make_void_port
, "%make-void-port", 1, 0, 0,
2853 "Create and return a new void port. A void port acts like\n"
2854 "@file{/dev/null}. The @var{mode} argument\n"
2855 "specifies the input/output modes for this port: see the\n"
2856 "documentation for @code{open-file} in @ref{File Ports}.")
2857 #define FUNC_NAME s_scm_sys_make_void_port
2859 return scm_i_void_port (scm_i_mode_bits (mode
));
2864 /* Initialization. */
2869 /* lseek() symbols. */
2870 scm_c_define ("SEEK_SET", scm_from_int (SEEK_SET
));
2871 scm_c_define ("SEEK_CUR", scm_from_int (SEEK_CUR
));
2872 scm_c_define ("SEEK_END", scm_from_int (SEEK_END
));
2874 scm_tc16_void_port
= scm_make_port_type ("void", fill_input_void_port
,
2877 cur_inport_fluid
= scm_make_fluid ();
2878 cur_outport_fluid
= scm_make_fluid ();
2879 cur_errport_fluid
= scm_make_fluid ();
2880 cur_loadport_fluid
= scm_make_fluid ();
2882 scm_i_port_weak_hash
= scm_make_weak_key_hash_table (SCM_I_MAKINUM(31));
2884 #include "libguile/ports.x"
2886 /* Use Latin-1 as the default port encoding. */
2887 SCM_VARIABLE_SET (default_port_encoding_var
,
2888 scm_make_fluid_with_default (SCM_BOOL_F
));
2889 scm_port_encoding_init
= 1;
2891 SCM_VARIABLE_SET (default_conversion_strategy_var
,
2892 scm_make_fluid_with_default (sym_substitute
));
2893 scm_conversion_strategy_init
= 1;
2895 /* These bindings are used when boot-9 turns `current-input-port' et
2896 al into parameters. They are then removed from the guile module. */
2897 scm_c_define ("%current-input-port-fluid", cur_inport_fluid
);
2898 scm_c_define ("%current-output-port-fluid", cur_outport_fluid
);
2899 scm_c_define ("%current-error-port-fluid", cur_errport_fluid
);