1 # This file is part of NIT ( http://www.nitlanguage.org ).
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>
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
15 # File manipulations (create, read, write, etc.)
27 #include <sys/types.h>
35 # `Stream` used to interact with a File or FileDescriptor
36 abstract class FileStream
38 # The path of the file.
39 var path
: nullable String = null
42 private var file
: nullable NativeFile = null
44 # The status of a file. see POSIX stat(2).
45 fun file_stat
: NativeFileStat do return _file
.file_stat
47 # File descriptor of this file
48 fun fd
: Int do return _file
.fileno
52 if _file
== null then return
53 if _file
.address_is_null
then
54 if last_error
!= null then return
55 last_error
= new IOError("Cannot close unopened file")
58 var i
= _file
.io_close
60 last_error
= new IOError("Close failed due to error {sys.errno.strerror}")
65 # Sets the buffering mode for the current FileStream
67 # If the buf_size is <= 0, its value will be 512 by default
69 # The mode is any of the buffer_mode enumeration in `Sys`:
73 fun set_buffering_mode
(buf_size
, mode
: Int) do
74 if buf_size
<= 0 then buf_size
= 512
75 if _file
.set_buffering_type
(buf_size
, mode
) != 0 then
76 last_error
= new IOError("Error while changing buffering type for FileStream, returned error {sys.errno.strerror}")
81 # `Stream` that can read from a File
88 # Open the same file again.
89 # The original path is reused, therefore the reopened file can be a different file.
92 if not eof
and not _file
.address_is_null
then close
94 _file
= new NativeFile.io_open_read
(path
.to_cstring
)
95 if _file
.address_is_null
then
96 last_error
= new IOError("Error: Opening file at '{path.as(not null)}' failed with '{sys.errno.strerror}'")
112 redef fun fill_buffer
114 var nb
= _file
.io_read
(_buffer
.items
, _buffer
.capacity
)
124 redef var end_reached
: Bool = false
126 # Open the file at `path` for reading.
127 init open
(path
: String)
131 _file
= new NativeFile.io_open_read
(path
.to_cstring
)
132 if _file
.address_is_null
then
133 last_error
= new IOError("Error: Opening file at '{path}' failed with '{sys.errno.strerror}'")
138 # Creates a new File stream from a file descriptor
139 init from_fd
(fd
: Int) do
142 _file
= fd
.fd_to_stream
(read_only
)
143 if _file
.address_is_null
then
144 last_error
= new IOError("Error: Converting fd {fd} to stream failed with '{sys.errno.strerror}'")
150 # `Stream` that can write to a File
157 if last_error
!= null then return
158 if not _is_writable
then
159 last_error
= new IOError("Cannot write to non-writable stream")
162 if s
isa FlatText then
163 write_native
(s
.to_cstring
, s
.length
)
165 for i
in s
.substrings
do write_native
(i
.to_cstring
, i
.length
)
174 redef var is_writable
= false
176 # Write `len` bytes from `native`.
177 private fun write_native
(native
: NativeString, len
: Int)
179 if last_error
!= null then return
180 if not _is_writable
then
181 last_error
= new IOError("Cannot write to non-writable stream")
184 if _file
.address_is_null
then
185 last_error
= new IOError("Writing on a null stream")
189 var err
= _file
.io_write
(native
, len
)
192 last_error
= new IOError("Problem in writing : {err} {len} \n")
196 # Open the file at `path` for writing.
197 init open
(path
: String)
199 _file
= new NativeFile.io_open_write
(path
.to_cstring
)
202 if _file
.address_is_null
then
203 last_error
= new IOError("Error: Opening file at '{path}' failed with '{sys.errno.strerror}'")
208 # Creates a new File stream from a file descriptor
209 init from_fd
(fd
: Int) do
211 _file
= fd
.fd_to_stream
(wipe_write
)
213 if _file
.address_is_null
then
214 last_error
= new IOError("Error: Opening stream from file descriptor {fd} failed with '{sys.errno.strerror}'")
221 # Creates a file stream from a file descriptor `fd` using the file access `mode`.
223 # NOTE: The `mode` specified must be compatible with the one used in the file descriptor.
224 private fun fd_to_stream
(mode
: NativeString): NativeFile is extern "file_int_fdtostream"
227 # Constant for read-only file streams
228 private fun read_only
: NativeString do return "r".to_cstring
230 # Constant for write-only file streams
232 # If a stream is opened on a file with this method,
233 # it will wipe the previous file if any.
234 # Else, it will create the file.
235 private fun wipe_write
: NativeString do return "w".to_cstring
237 ###############################################################################
239 # Standard input stream.
244 _file
= new NativeFile.native_stdin
249 redef fun poll_in
: Bool is extern "file_stdin_poll_in"
252 # Standard output stream.
256 _file
= new NativeFile.native_stdout
259 set_buffering_mode
(256, sys
.buffer_mode_line
)
263 # Standard error stream.
267 _file
= new NativeFile.native_stderr
273 ###############################################################################
276 # Like `write_to` but take care of creating the file
277 fun write_to_file
(filepath
: String)
279 var stream
= new FileWriter.open
(filepath
)
285 # Utility class to access file system services
287 # Usually created with `Text::to_path`.
290 private var path
: String
293 redef fun to_s
do return path
295 # Name of the file name at `to_s`
298 # var path = "/tmp/somefile".to_path
299 # assert path.filename == "somefile"
301 var filename
: String = path
.basename
("") is lazy
303 # Does the file at `path` exists?
304 fun exists
: Bool do return stat
!= null
306 # Information on the file at `self` following symbolic links
308 # Returns `null` if there is no file at `self`.
311 # var p = "/tmp/".to_path
313 # if stat != null then # Does `p` exist?
314 # print "It's size is {stat.size}"
315 # if stat.is_dir then print "It's a directory"
318 fun stat
: nullable FileStat
320 var stat
= path
.to_cstring
.file_stat
321 if stat
.address_is_null
then return null
322 return new FileStat(stat
)
325 # Information on the file or link at `self`
327 # Do not follow symbolic links.
328 fun link_stat
: nullable FileStat
330 var stat
= path
.to_cstring
.file_lstat
331 if stat
.address_is_null
then return null
332 return new FileStat(stat
)
335 # Delete a file from the file system, return `true` on success
338 fun delete
: Bool do return path
.to_cstring
.file_delete
340 # Copy content of file at `path` to `dest`
346 var output
= dest
.open_wo
348 while not input
.eof
do
349 var buffer
= input
.read
(1024)
357 # Open this file for reading
359 # Require: `exists and not link_stat.is_dir`
360 fun open_ro
: FileReader
362 # TODO manage streams error when they are merged
363 return new FileReader.open
(path
)
366 # Open this file for writing
368 # Require: `not exists or not stat.is_dir`
369 fun open_wo
: FileWriter
371 # TODO manage streams error when they are merged
372 return new FileWriter.open
(path
)
375 # Read all the content of the file
378 # var content = "/etc/issue".to_path.read_all
382 # See `Reader::read_all` for details.
391 # Read all the lines of the file
394 # var lines = "/etc/passwd".to_path.read_lines
396 # print "{lines.length} users"
399 # var fields = l.split(":")
400 # print "name={fields[0]} uid={fields[2]}"
404 # See `Reader::read_lines` for details.
405 fun read_lines
: Array[String]
408 var res
= s
.read_lines
413 # Return an iterator on each line of the file
416 # for l in "/etc/passwd".to_path.each_line do
417 # var fields = l.split(":")
418 # print "name={fields[0]} uid={fields[2]}"
422 # Note: the stream is automatically closed at the end of the file (see `LineIterator::close_on_finish`)
424 # See `Reader::each_line` for details.
425 fun each_line
: LineIterator
428 var res
= s
.each_line
429 res
.close_on_finish
= true
434 # Lists the name of the files contained within the directory at `path`
436 # Require: `exists and is_dir`
437 fun files
: Array[Path]
439 var files
= new Array[Path]
440 for filename
in path
.files
do
441 files
.add
new Path(path
/ filename
)
446 # Delete a directory and all of its content, return `true` on success
448 # Does not go through symbolic links and may get stuck in a cycle if there
449 # is a cycle in the file system.
453 for file
in self.files
do
454 var stat
= file
.link_stat
456 ok
= file
.rmdir
and ok
458 ok
= file
.delete
and ok
462 # Delete the directory itself
463 if ok
then path
.to_cstring
.rmdir
468 redef fun ==(other
) do return other
isa Path and path
.simplify_path
== other
.path
.simplify_path
469 redef fun hash
do return path
.simplify_path
.hash
472 # Information on a file
474 # Created by `Path::stat` and `Path::link_stat`.
476 # The information within this class is gathered when the instance is initialized
477 # it will not be updated if the targeted file is modified.
483 # The low-level status of a file
486 private var stat
: NativeFileStat
488 private var finalized
= false
492 if not finalized
then
498 # Returns the last access time in seconds since Epoch
499 fun last_access_time
: Int
505 # Returns the last modification time in seconds since Epoch
506 fun last_modification_time
: Int
512 # Size of the file at `path`
519 # Is this a regular file and not a device file, pipe, socket, etc.?
526 # Is this a directory?
533 # Is this a symbolic link?
540 # FIXME Make the following POSIX only? or implement in some other way on Windows
542 # Returns the last status change time in seconds since Epoch
543 fun last_status_change_time
: Int
549 # Returns the permission bits of file
556 # Is this a character device?
563 # Is this a block device?
570 # Is this a FIFO pipe?
577 # Is this a UNIX socket
586 # Access file system related services on the path at `self`
587 fun to_path
: Path do return new Path(to_s
)
591 # return true if a file with this names exists
592 fun file_exists
: Bool do return to_cstring
.file_exists
594 # The status of a file. see POSIX stat(2).
595 fun file_stat
: NativeFileStat do return to_cstring
.file_stat
597 # The status of a file or of a symlink. see POSIX lstat(2).
598 fun file_lstat
: NativeFileStat do return to_cstring
.file_lstat
600 # Remove a file, return true if success
601 fun file_delete
: Bool do return to_cstring
.file_delete
603 # Copy content of file at `self` to `dest`
604 fun file_copy_to
(dest
: String) do to_path
.copy
(dest
.to_path
)
606 # Remove the trailing extension `ext`.
608 # `ext` usually starts with a dot but could be anything.
610 # assert "file.txt".strip_extension(".txt") == "file"
611 # assert "file.txt".strip_extension("le.txt") == "fi"
612 # assert "file.txt".strip_extension("xt") == "file.t"
614 # if `ext` is not present, `self` is returned unmodified.
616 # assert "file.txt".strip_extension(".tar.gz") == "file.txt"
617 fun strip_extension
(ext
: String): String
619 if has_suffix
(ext
) then
620 return substring
(0, length
- ext
.length
)
625 # Extract the basename of a path and remove the extension
627 # assert "/path/to/a_file.ext".basename(".ext") == "a_file"
628 # assert "path/to/a_file.ext".basename(".ext") == "a_file"
629 # assert "path/to".basename(".ext") == "to"
630 # assert "path/to/".basename(".ext") == "to"
631 # assert "path".basename("") == "path"
632 # assert "/path".basename("") == "path"
633 # assert "/".basename("") == "/"
634 # assert "".basename("") == ""
635 fun basename
(ext
: String): String
637 var l
= length
- 1 # Index of the last char
638 while l
> 0 and self.chars
[l
] == '/' do l
-= 1 # remove all trailing `/`
639 if l
== 0 then return "/"
640 var pos
= chars
.last_index_of_from
('/', l
)
643 n
= substring
(pos
+1, l-pos
)
645 return n
.strip_extension
(ext
)
648 # Extract the dirname of a path
650 # assert "/path/to/a_file.ext".dirname == "/path/to"
651 # assert "path/to/a_file.ext".dirname == "path/to"
652 # assert "path/to".dirname == "path"
653 # assert "path/to/".dirname == "path"
654 # assert "path".dirname == "."
655 # assert "/path".dirname == "/"
656 # assert "/".dirname == "/"
657 # assert "".dirname == "."
660 var l
= length
- 1 # Index of the last char
661 while l
> 0 and self.chars
[l
] == '/' do l
-= 1 # remove all trailing `/`
662 var pos
= chars
.last_index_of_from
('/', l
)
664 return substring
(0, pos
)
665 else if pos
== 0 then
672 # Return the canonicalized absolute pathname (see POSIX function `realpath`)
673 fun realpath
: String do
674 var cs
= to_cstring
.file_realpath
675 var res
= cs
.to_s_with_copy
676 # cs.free_malloc # FIXME memory leak
680 # Simplify a file path by remove useless ".", removing "//", and resolving ".."
681 # ".." are not resolved if they start the path
682 # starting "/" is not removed
683 # trainling "/" is removed
685 # Note that the method only wonrk on the string:
687 # * no I/O access is performed
688 # * the validity of the path is not checked
691 # assert "some/./complex/../../path/from/../to/a////file//".simplify_path == "path/to/a/file"
692 # assert "../dir/file".simplify_path == "../dir/file"
693 # assert "dir/../../".simplify_path == ".."
694 # assert "dir/..".simplify_path == "."
695 # assert "//absolute//path/".simplify_path == "/absolute/path"
696 # assert "//absolute//../".simplify_path == "/"
698 fun simplify_path
: String
700 var a
= self.split_with
("/")
701 var a2
= new Array[String]
703 if x
== "." then continue
704 if x
== "" and not a2
.is_empty
then continue
705 if x
== ".." and not a2
.is_empty
and a2
.last
!= ".." then
711 if a2
.is_empty
then return "."
712 if a2
.length
== 1 and a2
.first
== "" then return "/"
716 # Correctly join two path using the directory separator.
718 # Using a standard "{self}/{path}" does not work in the following cases:
721 # * `path` ends with `'/'`.
722 # * `path` starts with `'/'`.
724 # This method ensures that the join is valid.
726 # assert "hello".join_path("world") == "hello/world"
727 # assert "hel/lo".join_path("wor/ld") == "hel/lo/wor/ld"
728 # assert "".join_path("world") == "world"
729 # assert "hello".join_path("/world") == "/world"
730 # assert "hello/".join_path("world") == "hello/world"
731 # assert "hello/".join_path("/world") == "/world"
733 # Note: You may want to use `simplify_path` on the result.
735 # Note: This method works only with POSIX paths.
736 fun join_path
(path
: String): String
738 if path
.is_empty
then return self
739 if self.is_empty
then return path
740 if path
.chars
[0] == '/' then return path
741 if self.last
== '/' then return "{self}{path}"
742 return "{self}/{path}"
745 # Convert the path (`self`) to a program name.
747 # Ensure the path (`self`) will be treated as-is by POSIX shells when it is
748 # used as a program name. In order to do that, prepend `./` if needed.
750 # assert "foo".to_program_name == "./foo"
751 # assert "/foo".to_program_name == "/foo"
752 # assert "".to_program_name == "./" # At least, your shell will detect the error.
753 fun to_program_name
: String do
754 if self.has_prefix
("/") then
761 # Alias for `join_path`
763 # assert "hello" / "world" == "hello/world"
764 # assert "hel/lo" / "wor/ld" == "hel/lo/wor/ld"
765 # assert "" / "world" == "world"
766 # assert "/hello" / "/world" == "/world"
768 # This operator is quite useful for chaining changes of path.
769 # The next one being relative to the previous one.
773 # var c = "baz/foobar"
774 # assert a/b/c == "/bar/baz/foobar"
775 fun /(path
: String): String do return join_path
(path
)
777 # Returns the relative path needed to go from `self` to `dest`.
779 # assert "/foo/bar".relpath("/foo/baz") == "../baz"
780 # assert "/foo/bar".relpath("/baz/bar") == "../../baz/bar"
782 # If `self` or `dest` is relative, they are considered relatively to `getcwd`.
784 # In some cases, the result is still independent of the current directory:
786 # assert "foo/bar".relpath("..") == "../../.."
788 # In other cases, parts of the current directory may be exhibited:
790 # var p = "../foo/bar".relpath("baz")
791 # var c = getcwd.basename("")
792 # assert p == "../../{c}/baz"
794 # For path resolution independent of the current directory (eg. for paths in URL),
795 # or to use an other starting directory than the current directory,
796 # just force absolute paths:
798 # var start = "/a/b/c/d"
799 # var p2 = (start/"../foo/bar").relpath(start/"baz")
800 # assert p2 == "../../d/baz"
803 # Neither `self` or `dest` has to be real paths or to exist in directories since
804 # the resolution is only done with string manipulations and without any access to
805 # the underlying file system.
807 # If `self` and `dest` are the same directory, the empty string is returned:
809 # assert "foo".relpath("foo") == ""
810 # assert "foo/../bar".relpath("bar") == ""
812 # The empty string and "." designate both the current directory:
814 # assert "".relpath("foo/bar") == "foo/bar"
815 # assert ".".relpath("foo/bar") == "foo/bar"
816 # assert "foo/bar".relpath("") == "../.."
817 # assert "/" + "/".relpath(".") == getcwd
818 fun relpath
(dest
: String): String
821 var from
= (cwd
/self).simplify_path
.split
("/")
822 if from
.last
.is_empty
then from
.pop
# case for the root directory
823 var to
= (cwd
/dest
).simplify_path
.split
("/")
824 if to
.last
.is_empty
then to
.pop
# case for the root directory
826 # Remove common prefixes
827 while not from
.is_empty
and not to
.is_empty
and from
.first
== to
.first
do
832 # Result is going up in `from` with ".." then going down following `to`
833 var from_len
= from
.length
834 if from_len
== 0 then return to
.join
("/")
835 var up
= "../"*(from_len-1
) + ".."
836 if to
.is_empty
then return up
837 var res
= up
+ "/" + to
.join
("/")
841 # Create a directory (and all intermediate directories if needed)
844 var dirs
= self.split_with
("/")
845 var path
= new FlatBuffer
846 if dirs
.is_empty
then return
847 if dirs
[0].is_empty
then
848 # it was a starting /
852 if d
.is_empty
then continue
855 path
.to_s
.to_cstring
.file_mkdir
859 # Delete a directory and all of its content, return `true` on success
861 # Does not go through symbolic links and may get stuck in a cycle if there
862 # is a cycle in the filesystem.
863 fun rmdir
: Bool do return to_path
.rmdir
865 # Change the current working directory
868 # assert getcwd == "/etc"
870 # assert getcwd == "/"
873 fun chdir
do to_cstring
.file_chdir
875 # Return right-most extension (without the dot)
877 # Only the last extension is returned.
878 # There is no special case for combined extensions.
880 # assert "file.txt".file_extension == "txt"
881 # assert "file.tar.gz".file_extension == "gz"
883 # For file without extension, `null` is returned.
884 # Hoever, for trailing dot, `""` is returned.
886 # assert "file".file_extension == null
887 # assert "file.".file_extension == ""
889 # The starting dot of hidden files is never considered.
891 # assert ".file.txt".file_extension == "txt"
892 # assert ".file".file_extension == null
893 fun file_extension
: nullable String
895 var last_slash
= chars
.last_index_of
('.')
896 if last_slash
> 0 then
897 return substring
( last_slash
+1, length
)
903 # returns files contained within the directory represented by self
904 fun files
: Array[String] is extern import Array[String], Array[String].add
, NativeString.to_s
, String.to_cstring
`{
908 dir_path = String_to_cstring( recv );
909 if ((dir = opendir(dir_path)) == NULL)
916 Array_of_String results;
920 results = new_Array_of_String();
922 while ( ( de = readdir( dir ) ) != NULL )
923 if ( strcmp( de->d_name, ".." ) != 0 &&
924 strcmp( de->d_name, "." ) != 0 )
926 file_name = NativeString_to_s( strdup( de->d_name ) );
927 Array_of_String_add( results, file_name );
936 redef class NativeString
937 private fun file_exists
: Bool is extern "string_NativeString_NativeString_file_exists_0"
938 private fun file_stat
: NativeFileStat is extern "string_NativeString_NativeString_file_stat_0"
939 private fun file_lstat
: NativeFileStat `{
940 struct stat* stat_element;
942 stat_element = malloc(sizeof(struct stat));
943 res = lstat(recv, stat_element);
944 if (res == -1) return NULL;
947 private fun file_mkdir
: Bool is extern "string_NativeString_NativeString_file_mkdir_0"
948 private fun rmdir
: Bool `{ return rmdir(recv); `}
949 private fun file_delete: Bool is extern "string_NativeString_NativeString_file_delete_0"
950 private fun file_chdir is extern "string_NativeString_NativeString_file_chdir_0"
951 private fun file_realpath: NativeString is extern "file_NativeString_realpath"
954 # This class is system dependent ... must reify the vfs
955 extern class NativeFileStat `{ struct stat * `}
956 # Returns the permission bits of file
957 fun mode
: Int is extern "file_FileStat_FileStat_mode_0"
958 # Returns the last access time
959 fun atime
: Int is extern "file_FileStat_FileStat_atime_0"
960 # Returns the last status change time
961 fun ctime
: Int is extern "file_FileStat_FileStat_ctime_0"
962 # Returns the last modification time
963 fun mtime
: Int is extern "file_FileStat_FileStat_mtime_0"
965 fun size
: Int is extern "file_FileStat_FileStat_size_0"
967 # Returns true if it is a regular file (not a device file, pipe, sockect, ...)
968 fun is_reg
: Bool `{ return S_ISREG(recv->st_mode); `}
969 # Returns true if it is a directory
970 fun is_dir: Bool `{ return S_ISDIR(recv->st_mode); `}
971 # Returns true if it is a character device
972 fun is_chr
: Bool `{ return S_ISCHR(recv->st_mode); `}
973 # Returns true if it is a block device
974 fun is_blk: Bool `{ return S_ISBLK(recv->st_mode); `}
975 # Returns true if the type is fifo
976 fun is_fifo
: Bool `{ return S_ISFIFO(recv->st_mode); `}
977 # Returns true if the type is a link
978 fun is_lnk: Bool `{ return S_ISLNK(recv->st_mode); `}
979 # Returns true if the type is a socket
980 fun is_sock
: Bool `{ return S_ISSOCK(recv->st_mode); `}
983 # Instance of this class are standard FILE * pointers
984 private extern class NativeFile `{ FILE* `}
985 fun io_read
(buf
: NativeString, len
: Int): Int is extern "file_NativeFile_NativeFile_io_read_2"
986 fun io_write
(buf
: NativeString, len
: Int): Int is extern "file_NativeFile_NativeFile_io_write_2"
987 fun io_close
: Int is extern "file_NativeFile_NativeFile_io_close_0"
988 fun file_stat
: NativeFileStat is extern "file_NativeFile_NativeFile_file_stat_0"
989 fun fileno
: Int `{ return fileno(recv); `}
990 # Flushes the buffer, forcing the write operation
991 fun flush: Int is extern "fflush"
992 # Used to specify how the buffering will be handled for the current stream.
993 fun set_buffering_type(buf_length: Int, mode: Int): Int is extern "file_NativeFile_NativeFile_set_buffering_type_0"
995 new io_open_read(path: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_read_1"
996 new io_open_write(path: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_write_1"
997 new native_stdin is extern "file_NativeFileCapable_NativeFileCapable_native_stdin_0"
998 new native_stdout is extern "file_NativeFileCapable_NativeFileCapable_native_stdout_0"
999 new native_stderr is extern "file_NativeFileCapable_NativeFileCapable_native_stderr_0"
1005 var stdin: PollableReader = new Stdin is protected writable, lazy
1008 var stdout: Writer = new Stdout is protected writable, lazy
1010 # Standard output for errors
1011 var stderr: Writer = new Stderr is protected writable, lazy
1013 # Enumeration for buffer mode full (flushes when buffer is full)
1014 fun buffer_mode_full: Int is extern "file_Sys_Sys_buffer_mode_full_0"
1015 # Enumeration for buffer mode line (flushes when a `\n
` is encountered)
1016 fun buffer_mode_line: Int is extern "file_Sys_Sys_buffer_mode_line_0"
1017 # Enumeration for buffer mode none (flushes ASAP when something is written)
1018 fun buffer_mode_none: Int is extern "file_Sys_Sys_buffer_mode_none_0"
1020 # returns first available stream to read or write to
1021 # return null on interruption (possibly a signal)
1022 protected fun poll( streams : Sequence[FileStream] ) : nullable FileStream
1024 var in_fds = new Array[Int]
1025 var out_fds = new Array[Int]
1026 var fd_to_stream = new HashMap[Int,FileStream]
1029 if s isa FileReader then in_fds.add( fd )
1030 if s isa FileWriter then out_fds.add( fd )
1032 fd_to_stream[fd] = s
1035 var polled_fd = intern_poll( in_fds, out_fds )
1037 if polled_fd == null then
1040 return fd_to_stream[polled_fd]
1044 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) `{
1045 int in_len
, out_len
, total_len
;
1046 struct pollfd
*c_fds
;
1049 int first_polled_fd
= -1;
1052 in_len
= Array_of_Int_length( in_fds
);
1053 out_len
= Array_of_Int_length( out_fds
);
1054 total_len
= in_len
+ out_len
;
1055 c_fds
= malloc
( sizeof
(struct pollfd
) * total_len
);
1058 for ( i
=0; i
<in_len
; i
++ ) {
1060 fd
= Array_of_Int__index( in_fds
, i
);
1063 c_fds
[i
].events
= POLLIN;
1066 /* output streams
*/
1067 for ( i
=0; i
<out_len
; i
++ ) {
1069 fd
= Array_of_Int__index( out_fds
, i
);
1072 c_fds
[i
].events
= POLLOUT;
1075 /* poll all fds
, unlimited timeout
*/
1076 result
= poll
( c_fds
, total_len
, -1 );
1079 /* analyse results
*/
1080 for ( i
=0; i
<total_len
; i
++ )
1081 if ( c_fds
[i
].revents
& c_fds
[i
].events
|| /* awaited event
*/
1082 c_fds
[i
].revents
& POLLHUP ) /* closed
*/
1084 first_polled_fd
= c_fds
[i
].fd
;
1088 return Int_as_nullable( first_polled_fd
);
1090 else if ( result
< 0 )
1091 fprintf
( stderr
, "Error in Stream:poll: %s\n", strerror
( errno
) );
1098 # Print `objects
` on the standard output (`stdout
`).
1099 fun printn(objects: Object...)
1101 sys.stdout.write(objects.to_s)
1104 # Print an `object
` on the standard output (`stdout
`) and add a newline.
1105 fun print(object: Object)
1107 sys.stdout.write(object.to_s)
1108 sys.stdout.write("\n")
1111 # Read a character from the standard input (`stdin
`).
1114 return sys.stdin.read_char.ascii
1117 # Read a line from the standard input (`stdin
`).
1120 return sys.stdin.read_line
1123 # Return the working (current) directory
1124 fun getcwd: String do return file_getcwd.to_s
1125 private fun file_getcwd: NativeString is extern "string_NativeString_NativeString_file_getcwd_0"