1ac7eed7c95e3e57ca8cb0588c5776aeeeefa097
[bpt/guile.git] / libguile / ioext.c
1 /* Copyright (C) 1995, 1996, 1997, 1998, 1999 Free Software Foundation, Inc.
2 *
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2, or (at your option)
6 * any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this software; see the file COPYING. If not, write to
15 * the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
16 * Boston, MA 02111-1307 USA
17 *
18 * As a special exception, the Free Software Foundation gives permission
19 * for additional uses of the text contained in its release of GUILE.
20 *
21 * The exception is that, if you link the GUILE library with other files
22 * to produce an executable, this does not by itself cause the
23 * resulting executable to be covered by the GNU General Public License.
24 * Your use of that executable is in no way restricted on account of
25 * linking the GUILE library code into it.
26 *
27 * This exception does not however invalidate any other reasons why
28 * the executable file might be covered by the GNU General Public License.
29 *
30 * This exception applies only to the code released by the
31 * Free Software Foundation under the name GUILE. If you copy
32 * code from other Free Software Foundation releases into a copy of
33 * GUILE, as the General Public License permits, the exception does
34 * not apply to the code that you add in this way. To avoid misleading
35 * anyone as to the status of such modified files, you must delete
36 * this exception notice from them.
37 *
38 * If you write modifications of your own for GUILE, it is your choice
39 * whether to permit this exception to apply to your modifications.
40 * If you do not wish that, delete this exception notice. */
41
42 /* Software engineering face-lift by Greg J. Badros, 11-Dec-1999,
43 gjb@cs.washington.edu, http://www.cs.washington.edu/homes/gjb */
44
45 \f
46
47
48 #include <stdio.h>
49 #include "_scm.h"
50 #include "ports.h"
51 #include "read.h"
52 #include "fports.h"
53 #include "unif.h"
54 #include "chars.h"
55 #include "feature.h"
56
57 #include "scm_validate.h"
58 #include "ioext.h"
59
60 #include <fcntl.h>
61
62 #ifdef HAVE_STRING_H
63 #include <string.h>
64 #endif
65 #ifdef HAVE_UNISTD_H
66 #include <unistd.h>
67 #endif
68 \f
69
70 GUILE_PROC (scm_read_delimited_x, "%read-delimited!", 3, 3, 0,
71 (SCM delims, SCM buf, SCM gobble, SCM port, SCM start, SCM end),
72 "Read characters from @var{port} into @var{buf} until one of the
73 characters in the @var{delims} string is encountered. If @var{gobble?}
74 is true, store the delimiter character in @var{buf} as well; otherwise,
75 discard it. If @var{port} is not specified, use the value of
76 @code{(current-input-port)}. If @var{start} or @var{end} are specified,
77 store data only into the substring of @var{buf} bounded by @var{start}
78 and @var{end} (which default to the beginning and end of the buffer,
79 respectively).
80
81 Return a pair consisting of the delimiter that terminated the string and
82 the number of characters read. If reading stopped at the end of file,
83 the delimiter returned is the @var{eof-object}; if the buffer was filled
84 without encountering a delimiter, this value is @var{#f}.")
85 #define FUNC_NAME s_scm_read_delimited_x
86 {
87 long j;
88 char *cbuf;
89 long cstart;
90 long cend, tend;
91 int c;
92 char *cdelims;
93 int num_delims;
94
95 SCM_VALIDATE_ROSTRING_COPY(1,delims,cdelims);
96 num_delims = SCM_ROLENGTH (delims);
97 SCM_VALIDATE_STRING_COPY(2,buf,cbuf);
98 cend = SCM_LENGTH (buf);
99 if (SCM_UNBNDP (port))
100 port = scm_cur_inp;
101 else
102 SCM_VALIDATE_OPINPORT(4,port);
103
104 SCM_VALIDATE_INT_DEF_COPY(5,start,0,cstart);
105 if (cstart < 0 || cstart >= cend)
106 scm_out_of_range (FUNC_NAME, start);
107
108 SCM_VALIDATE_INT_DEF_COPY(6,end,cend,tend);
109 if (tend <= cstart || tend > cend)
110 scm_out_of_range (FUNC_NAME, end);
111 cend = tend;
112
113 for (j = cstart; j < cend; j++)
114 {
115 int k;
116
117 c = scm_getc (port);
118 for (k = 0; k < num_delims; k++)
119 {
120 if (cdelims[k] == c)
121 {
122 if (SCM_FALSEP (gobble))
123 scm_ungetc (c, port);
124
125 return scm_cons (SCM_MAKICHR (c),
126 scm_long2num (j - cstart));
127 }
128 }
129 if (c == EOF)
130 return scm_cons (SCM_EOF_VAL,
131 scm_long2num (j - cstart));
132
133 cbuf[j] = c;
134 }
135 return scm_cons (SCM_BOOL_F, scm_long2num (j - cstart));
136 }
137 #undef FUNC_NAME
138
139 static unsigned char *
140 scm_do_read_line (SCM port, int *len_p)
141 {
142 scm_port *pt = SCM_PTAB_ENTRY (port);
143 unsigned char *end;
144
145 /* I thought reading lines was simple. Mercy me. */
146
147 /* The common case: the buffer contains a complete line.
148 This needs to be fast. */
149 if ((end = memchr (pt->read_pos, '\n', (pt->read_end - pt->read_pos)))
150 != 0)
151 {
152 int buf_len = (end + 1) - pt->read_pos;
153 /* Allocate a buffer of the perfect size. */
154 unsigned char *buf = scm_must_malloc (buf_len + 1, "%read-line");
155
156 memcpy (buf, pt->read_pos, buf_len);
157 pt->read_pos += buf_len;
158
159 buf[buf_len] = '\0';
160
161 *len_p = buf_len;
162 return buf;
163 }
164
165 /* The buffer contains no newlines. */
166 {
167 /* When live, len is always the number of characters in the
168 current buffer that are part of the current line. */
169 int len = (pt->read_end - pt->read_pos);
170 int buf_size = (len < 50) ? 60 : len * 2;
171 /* Invariant: buf always has buf_size + 1 characters allocated;
172 the `+ 1' is for the final '\0'. */
173 unsigned char *buf = scm_must_malloc (buf_size + 1, "%read-line");
174 int buf_len = 0;
175
176 for (;;)
177 {
178 if (buf_len + len > buf_size)
179 {
180 int new_size = (buf_len + len) * 2;
181 buf = scm_must_realloc (buf, buf_size + 1, new_size + 1,
182 "%read-line");
183 buf_size = new_size;
184 }
185
186 /* Copy what we've got out of the port, into our buffer. */
187 memcpy (buf + buf_len, pt->read_pos, len);
188 buf_len += len;
189 pt->read_pos += len;
190
191 /* If we had seen a newline, we're done now. */
192 if (end)
193 break;
194
195 /* Get more characters. */
196 if (scm_fill_input (port) == EOF)
197 {
198 /* If we're missing a final newline in the file, return
199 what we did get, sans newline. */
200 if (buf_len > 0)
201 break;
202
203 free (buf);
204 return 0;
205 }
206
207 /* Search the buffer for newlines. */
208 if ((end = memchr (pt->read_pos, '\n',
209 (len = (pt->read_end - pt->read_pos))))
210 != 0)
211 len = (end - pt->read_pos) + 1;
212 }
213
214 /* I wonder how expensive this realloc is. */
215 buf = scm_must_realloc (buf, buf_size + 1, buf_len + 1, "%read-line");
216 buf[buf_len] = '\0';
217 *len_p = buf_len;
218 return buf;
219 }
220 }
221
222
223 /*
224 * %read-line
225 * truncates any terminating newline from its input, and returns
226 * a cons of the string read and its terminating character. Doing
227 * so makes it easy to implement the hairy `read-line' options
228 * efficiently in Scheme.
229 */
230
231 GUILE_PROC (scm_read_line, "%read-line", 0, 1, 0,
232 (SCM port),
233 "Read a newline-terminated line from @var{port}, allocating storage as
234 necessary. The newline terminator (if any) is removed from the string,
235 and a pair consisting of the line and its delimiter is returned. The
236 delimiter may be either a newline or the @var{eof-object}; if
237 @code{%read-line} is called at the end of file, it returns the pair
238 @code{(#<eof> . #<eof>)}.")
239 #define FUNC_NAME s_scm_read_line
240 {
241 scm_port *pt;
242 char *s;
243 int slen;
244 SCM line, term;
245
246 if (SCM_UNBNDP (port))
247 port = scm_cur_inp;
248 SCM_VALIDATE_OPINPORT(1,port);
249
250 pt = SCM_PTAB_ENTRY (port);
251 if (pt->rw_active == SCM_PORT_WRITE)
252 scm_ptobs[SCM_PTOBNUM (port)].flush (port);
253
254 s = scm_do_read_line (port, &slen);
255
256 if (s == NULL)
257 term = line = SCM_EOF_VAL;
258 else
259 {
260 if (s[slen-1] == '\n')
261 {
262 term = SCM_MAKICHR ('\n');
263 s[slen-1] = '\0';
264 line = scm_take_str (s, slen-1);
265 scm_done_malloc (-1);
266 SCM_INCLINE (port);
267 }
268 else
269 {
270 /* Fix: we should check for eof on the port before assuming this. */
271 term = SCM_EOF_VAL;
272 line = scm_take_str (s, slen);
273 SCM_COL (port) += slen;
274 }
275 }
276
277 if (pt->rw_random)
278 pt->rw_active = SCM_PORT_READ;
279
280 return scm_cons (line, term);
281 }
282 #undef FUNC_NAME
283
284 GUILE_PROC (scm_write_line, "write-line", 1, 1, 0,
285 (SCM obj, SCM port),
286 "Display @var{obj} and a newline character to @var{port}. If @var{port}
287 is not specified, @code{(current-output-port)} is used. This function
288 is equivalent to:
289
290 @smalllisp
291 (display obj [port])
292 (newline [port])
293 @end smalllisp")
294 #define FUNC_NAME s_scm_write_line
295 {
296 scm_display (obj, port);
297 return scm_newline (port);
298 }
299 #undef FUNC_NAME
300
301 GUILE_PROC (scm_ftell, "ftell", 1, 0, 0,
302 (SCM object),
303 "Returns an integer representing the current position of @var{fd/port},
304 measured from the beginning. Equivalent to:
305 @smalllisp
306 (seek port 0 SEEK_CUR)
307 @end smalllisp")
308 #define FUNC_NAME s_scm_ftell
309 {
310 return scm_seek (object, SCM_INUM0, SCM_MAKINUM (SEEK_CUR));
311 }
312 #undef FUNC_NAME
313
314 GUILE_PROC (scm_fseek, "fseek", 3, 0, 0,
315 (SCM object, SCM offset, SCM whence),
316 "Obsolete. Almost the same as seek, above, but the return value is
317 unspecified.")
318 #define FUNC_NAME s_scm_fseek
319 {
320 scm_seek (object, offset, whence);
321 return SCM_UNSPECIFIED;
322 }
323 #undef FUNC_NAME
324
325 GUILE_PROC (scm_redirect_port, "redirect-port", 2, 0, 0,
326 (SCM old, SCM new),
327 "This procedure takes two ports and duplicates the underlying file
328 descriptor from @var{old-port} into @var{new-port}. The
329 current file descriptor in @var{new-port} will be closed.
330 After the redirection the two ports will share a file position
331 and file status flags.
332
333 The return value is unspecified.
334
335 Unexpected behaviour can result if both ports are subsequently used
336 and the original and/or duplicate ports are buffered.
337
338 This procedure does not have any side effects on other ports or
339 revealed counts.")
340 #define FUNC_NAME s_scm_redirect_port
341 {
342 int ans, oldfd, newfd;
343 struct scm_fport *fp;
344
345 old = SCM_COERCE_OUTPORT (old);
346 new = SCM_COERCE_OUTPORT (new);
347
348 SCM_VALIDATE_OPFPORT(1,old);
349 SCM_VALIDATE_OPFPORT(2,new);
350 oldfd = SCM_FPORT_FDES (old);
351 fp = SCM_FSTREAM (new);
352 newfd = fp->fdes;
353 if (oldfd != newfd)
354 {
355 scm_port *pt = SCM_PTAB_ENTRY (new);
356 scm_port *old_pt = SCM_PTAB_ENTRY (old);
357 scm_ptob_descriptor *ptob = &scm_ptobs[SCM_PTOBNUM (new)];
358
359 /* must flush to old fdes. */
360 if (pt->rw_active == SCM_PORT_WRITE)
361 ptob->flush (new);
362 else if (pt->rw_active == SCM_PORT_READ)
363 scm_end_input (new);
364 ans = dup2 (oldfd, newfd);
365 if (ans == -1)
366 SCM_SYSERROR;
367 pt->rw_random = old_pt->rw_random;
368 /* continue using existing buffers, even if inappropriate. */
369 }
370 return SCM_UNSPECIFIED;
371 }
372 #undef FUNC_NAME
373
374 GUILE_PROC (scm_dup_to_fdes, "dup->fdes", 1, 1, 0,
375 (SCM fd_or_port, SCM fd),
376 "Returns an integer file descriptor.")
377 #define FUNC_NAME s_scm_dup_to_fdes
378 {
379 int oldfd, newfd, rv;
380
381 fd_or_port = SCM_COERCE_OUTPORT (fd_or_port);
382
383 if (SCM_INUMP (fd_or_port))
384 oldfd = SCM_INUM (fd_or_port);
385 else
386 {
387 SCM_VALIDATE_OPFPORT(1,fd_or_port);
388 oldfd = SCM_FPORT_FDES (fd_or_port);
389 }
390
391 if (SCM_UNBNDP (fd))
392 {
393 newfd = dup (oldfd);
394 if (newfd == -1)
395 SCM_SYSERROR;
396 fd = SCM_MAKINUM (newfd);
397 }
398 else
399 {
400 SCM_ASSERT (SCM_INUMP (fd), fd, SCM_ARG2, FUNC_NAME);
401 newfd = SCM_INUM (fd);
402 if (oldfd != newfd)
403 {
404 scm_evict_ports (newfd); /* see scsh manual. */
405 rv = dup2 (oldfd, newfd);
406 if (rv == -1)
407 SCM_SYSERROR;
408 }
409 }
410 return fd;
411 }
412 #undef FUNC_NAME
413
414 GUILE_PROC (scm_fileno, "fileno", 1, 0, 0,
415 (SCM port),
416 "Returns the integer file descriptor underlying @var{port}.
417 Does not change its revealed count.")
418 #define FUNC_NAME s_scm_fileno
419 {
420 port = SCM_COERCE_OUTPORT (port);
421 SCM_VALIDATE_OPFPORT(1,port);
422 return SCM_MAKINUM (SCM_FPORT_FDES (port));
423 }
424 #undef FUNC_NAME
425
426 /* GJB:FIXME:: why does this not throw
427 an error if the arg is not a port?
428 This proc as is would be better names isattyport?
429 if it is not going to assume that the arg is a port */
430 GUILE_PROC (scm_isatty_p, "isatty?", 1, 0, 0,
431 (SCM port),
432 "Returns @code{#t} if @var{port} is using a serial
433 non-file device, otherwise @code{#f}.")
434 #define FUNC_NAME s_scm_isatty_p
435 {
436 int rv;
437
438 port = SCM_COERCE_OUTPORT (port);
439
440 if (!(SCM_NIMP (port) && SCM_OPFPORTP (port)))
441 return SCM_BOOL_F;
442
443 rv = isatty (SCM_FPORT_FDES (port));
444 return SCM_BOOL(rv);
445 }
446 #undef FUNC_NAME
447
448
449
450 GUILE_PROC (scm_fdopen, "fdopen", 2, 0, 0,
451 (SCM fdes, SCM modes),
452 "Returns a new port based on the file descriptor @var{fdes}.
453 Modes are given by the string @var{modes}. The revealed count of the port
454 is initialized to zero. The modes string is the same as that accepted
455 by @ref{File Ports, open-file}.")
456 #define FUNC_NAME s_scm_fdopen
457 {
458 SCM port;
459
460 SCM_VALIDATE_INT(1,fdes);
461 SCM_VALIDATE_ROSTRING(2,modes);
462 SCM_COERCE_SUBSTR (modes);
463 port = scm_fdes_to_port (SCM_INUM (fdes), SCM_ROCHARS (modes), SCM_BOOL_F);
464 return port;
465 }
466 #undef FUNC_NAME
467
468
469
470 /* Move a port's underlying file descriptor to a given value.
471 * Returns #f if fdes is already the given value.
472 * #t if fdes moved.
473 * MOVE->FDES is implemented in Scheme and calls this primitive.
474 */
475 GUILE_PROC (scm_primitive_move_to_fdes, "primitive-move->fdes", 2, 0, 0,
476 (SCM port, SCM fd),
477 "Moves the underlying file descriptor for @var{port} to the integer
478 value @var{fdes} without changing the revealed count of @var{port}.
479 Any other ports already using this descriptor will be automatically
480 shifted to new descriptors and their revealed counts reset to zero.
481 The return value is @code{#f} if the file descriptor already had the
482 required value or @code{#t} if it was moved.")
483 #define FUNC_NAME s_scm_primitive_move_to_fdes
484 {
485 struct scm_fport *stream;
486 int old_fd;
487 int new_fd;
488 int rv;
489
490 port = SCM_COERCE_OUTPORT (port);
491
492 SCM_VALIDATE_OPFPORT(1,port);
493 SCM_VALIDATE_INT(2,fd);
494 stream = SCM_FSTREAM (port);
495 old_fd = stream->fdes;
496 new_fd = SCM_INUM (fd);
497 if (old_fd == new_fd)
498 {
499 return SCM_BOOL_F;
500 }
501 scm_evict_ports (new_fd);
502 rv = dup2 (old_fd, new_fd);
503 if (rv == -1)
504 SCM_SYSERROR;
505 stream->fdes = new_fd;
506 SCM_SYSCALL (close (old_fd));
507 return SCM_BOOL_T;
508 }
509 #undef FUNC_NAME
510
511 /* Return a list of ports using a given file descriptor. */
512 GUILE_PROC(scm_fdes_to_ports, "fdes->ports", 1, 0, 0,
513 (SCM fd),
514 "Returns a list of existing ports which have @var{fdes} as an
515 underlying file descriptor, without changing their revealed counts.")
516 #define FUNC_NAME s_scm_fdes_to_ports
517 {
518 SCM result = SCM_EOL;
519 int int_fd;
520 int i;
521
522 SCM_VALIDATE_INT_COPY(1,fd,int_fd);
523
524 for (i = 0; i < scm_port_table_size; i++)
525 {
526 if (SCM_OPFPORTP (scm_port_table[i]->port)
527 && ((struct scm_fport *) scm_port_table[i]->stream)->fdes == int_fd)
528 result = scm_cons (scm_port_table[i]->port, result);
529 }
530 return result;
531 }
532 #undef FUNC_NAME
533
534
535 void
536 scm_init_ioext ()
537 {
538 scm_add_feature ("i/o-extensions");
539
540 #include "ioext.x"
541 }
542