lib/standard/file: Added a way to change the buffering for a specified stream
[nit.git] / lib / standard / file.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2004-2008 Jean Privat <jean@pryen.org>
4 # Copyright 2008 Floréal Morandat <morandat@lirmm.fr>
5 # Copyright 2008 Jean-Sébastien Gélinas <calestar@gmail.com>
6 #
7 # This file is free software, which comes along with NIT. This software is
8 # distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
9 # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
10 # PARTICULAR PURPOSE. You can modify it is you want, provided this header
11 # is kept unaltered, and a notification of the changes is added.
12 # You are allowed to redistribute it and sell it, alone or is a part of
13 # another product.
14
15 # File manipulations (create, read, write, etc.)
16 module file
17
18 intrude import stream
19 intrude import ropes
20 import string_search
21 import time
22
23 in "C Header" `{
24 #include <dirent.h>
25 #include <string.h>
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <unistd.h>
29 #include <stdio.h>
30 #include <poll.h>
31 #include <errno.h>
32 `}
33
34 # File Abstract Stream
35 abstract class FStream
36 super IOS
37 # The path of the file.
38 var path: nullable String = null
39
40 # The FILE *.
41 private var file: nullable NativeFile = null
42
43 fun file_stat: FileStat do return _file.file_stat
44
45 # File descriptor of this file
46 fun fd: Int do return _file.fileno
47
48 # Sets the buffering mode for the current FStream
49 #
50 # If the buf_size is <= 0, its value will be 512 by default
51 #
52 # The mode is any of the buffer_mode enumeration in `Sys`:
53 # - buffer_mode_full
54 # - buffer_mode_line
55 # - buffer_mode_none
56 fun set_buffering_mode(buf_size, mode: Int) do
57 if buf_size <= 0 then buf_size = 512
58 if _file.set_buffering_type(buf_size, mode) != 0 then
59 last_error = new IOError("Error while changing buffering type for FStream, returned error {sys.errno.strerror}")
60 end
61 end
62 end
63
64 # File input stream
65 class IFStream
66 super FStream
67 super BufferedIStream
68 super PollableIStream
69 # Misc
70
71 # Open the same file again.
72 # The original path is reused, therefore the reopened file can be a different file.
73 fun reopen
74 do
75 if not eof and not _file.address_is_null then close
76 last_error = null
77 _file = new NativeFile.io_open_read(path.to_cstring)
78 if _file.address_is_null then
79 last_error = new IOError("Error: Opening file at '{path.as(not null)}' failed with '{sys.errno.strerror}'")
80 end_reached = true
81 return
82 end
83 end_reached = false
84 _buffer_pos = 0
85 _buffer.clear
86 end
87
88 redef fun close
89 do
90 if _file.address_is_null then return
91 var i = _file.io_close
92 _buffer.clear
93 end_reached = true
94 end
95
96 redef fun fill_buffer
97 do
98 var nb = _file.io_read(_buffer.items, _buffer.capacity)
99 if nb <= 0 then
100 end_reached = true
101 nb = 0
102 end
103 _buffer.length = nb
104 _buffer_pos = 0
105 end
106
107 # End of file?
108 redef var end_reached: Bool = false
109
110 # Open the file at `path` for reading.
111 init open(path: String)
112 do
113 self.path = path
114 prepare_buffer(10)
115 _file = new NativeFile.io_open_read(path.to_cstring)
116 if _file.address_is_null then
117 last_error = new IOError("Error: Opening file at '{path}' failed with '{sys.errno.strerror}'")
118 end_reached = true
119 end
120 end
121
122 init from_fd(fd: Int) do
123 self.path = ""
124 prepare_buffer(1)
125 _file = fd.fd_to_stream(read_only)
126 if _file.address_is_null then
127 last_error = new IOError("Error: Converting fd {fd} to stream failed with '{sys.errno.strerror}'")
128 end_reached = true
129 end
130 end
131 end
132
133 # File output stream
134 class OFStream
135 super FStream
136 super OStream
137
138 redef fun write(s)
139 do
140 if last_error != null then return
141 if not _is_writable then
142 last_error = new IOError("Cannot write to non-writable stream")
143 return
144 end
145 if s isa FlatText then
146 write_native(s.to_cstring, s.length)
147 else
148 for i in s.substrings do write_native(i.to_cstring, i.length)
149 end
150 _file.flush
151 end
152
153 redef fun close
154 do
155 if _file.address_is_null then
156 if last_error != null then return
157 last_error = new IOError("Cannot close unopened write stream")
158 _is_writable = false
159 return
160 end
161 var i = _file.io_close
162 if i != 0 then
163 last_error = new IOError("Close failed due to error {sys.errno.strerror}")
164 end
165 _is_writable = false
166 end
167 redef var is_writable = false
168
169 # Write `len` bytes from `native`.
170 private fun write_native(native: NativeString, len: Int)
171 do
172 if last_error != null then return
173 if not _is_writable then
174 last_error = new IOError("Cannot write to non-writable stream")
175 return
176 end
177 if _file.address_is_null then
178 last_error = new IOError("Writing on a null stream")
179 _is_writable = false
180 return
181 end
182 var err = _file.io_write(native, len)
183 if err != len then
184 # Big problem
185 last_error = new IOError("Problem in writing : {err} {len} \n")
186 end
187 end
188
189 # Open the file at `path` for writing.
190 init open(path: String)
191 do
192 _file = new NativeFile.io_open_write(path.to_cstring)
193 self.path = path
194 _is_writable = true
195 if _file.address_is_null then
196 last_error = new IOError("Error: Opening file at '{path}' failed with '{sys.errno.strerror}'")
197 is_writable = false
198 end
199 end
200
201 # Creates a new File stream from a file descriptor
202 init from_fd(fd: Int) do
203 self.path = ""
204 _file = fd.fd_to_stream(wipe_write)
205 _is_writable = true
206 if _file.address_is_null then
207 last_error = new IOError("Error: Opening stream from file descriptor {fd} failed with '{sys.errno.strerror}'")
208 _is_writable = false
209 end
210 end
211 end
212
213 redef class Int
214 # Creates a file stream from a file descriptor `fd` using the file access `mode`.
215 #
216 # NOTE: The `mode` specified must be compatible with the one used in the file descriptor.
217 private fun fd_to_stream(mode: NativeString): NativeFile is extern "file_int_fdtostream"
218 end
219
220 # Constant for read-only file streams
221 private fun read_only: NativeString do return "r".to_cstring
222
223 # Constant for write-only file streams
224 #
225 # If a stream is opened on a file with this method,
226 # it will wipe the previous file if any.
227 # Else, it will create the file.
228 private fun wipe_write: NativeString do return "w".to_cstring
229
230 ###############################################################################
231
232 class Stdin
233 super IFStream
234
235 init do
236 _file = new NativeFile.native_stdin
237 path = "/dev/stdin"
238 prepare_buffer(1)
239 end
240
241 redef fun poll_in: Bool is extern "file_stdin_poll_in"
242 end
243
244 class Stdout
245 super OFStream
246 init do
247 _file = new NativeFile.native_stdout
248 path = "/dev/stdout"
249 _is_writable = true
250 end
251 end
252
253 class Stderr
254 super OFStream
255 init do
256 _file = new NativeFile.native_stderr
257 path = "/dev/stderr"
258 _is_writable = true
259 end
260 end
261
262 ###############################################################################
263
264 redef class Streamable
265 # Like `write_to` but take care of creating the file
266 fun write_to_file(filepath: String)
267 do
268 var stream = new OFStream.open(filepath)
269 write_to(stream)
270 stream.close
271 end
272 end
273
274 redef class String
275 # return true if a file with this names exists
276 fun file_exists: Bool do return to_cstring.file_exists
277
278 # The status of a file. see POSIX stat(2).
279 fun file_stat: FileStat do return to_cstring.file_stat
280
281 # The status of a file or of a symlink. see POSIX lstat(2).
282 fun file_lstat: FileStat do return to_cstring.file_lstat
283
284 # Remove a file, return true if success
285 fun file_delete: Bool do return to_cstring.file_delete
286
287 # Copy content of file at `self` to `dest`
288 fun file_copy_to(dest: String)
289 do
290 var input = new IFStream.open(self)
291 var output = new OFStream.open(dest)
292
293 while not input.eof do
294 var buffer = input.read(1024)
295 output.write buffer
296 end
297
298 input.close
299 output.close
300 end
301
302 # Remove the trailing extension `ext`.
303 #
304 # `ext` usually starts with a dot but could be anything.
305 #
306 # assert "file.txt".strip_extension(".txt") == "file"
307 # assert "file.txt".strip_extension("le.txt") == "fi"
308 # assert "file.txt".strip_extension("xt") == "file.t"
309 #
310 # if `ext` is not present, `self` is returned unmodified.
311 #
312 # assert "file.txt".strip_extension(".tar.gz") == "file.txt"
313 fun strip_extension(ext: String): String
314 do
315 if has_suffix(ext) then
316 return substring(0, length - ext.length)
317 end
318 return self
319 end
320
321 # Extract the basename of a path and remove the extension
322 #
323 # assert "/path/to/a_file.ext".basename(".ext") == "a_file"
324 # assert "path/to/a_file.ext".basename(".ext") == "a_file"
325 # assert "path/to".basename(".ext") == "to"
326 # assert "path/to/".basename(".ext") == "to"
327 # assert "path".basename("") == "path"
328 # assert "/path".basename("") == "path"
329 # assert "/".basename("") == "/"
330 # assert "".basename("") == ""
331 fun basename(ext: String): String
332 do
333 var l = length - 1 # Index of the last char
334 while l > 0 and self.chars[l] == '/' do l -= 1 # remove all trailing `/`
335 if l == 0 then return "/"
336 var pos = chars.last_index_of_from('/', l)
337 var n = self
338 if pos >= 0 then
339 n = substring(pos+1, l-pos)
340 end
341 return n.strip_extension(ext)
342 end
343
344 # Extract the dirname of a path
345 #
346 # assert "/path/to/a_file.ext".dirname == "/path/to"
347 # assert "path/to/a_file.ext".dirname == "path/to"
348 # assert "path/to".dirname == "path"
349 # assert "path/to/".dirname == "path"
350 # assert "path".dirname == "."
351 # assert "/path".dirname == "/"
352 # assert "/".dirname == "/"
353 # assert "".dirname == "."
354 fun dirname: String
355 do
356 var l = length - 1 # Index of the last char
357 while l > 0 and self.chars[l] == '/' do l -= 1 # remove all trailing `/`
358 var pos = chars.last_index_of_from('/', l)
359 if pos > 0 then
360 return substring(0, pos)
361 else if pos == 0 then
362 return "/"
363 else
364 return "."
365 end
366 end
367
368 # Return the canonicalized absolute pathname (see POSIX function `realpath`)
369 fun realpath: String do
370 var cs = to_cstring.file_realpath
371 var res = cs.to_s_with_copy
372 # cs.free_malloc # FIXME memory leak
373 return res
374 end
375
376 # Simplify a file path by remove useless ".", removing "//", and resolving ".."
377 # ".." are not resolved if they start the path
378 # starting "/" is not removed
379 # trainling "/" is removed
380 #
381 # Note that the method only wonrk on the string:
382 # * no I/O access is performed
383 # * the validity of the path is not checked
384 #
385 # assert "some/./complex/../../path/from/../to/a////file//".simplify_path == "path/to/a/file"
386 # assert "../dir/file".simplify_path == "../dir/file"
387 # assert "dir/../../".simplify_path == ".."
388 # assert "dir/..".simplify_path == "."
389 # assert "//absolute//path/".simplify_path == "/absolute/path"
390 # assert "//absolute//../".simplify_path == "/"
391 fun simplify_path: String
392 do
393 var a = self.split_with("/")
394 var a2 = new Array[String]
395 for x in a do
396 if x == "." then continue
397 if x == "" and not a2.is_empty then continue
398 if x == ".." and not a2.is_empty and a2.last != ".." then
399 a2.pop
400 continue
401 end
402 a2.push(x)
403 end
404 if a2.is_empty then return "."
405 if a2.length == 1 and a2.first == "" then return "/"
406 return a2.join("/")
407 end
408
409 # Correctly join two path using the directory separator.
410 #
411 # Using a standard "{self}/{path}" does not work in the following cases:
412 #
413 # * `self` is empty.
414 # * `path` ends with `'/'`.
415 # * `path` starts with `'/'`.
416 #
417 # This method ensures that the join is valid.
418 #
419 # assert "hello".join_path("world") == "hello/world"
420 # assert "hel/lo".join_path("wor/ld") == "hel/lo/wor/ld"
421 # assert "".join_path("world") == "world"
422 # assert "hello".join_path("/world") == "/world"
423 # assert "hello/".join_path("world") == "hello/world"
424 # assert "hello/".join_path("/world") == "/world"
425 #
426 # Note: You may want to use `simplify_path` on the result.
427 #
428 # Note: This method works only with POSIX paths.
429 fun join_path(path: String): String
430 do
431 if path.is_empty then return self
432 if self.is_empty then return path
433 if path.chars[0] == '/' then return path
434 if self.last == '/' then return "{self}{path}"
435 return "{self}/{path}"
436 end
437
438 # Convert the path (`self`) to a program name.
439 #
440 # Ensure the path (`self`) will be treated as-is by POSIX shells when it is
441 # used as a program name. In order to do that, prepend `./` if needed.
442 #
443 # assert "foo".to_program_name == "./foo"
444 # assert "/foo".to_program_name == "/foo"
445 # assert "".to_program_name == "./" # At least, your shell will detect the error.
446 fun to_program_name: String do
447 if self.has_prefix("/") then
448 return self
449 else
450 return "./{self}"
451 end
452 end
453
454 # Alias for `join_path`
455 #
456 # assert "hello" / "world" == "hello/world"
457 # assert "hel/lo" / "wor/ld" == "hel/lo/wor/ld"
458 # assert "" / "world" == "world"
459 # assert "/hello" / "/world" == "/world"
460 #
461 # This operator is quite useful for chaining changes of path.
462 # The next one being relative to the previous one.
463 #
464 # var a = "foo"
465 # var b = "/bar"
466 # var c = "baz/foobar"
467 # assert a/b/c == "/bar/baz/foobar"
468 fun /(path: String): String do return join_path(path)
469
470 # Returns the relative path needed to go from `self` to `dest`.
471 #
472 # assert "/foo/bar".relpath("/foo/baz") == "../baz"
473 # assert "/foo/bar".relpath("/baz/bar") == "../../baz/bar"
474 #
475 # If `self` or `dest` is relative, they are considered relatively to `getcwd`.
476 #
477 # In some cases, the result is still independent of the current directory:
478 #
479 # assert "foo/bar".relpath("..") == "../../.."
480 #
481 # In other cases, parts of the current directory may be exhibited:
482 #
483 # var p = "../foo/bar".relpath("baz")
484 # var c = getcwd.basename("")
485 # assert p == "../../{c}/baz"
486 #
487 # For path resolution independent of the current directory (eg. for paths in URL),
488 # or to use an other starting directory than the current directory,
489 # just force absolute paths:
490 #
491 # var start = "/a/b/c/d"
492 # var p2 = (start/"../foo/bar").relpath(start/"baz")
493 # assert p2 == "../../d/baz"
494 #
495 #
496 # Neither `self` or `dest` has to be real paths or to exist in directories since
497 # the resolution is only done with string manipulations and without any access to
498 # the underlying file system.
499 #
500 # If `self` and `dest` are the same directory, the empty string is returned:
501 #
502 # assert "foo".relpath("foo") == ""
503 # assert "foo/../bar".relpath("bar") == ""
504 #
505 # The empty string and "." designate both the current directory:
506 #
507 # assert "".relpath("foo/bar") == "foo/bar"
508 # assert ".".relpath("foo/bar") == "foo/bar"
509 # assert "foo/bar".relpath("") == "../.."
510 # assert "/" + "/".relpath(".") == getcwd
511 fun relpath(dest: String): String
512 do
513 var cwd = getcwd
514 var from = (cwd/self).simplify_path.split("/")
515 if from.last.is_empty then from.pop # case for the root directory
516 var to = (cwd/dest).simplify_path.split("/")
517 if to.last.is_empty then to.pop # case for the root directory
518
519 # Remove common prefixes
520 while not from.is_empty and not to.is_empty and from.first == to.first do
521 from.shift
522 to.shift
523 end
524
525 # Result is going up in `from` with ".." then going down following `to`
526 var from_len = from.length
527 if from_len == 0 then return to.join("/")
528 var up = "../"*(from_len-1) + ".."
529 if to.is_empty then return up
530 var res = up + "/" + to.join("/")
531 return res
532 end
533
534 # Create a directory (and all intermediate directories if needed)
535 fun mkdir
536 do
537 var dirs = self.split_with("/")
538 var path = new FlatBuffer
539 if dirs.is_empty then return
540 if dirs[0].is_empty then
541 # it was a starting /
542 path.add('/')
543 end
544 for d in dirs do
545 if d.is_empty then continue
546 path.append(d)
547 path.add('/')
548 path.to_s.to_cstring.file_mkdir
549 end
550 end
551
552 # Delete a directory and all of its content, return `true` on success
553 #
554 # Does not go through symbolic links and may get stuck in a cycle if there
555 # is a cycle in the filesystem.
556 fun rmdir: Bool
557 do
558 var ok = true
559 for file in self.files do
560 var file_path = self.join_path(file)
561 var stat = file_path.file_lstat
562 if stat.is_dir then
563 ok = file_path.rmdir and ok
564 else
565 ok = file_path.file_delete and ok
566 end
567 stat.free
568 end
569
570 # Delete the directory itself
571 if ok then to_cstring.rmdir
572
573 return ok
574 end
575
576 # Change the current working directory
577 #
578 # "/etc".chdir
579 # assert getcwd == "/etc"
580 # "..".chdir
581 # assert getcwd == "/"
582 #
583 # TODO: errno
584 fun chdir do to_cstring.file_chdir
585
586 # Return right-most extension (without the dot)
587 #
588 # Only the last extension is returned.
589 # There is no special case for combined extensions.
590 #
591 # assert "file.txt".file_extension == "txt"
592 # assert "file.tar.gz".file_extension == "gz"
593 #
594 # For file without extension, `null` is returned.
595 # Hoever, for trailing dot, `""` is returned.
596 #
597 # assert "file".file_extension == null
598 # assert "file.".file_extension == ""
599 #
600 # The starting dot of hidden files is never considered.
601 #
602 # assert ".file.txt".file_extension == "txt"
603 # assert ".file".file_extension == null
604 fun file_extension: nullable String
605 do
606 var last_slash = chars.last_index_of('.')
607 if last_slash > 0 then
608 return substring( last_slash+1, length )
609 else
610 return null
611 end
612 end
613
614 # returns files contained within the directory represented by self
615 fun files : Set[ String ] is extern import HashSet[String], HashSet[String].add, NativeString.to_s, String.to_cstring, HashSet[String].as(Set[String]) `{
616 char *dir_path;
617 DIR *dir;
618
619 dir_path = String_to_cstring( recv );
620 if ((dir = opendir(dir_path)) == NULL)
621 {
622 perror( dir_path );
623 exit( 1 );
624 }
625 else
626 {
627 HashSet_of_String results;
628 String file_name;
629 struct dirent *de;
630
631 results = new_HashSet_of_String();
632
633 while ( ( de = readdir( dir ) ) != NULL )
634 if ( strcmp( de->d_name, ".." ) != 0 &&
635 strcmp( de->d_name, "." ) != 0 )
636 {
637 file_name = NativeString_to_s( strdup( de->d_name ) );
638 HashSet_of_String_add( results, file_name );
639 }
640
641 closedir( dir );
642 return HashSet_of_String_as_Set_of_String( results );
643 }
644 `}
645 end
646
647 redef class NativeString
648 private fun file_exists: Bool is extern "string_NativeString_NativeString_file_exists_0"
649 private fun file_stat: FileStat is extern "string_NativeString_NativeString_file_stat_0"
650 private fun file_lstat: FileStat `{
651 struct stat* stat_element;
652 int res;
653 stat_element = malloc(sizeof(struct stat));
654 res = lstat(recv, stat_element);
655 if (res == -1) return NULL;
656 return stat_element;
657 `}
658 private fun file_mkdir: Bool is extern "string_NativeString_NativeString_file_mkdir_0"
659 private fun rmdir: Bool `{ return rmdir(recv); `}
660 private fun file_delete: Bool is extern "string_NativeString_NativeString_file_delete_0"
661 private fun file_chdir is extern "string_NativeString_NativeString_file_chdir_0"
662 private fun file_realpath: NativeString is extern "file_NativeString_realpath"
663 end
664
665 # This class is system dependent ... must reify the vfs
666 extern class FileStat `{ struct stat * `}
667 # Returns the permission bits of file
668 fun mode: Int is extern "file_FileStat_FileStat_mode_0"
669 # Returns the last access time
670 fun atime: Int is extern "file_FileStat_FileStat_atime_0"
671 # Returns the last status change time
672 fun ctime: Int is extern "file_FileStat_FileStat_ctime_0"
673 # Returns the last modification time
674 fun mtime: Int is extern "file_FileStat_FileStat_mtime_0"
675 # Returns the size
676 fun size: Int is extern "file_FileStat_FileStat_size_0"
677
678 # Returns true if it is a regular file (not a device file, pipe, sockect, ...)
679 fun is_reg: Bool `{ return S_ISREG(recv->st_mode); `}
680 # Returns true if it is a directory
681 fun is_dir: Bool `{ return S_ISDIR(recv->st_mode); `}
682 # Returns true if it is a character device
683 fun is_chr: Bool `{ return S_ISCHR(recv->st_mode); `}
684 # Returns true if it is a block device
685 fun is_blk: Bool `{ return S_ISBLK(recv->st_mode); `}
686 # Returns true if the type is fifo
687 fun is_fifo: Bool `{ return S_ISFIFO(recv->st_mode); `}
688 # Returns true if the type is a link
689 fun is_lnk: Bool `{ return S_ISLNK(recv->st_mode); `}
690 # Returns true if the type is a socket
691 fun is_sock: Bool `{ return S_ISSOCK(recv->st_mode); `}
692 end
693
694 # Instance of this class are standard FILE * pointers
695 private extern class NativeFile `{ FILE* `}
696 fun io_read(buf: NativeString, len: Int): Int is extern "file_NativeFile_NativeFile_io_read_2"
697 fun io_write(buf: NativeString, len: Int): Int is extern "file_NativeFile_NativeFile_io_write_2"
698 fun io_close: Int is extern "file_NativeFile_NativeFile_io_close_0"
699 fun file_stat: FileStat is extern "file_NativeFile_NativeFile_file_stat_0"
700 fun fileno: Int `{ return fileno(recv); `}
701 # Flushes the buffer, forcing the write operation
702 fun flush: Int is extern "fflush"
703 # Used to specify how the buffering will be handled for the current stream.
704 fun set_buffering_type(buf_length: Int, mode: Int): Int is extern "file_NativeFile_NativeFile_set_buffering_type_0"
705
706 new io_open_read(path: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_read_1"
707 new io_open_write(path: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_write_1"
708 new native_stdin is extern "file_NativeFileCapable_NativeFileCapable_native_stdin_0"
709 new native_stdout is extern "file_NativeFileCapable_NativeFileCapable_native_stdout_0"
710 new native_stderr is extern "file_NativeFileCapable_NativeFileCapable_native_stderr_0"
711 end
712
713 redef class Sys
714
715 # Standard input
716 var stdin: PollableIStream = new Stdin is protected writable
717
718 # Standard output
719 var stdout: OStream = new Stdout is protected writable
720
721 # Standard output for errors
722 var stderr: OStream = new Stderr is protected writable
723
724 # Enumeration for buffer mode full (flushes when buffer is full)
725 fun buffer_mode_full: Int is extern "file_Sys_Sys_buffer_mode_full_0"
726 # Enumeration for buffer mode line (flushes when a `\n` is encountered)
727 fun buffer_mode_line: Int is extern "file_Sys_Sys_buffer_mode_line_0"
728 # Enumeration for buffer mode none (flushes ASAP when something is written)
729 fun buffer_mode_none: Int is extern "file_Sys_Sys_buffer_mode_none_0"
730
731 # returns first available stream to read or write to
732 # return null on interruption (possibly a signal)
733 protected fun poll( streams : Sequence[FStream] ) : nullable FStream
734 do
735 var in_fds = new Array[Int]
736 var out_fds = new Array[Int]
737 var fd_to_stream = new HashMap[Int,FStream]
738 for s in streams do
739 var fd = s.fd
740 if s isa IFStream then in_fds.add( fd )
741 if s isa OFStream then out_fds.add( fd )
742
743 fd_to_stream[fd] = s
744 end
745
746 var polled_fd = intern_poll( in_fds, out_fds )
747
748 if polled_fd == null then
749 return null
750 else
751 return fd_to_stream[polled_fd]
752 end
753 end
754
755 private fun intern_poll(in_fds: Array[Int], out_fds: Array[Int]) : nullable Int is extern import Array[Int].length, Array[Int].[], Int.as(nullable Int) `{
756 int in_len, out_len, total_len;
757 struct pollfd *c_fds;
758 sigset_t sigmask;
759 int i;
760 int first_polled_fd = -1;
761 int result;
762
763 in_len = Array_of_Int_length( in_fds );
764 out_len = Array_of_Int_length( out_fds );
765 total_len = in_len + out_len;
766 c_fds = malloc( sizeof(struct pollfd) * total_len );
767
768 /* input streams */
769 for ( i=0; i<in_len; i ++ ) {
770 int fd;
771 fd = Array_of_Int__index( in_fds, i );
772
773 c_fds[i].fd = fd;
774 c_fds[i].events = POLLIN;
775 }
776
777 /* output streams */
778 for ( i=0; i<out_len; i ++ ) {
779 int fd;
780 fd = Array_of_Int__index( out_fds, i );
781
782 c_fds[i].fd = fd;
783 c_fds[i].events = POLLOUT;
784 }
785
786 /* poll all fds, unlimited timeout */
787 result = poll( c_fds, total_len, -1 );
788
789 if ( result > 0 ) {
790 /* analyse results */
791 for ( i=0; i<total_len; i++ )
792 if ( c_fds[i].revents & c_fds[i].events || /* awaited event */
793 c_fds[i].revents & POLLHUP ) /* closed */
794 {
795 first_polled_fd = c_fds[i].fd;
796 break;
797 }
798
799 return Int_as_nullable( first_polled_fd );
800 }
801 else if ( result < 0 )
802 fprintf( stderr, "Error in Stream:poll: %s\n", strerror( errno ) );
803
804 return null_Int();
805 `}
806
807 end
808
809 # Print `objects` on the standard output (`stdout`).
810 protected fun printn(objects: Object...)
811 do
812 sys.stdout.write(objects.to_s)
813 end
814
815 # Print an `object` on the standard output (`stdout`) and add a newline.
816 protected fun print(object: Object)
817 do
818 sys.stdout.write(object.to_s)
819 sys.stdout.write("\n")
820 end
821
822 # Read a character from the standard input (`stdin`).
823 protected fun getc: Char
824 do
825 return sys.stdin.read_char.ascii
826 end
827
828 # Read a line from the standard input (`stdin`).
829 protected fun gets: String
830 do
831 return sys.stdin.read_line
832 end
833
834 # Return the working (current) directory
835 protected fun getcwd: String do return file_getcwd.to_s
836 private fun file_getcwd: NativeString is extern "string_NativeString_NativeString_file_getcwd_0"