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 init from_fd
(fd
: Int) do
141 _file
= fd
.fd_to_stream
(read_only
)
142 if _file
.address_is_null
then
143 last_error
= new IOError("Error: Converting fd {fd} to stream failed with '{sys.errno.strerror}'")
149 # `Stream` that can write to a File
156 if last_error
!= null then return
157 if not _is_writable
then
158 last_error
= new IOError("Cannot write to non-writable stream")
161 if s
isa FlatText then
162 write_native
(s
.to_cstring
, s
.length
)
164 for i
in s
.substrings
do write_native
(i
.to_cstring
, i
.length
)
173 redef var is_writable
= false
175 # Write `len` bytes from `native`.
176 private fun write_native
(native
: NativeString, len
: Int)
178 if last_error
!= null then return
179 if not _is_writable
then
180 last_error
= new IOError("Cannot write to non-writable stream")
183 if _file
.address_is_null
then
184 last_error
= new IOError("Writing on a null stream")
188 var err
= _file
.io_write
(native
, len
)
191 last_error
= new IOError("Problem in writing : {err} {len} \n")
195 # Open the file at `path` for writing.
196 init open
(path
: String)
198 _file
= new NativeFile.io_open_write
(path
.to_cstring
)
201 if _file
.address_is_null
then
202 last_error
= new IOError("Error: Opening file at '{path}' failed with '{sys.errno.strerror}'")
207 # Creates a new File stream from a file descriptor
208 init from_fd
(fd
: Int) do
210 _file
= fd
.fd_to_stream
(wipe_write
)
212 if _file
.address_is_null
then
213 last_error
= new IOError("Error: Opening stream from file descriptor {fd} failed with '{sys.errno.strerror}'")
220 # Creates a file stream from a file descriptor `fd` using the file access `mode`.
222 # NOTE: The `mode` specified must be compatible with the one used in the file descriptor.
223 private fun fd_to_stream
(mode
: NativeString): NativeFile is extern "file_int_fdtostream"
226 # Constant for read-only file streams
227 private fun read_only
: NativeString do return "r".to_cstring
229 # Constant for write-only file streams
231 # If a stream is opened on a file with this method,
232 # it will wipe the previous file if any.
233 # Else, it will create the file.
234 private fun wipe_write
: NativeString do return "w".to_cstring
236 ###############################################################################
238 # Standard input stream.
243 _file
= new NativeFile.native_stdin
248 redef fun poll_in
: Bool is extern "file_stdin_poll_in"
251 # Standard output stream.
255 _file
= new NativeFile.native_stdout
258 set_buffering_mode
(256, sys
.buffer_mode_line
)
262 # Standard error stream.
266 _file
= new NativeFile.native_stderr
272 ###############################################################################
275 # Like `write_to` but take care of creating the file
276 fun write_to_file
(filepath
: String)
278 var stream
= new FileWriter.open
(filepath
)
284 # Utility class to access file system services
286 # Usually created with `Text::to_path`.
289 private var path
: String
292 redef fun to_s
do return path
294 # Name of the file name at `to_s`
297 # var path = "/tmp/somefile".to_path
298 # assert path.filename == "somefile"
300 var filename
: String = path
.basename
("") is lazy
302 # Does the file at `path` exists?
303 fun exists
: Bool do return stat
!= null
305 # Information on the file at `self` following symbolic links
307 # Returns `null` if there is no file at `self`.
310 # var p = "/tmp/".to_path
312 # if stat != null then # Does `p` exist?
313 # print "It's size is {stat.size}"
314 # if stat.is_dir then print "It's a directory"
317 fun stat
: nullable FileStat
319 var stat
= path
.to_cstring
.file_stat
320 if stat
.address_is_null
then return null
321 return new FileStat(stat
)
324 # Information on the file or link at `self`
326 # Do not follow symbolic links.
327 fun link_stat
: nullable FileStat
329 var stat
= path
.to_cstring
.file_lstat
330 if stat
.address_is_null
then return null
331 return new FileStat(stat
)
334 # Delete a file from the file system, return `true` on success
337 fun delete
: Bool do return path
.to_cstring
.file_delete
339 # Copy content of file at `path` to `dest`
345 var output
= dest
.open_wo
347 while not input
.eof
do
348 var buffer
= input
.read
(1024)
356 # Open this file for reading
358 # Require: `exists and not link_stat.is_dir`
359 fun open_ro
: FileReader
361 # TODO manage streams error when they are merged
362 return new FileReader.open
(path
)
365 # Open this file for writing
367 # Require: `not exists or not stat.is_dir`
368 fun open_wo
: FileWriter
370 # TODO manage streams error when they are merged
371 return new FileWriter.open
(path
)
374 # Read all the content of the file
377 # var content = "/etc/issue".to_path.read_all
381 # See `Reader::read_all` for details.
390 # Read all the lines of the file
393 # var lines = "/etc/passwd".to_path.read_lines
395 # print "{lines.length} users"
398 # var fields = l.split(":")
399 # print "name={fields[0]} uid={fields[2]}"
403 # See `Reader::read_lines` for details.
404 fun read_lines
: Array[String]
407 var res
= s
.read_lines
412 # Return an iterator on each line of the file
415 # for l in "/etc/passwd".to_path.each_line do
416 # var fields = l.split(":")
417 # print "name={fields[0]} uid={fields[2]}"
421 # Note: the stream is automatically closed at the end of the file (see `LineIterator::close_on_finish`)
423 # See `Reader::each_line` for details.
424 fun each_line
: LineIterator
427 var res
= s
.each_line
428 res
.close_on_finish
= true
433 # Lists the name of the files contained within the directory at `path`
435 # Require: `exists and is_dir`
436 fun files
: Array[Path]
438 var files
= new Array[Path]
439 for filename
in path
.files
do
440 files
.add
new Path(path
/ filename
)
445 # Delete a directory and all of its content, return `true` on success
447 # Does not go through symbolic links and may get stuck in a cycle if there
448 # is a cycle in the file system.
452 for file
in self.files
do
453 var stat
= file
.link_stat
455 ok
= file
.rmdir
and ok
457 ok
= file
.delete
and ok
461 # Delete the directory itself
462 if ok
then path
.to_cstring
.rmdir
467 redef fun ==(other
) do return other
isa Path and path
.simplify_path
== other
.path
.simplify_path
468 redef fun hash
do return path
.simplify_path
.hash
471 # Information on a file
473 # Created by `Path::stat` and `Path::link_stat`.
475 # The information within this class is gathered when the instance is initialized
476 # it will not be updated if the targeted file is modified.
482 # The low-level status of a file
485 private var stat
: NativeFileStat
487 private var finalized
= false
491 if not finalized
then
497 # Returns the last access time in seconds since Epoch
498 fun last_access_time
: Int
504 # Returns the last modification time in seconds since Epoch
505 fun last_modification_time
: Int
511 # Size of the file at `path`
518 # Is this a regular file and not a device file, pipe, socket, etc.?
525 # Is this a directory?
532 # Is this a symbolic link?
539 # FIXME Make the following POSIX only? or implement in some other way on Windows
541 # Returns the last status change time in seconds since Epoch
542 fun last_status_change_time
: Int
548 # Returns the permission bits of file
555 # Is this a character device?
562 # Is this a block device?
569 # Is this a FIFO pipe?
576 # Is this a UNIX socket
585 # Access file system related services on the path at `self`
586 fun to_path
: Path do return new Path(to_s
)
590 # return true if a file with this names exists
591 fun file_exists
: Bool do return to_cstring
.file_exists
593 # The status of a file. see POSIX stat(2).
594 fun file_stat
: NativeFileStat do return to_cstring
.file_stat
596 # The status of a file or of a symlink. see POSIX lstat(2).
597 fun file_lstat
: NativeFileStat do return to_cstring
.file_lstat
599 # Remove a file, return true if success
600 fun file_delete
: Bool do return to_cstring
.file_delete
602 # Copy content of file at `self` to `dest`
603 fun file_copy_to
(dest
: String) do to_path
.copy
(dest
.to_path
)
605 # Remove the trailing extension `ext`.
607 # `ext` usually starts with a dot but could be anything.
609 # assert "file.txt".strip_extension(".txt") == "file"
610 # assert "file.txt".strip_extension("le.txt") == "fi"
611 # assert "file.txt".strip_extension("xt") == "file.t"
613 # if `ext` is not present, `self` is returned unmodified.
615 # assert "file.txt".strip_extension(".tar.gz") == "file.txt"
616 fun strip_extension
(ext
: String): String
618 if has_suffix
(ext
) then
619 return substring
(0, length
- ext
.length
)
624 # Extract the basename of a path and remove the extension
626 # assert "/path/to/a_file.ext".basename(".ext") == "a_file"
627 # assert "path/to/a_file.ext".basename(".ext") == "a_file"
628 # assert "path/to".basename(".ext") == "to"
629 # assert "path/to/".basename(".ext") == "to"
630 # assert "path".basename("") == "path"
631 # assert "/path".basename("") == "path"
632 # assert "/".basename("") == "/"
633 # assert "".basename("") == ""
634 fun basename
(ext
: String): String
636 var l
= length
- 1 # Index of the last char
637 while l
> 0 and self.chars
[l
] == '/' do l
-= 1 # remove all trailing `/`
638 if l
== 0 then return "/"
639 var pos
= chars
.last_index_of_from
('/', l
)
642 n
= substring
(pos
+1, l-pos
)
644 return n
.strip_extension
(ext
)
647 # Extract the dirname of a path
649 # assert "/path/to/a_file.ext".dirname == "/path/to"
650 # assert "path/to/a_file.ext".dirname == "path/to"
651 # assert "path/to".dirname == "path"
652 # assert "path/to/".dirname == "path"
653 # assert "path".dirname == "."
654 # assert "/path".dirname == "/"
655 # assert "/".dirname == "/"
656 # assert "".dirname == "."
659 var l
= length
- 1 # Index of the last char
660 while l
> 0 and self.chars
[l
] == '/' do l
-= 1 # remove all trailing `/`
661 var pos
= chars
.last_index_of_from
('/', l
)
663 return substring
(0, pos
)
664 else if pos
== 0 then
671 # Return the canonicalized absolute pathname (see POSIX function `realpath`)
672 fun realpath
: String do
673 var cs
= to_cstring
.file_realpath
674 var res
= cs
.to_s_with_copy
675 # cs.free_malloc # FIXME memory leak
679 # Simplify a file path by remove useless ".", removing "//", and resolving ".."
680 # ".." are not resolved if they start the path
681 # starting "/" is not removed
682 # trainling "/" is removed
684 # Note that the method only wonrk on the string:
686 # * no I/O access is performed
687 # * the validity of the path is not checked
690 # assert "some/./complex/../../path/from/../to/a////file//".simplify_path == "path/to/a/file"
691 # assert "../dir/file".simplify_path == "../dir/file"
692 # assert "dir/../../".simplify_path == ".."
693 # assert "dir/..".simplify_path == "."
694 # assert "//absolute//path/".simplify_path == "/absolute/path"
695 # assert "//absolute//../".simplify_path == "/"
697 fun simplify_path
: String
699 var a
= self.split_with
("/")
700 var a2
= new Array[String]
702 if x
== "." then continue
703 if x
== "" and not a2
.is_empty
then continue
704 if x
== ".." and not a2
.is_empty
and a2
.last
!= ".." then
710 if a2
.is_empty
then return "."
711 if a2
.length
== 1 and a2
.first
== "" then return "/"
715 # Correctly join two path using the directory separator.
717 # Using a standard "{self}/{path}" does not work in the following cases:
720 # * `path` ends with `'/'`.
721 # * `path` starts with `'/'`.
723 # This method ensures that the join is valid.
725 # assert "hello".join_path("world") == "hello/world"
726 # assert "hel/lo".join_path("wor/ld") == "hel/lo/wor/ld"
727 # assert "".join_path("world") == "world"
728 # assert "hello".join_path("/world") == "/world"
729 # assert "hello/".join_path("world") == "hello/world"
730 # assert "hello/".join_path("/world") == "/world"
732 # Note: You may want to use `simplify_path` on the result.
734 # Note: This method works only with POSIX paths.
735 fun join_path
(path
: String): String
737 if path
.is_empty
then return self
738 if self.is_empty
then return path
739 if path
.chars
[0] == '/' then return path
740 if self.last
== '/' then return "{self}{path}"
741 return "{self}/{path}"
744 # Convert the path (`self`) to a program name.
746 # Ensure the path (`self`) will be treated as-is by POSIX shells when it is
747 # used as a program name. In order to do that, prepend `./` if needed.
749 # assert "foo".to_program_name == "./foo"
750 # assert "/foo".to_program_name == "/foo"
751 # assert "".to_program_name == "./" # At least, your shell will detect the error.
752 fun to_program_name
: String do
753 if self.has_prefix
("/") then
760 # Alias for `join_path`
762 # assert "hello" / "world" == "hello/world"
763 # assert "hel/lo" / "wor/ld" == "hel/lo/wor/ld"
764 # assert "" / "world" == "world"
765 # assert "/hello" / "/world" == "/world"
767 # This operator is quite useful for chaining changes of path.
768 # The next one being relative to the previous one.
772 # var c = "baz/foobar"
773 # assert a/b/c == "/bar/baz/foobar"
774 fun /(path
: String): String do return join_path
(path
)
776 # Returns the relative path needed to go from `self` to `dest`.
778 # assert "/foo/bar".relpath("/foo/baz") == "../baz"
779 # assert "/foo/bar".relpath("/baz/bar") == "../../baz/bar"
781 # If `self` or `dest` is relative, they are considered relatively to `getcwd`.
783 # In some cases, the result is still independent of the current directory:
785 # assert "foo/bar".relpath("..") == "../../.."
787 # In other cases, parts of the current directory may be exhibited:
789 # var p = "../foo/bar".relpath("baz")
790 # var c = getcwd.basename("")
791 # assert p == "../../{c}/baz"
793 # For path resolution independent of the current directory (eg. for paths in URL),
794 # or to use an other starting directory than the current directory,
795 # just force absolute paths:
797 # var start = "/a/b/c/d"
798 # var p2 = (start/"../foo/bar").relpath(start/"baz")
799 # assert p2 == "../../d/baz"
802 # Neither `self` or `dest` has to be real paths or to exist in directories since
803 # the resolution is only done with string manipulations and without any access to
804 # the underlying file system.
806 # If `self` and `dest` are the same directory, the empty string is returned:
808 # assert "foo".relpath("foo") == ""
809 # assert "foo/../bar".relpath("bar") == ""
811 # The empty string and "." designate both the current directory:
813 # assert "".relpath("foo/bar") == "foo/bar"
814 # assert ".".relpath("foo/bar") == "foo/bar"
815 # assert "foo/bar".relpath("") == "../.."
816 # assert "/" + "/".relpath(".") == getcwd
817 fun relpath
(dest
: String): String
820 var from
= (cwd
/self).simplify_path
.split
("/")
821 if from
.last
.is_empty
then from
.pop
# case for the root directory
822 var to
= (cwd
/dest
).simplify_path
.split
("/")
823 if to
.last
.is_empty
then to
.pop
# case for the root directory
825 # Remove common prefixes
826 while not from
.is_empty
and not to
.is_empty
and from
.first
== to
.first
do
831 # Result is going up in `from` with ".." then going down following `to`
832 var from_len
= from
.length
833 if from_len
== 0 then return to
.join
("/")
834 var up
= "../"*(from_len-1
) + ".."
835 if to
.is_empty
then return up
836 var res
= up
+ "/" + to
.join
("/")
840 # Create a directory (and all intermediate directories if needed)
843 var dirs
= self.split_with
("/")
844 var path
= new FlatBuffer
845 if dirs
.is_empty
then return
846 if dirs
[0].is_empty
then
847 # it was a starting /
851 if d
.is_empty
then continue
854 path
.to_s
.to_cstring
.file_mkdir
858 # Delete a directory and all of its content, return `true` on success
860 # Does not go through symbolic links and may get stuck in a cycle if there
861 # is a cycle in the filesystem.
862 fun rmdir
: Bool do return to_path
.rmdir
864 # Change the current working directory
867 # assert getcwd == "/etc"
869 # assert getcwd == "/"
872 fun chdir
do to_cstring
.file_chdir
874 # Return right-most extension (without the dot)
876 # Only the last extension is returned.
877 # There is no special case for combined extensions.
879 # assert "file.txt".file_extension == "txt"
880 # assert "file.tar.gz".file_extension == "gz"
882 # For file without extension, `null` is returned.
883 # Hoever, for trailing dot, `""` is returned.
885 # assert "file".file_extension == null
886 # assert "file.".file_extension == ""
888 # The starting dot of hidden files is never considered.
890 # assert ".file.txt".file_extension == "txt"
891 # assert ".file".file_extension == null
892 fun file_extension
: nullable String
894 var last_slash
= chars
.last_index_of
('.')
895 if last_slash
> 0 then
896 return substring
( last_slash
+1, length
)
902 # returns files contained within the directory represented by self
903 fun files
: Array[String] is extern import Array[String], Array[String].add
, NativeString.to_s
, String.to_cstring
`{
907 dir_path = String_to_cstring( recv );
908 if ((dir = opendir(dir_path)) == NULL)
915 Array_of_String results;
919 results = new_Array_of_String();
921 while ( ( de = readdir( dir ) ) != NULL )
922 if ( strcmp( de->d_name, ".." ) != 0 &&
923 strcmp( de->d_name, "." ) != 0 )
925 file_name = NativeString_to_s( strdup( de->d_name ) );
926 Array_of_String_add( results, file_name );
935 redef class NativeString
936 private fun file_exists
: Bool is extern "string_NativeString_NativeString_file_exists_0"
937 private fun file_stat
: NativeFileStat is extern "string_NativeString_NativeString_file_stat_0"
938 private fun file_lstat
: NativeFileStat `{
939 struct stat* stat_element;
941 stat_element = malloc(sizeof(struct stat));
942 res = lstat(recv, stat_element);
943 if (res == -1) return NULL;
946 private fun file_mkdir
: Bool is extern "string_NativeString_NativeString_file_mkdir_0"
947 private fun rmdir
: Bool `{ return rmdir(recv); `}
948 private fun file_delete: Bool is extern "string_NativeString_NativeString_file_delete_0"
949 private fun file_chdir is extern "string_NativeString_NativeString_file_chdir_0"
950 private fun file_realpath: NativeString is extern "file_NativeString_realpath"
953 # This class is system dependent ... must reify the vfs
954 extern class NativeFileStat `{ struct stat * `}
955 # Returns the permission bits of file
956 fun mode
: Int is extern "file_FileStat_FileStat_mode_0"
957 # Returns the last access time
958 fun atime
: Int is extern "file_FileStat_FileStat_atime_0"
959 # Returns the last status change time
960 fun ctime
: Int is extern "file_FileStat_FileStat_ctime_0"
961 # Returns the last modification time
962 fun mtime
: Int is extern "file_FileStat_FileStat_mtime_0"
964 fun size
: Int is extern "file_FileStat_FileStat_size_0"
966 # Returns true if it is a regular file (not a device file, pipe, sockect, ...)
967 fun is_reg
: Bool `{ return S_ISREG(recv->st_mode); `}
968 # Returns true if it is a directory
969 fun is_dir: Bool `{ return S_ISDIR(recv->st_mode); `}
970 # Returns true if it is a character device
971 fun is_chr
: Bool `{ return S_ISCHR(recv->st_mode); `}
972 # Returns true if it is a block device
973 fun is_blk: Bool `{ return S_ISBLK(recv->st_mode); `}
974 # Returns true if the type is fifo
975 fun is_fifo
: Bool `{ return S_ISFIFO(recv->st_mode); `}
976 # Returns true if the type is a link
977 fun is_lnk: Bool `{ return S_ISLNK(recv->st_mode); `}
978 # Returns true if the type is a socket
979 fun is_sock
: Bool `{ return S_ISSOCK(recv->st_mode); `}
982 # Instance of this class are standard FILE * pointers
983 private extern class NativeFile `{ FILE* `}
984 fun io_read
(buf
: NativeString, len
: Int): Int is extern "file_NativeFile_NativeFile_io_read_2"
985 fun io_write
(buf
: NativeString, len
: Int): Int is extern "file_NativeFile_NativeFile_io_write_2"
986 fun io_close
: Int is extern "file_NativeFile_NativeFile_io_close_0"
987 fun file_stat
: NativeFileStat is extern "file_NativeFile_NativeFile_file_stat_0"
988 fun fileno
: Int `{ return fileno(recv); `}
989 # Flushes the buffer, forcing the write operation
990 fun flush: Int is extern "fflush"
991 # Used to specify how the buffering will be handled for the current stream.
992 fun set_buffering_type(buf_length: Int, mode: Int): Int is extern "file_NativeFile_NativeFile_set_buffering_type_0"
994 new io_open_read(path: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_read_1"
995 new io_open_write(path: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_write_1"
996 new native_stdin is extern "file_NativeFileCapable_NativeFileCapable_native_stdin_0"
997 new native_stdout is extern "file_NativeFileCapable_NativeFileCapable_native_stdout_0"
998 new native_stderr is extern "file_NativeFileCapable_NativeFileCapable_native_stderr_0"
1004 var stdin: PollableReader = new Stdin is protected writable, lazy
1007 var stdout: Writer = new Stdout is protected writable, lazy
1009 # Standard output for errors
1010 var stderr: Writer = new Stderr is protected writable, lazy
1012 # Enumeration for buffer mode full (flushes when buffer is full)
1013 fun buffer_mode_full: Int is extern "file_Sys_Sys_buffer_mode_full_0"
1014 # Enumeration for buffer mode line (flushes when a `\n
` is encountered)
1015 fun buffer_mode_line: Int is extern "file_Sys_Sys_buffer_mode_line_0"
1016 # Enumeration for buffer mode none (flushes ASAP when something is written)
1017 fun buffer_mode_none: Int is extern "file_Sys_Sys_buffer_mode_none_0"
1019 # returns first available stream to read or write to
1020 # return null on interruption (possibly a signal)
1021 protected fun poll( streams : Sequence[FileStream] ) : nullable FileStream
1023 var in_fds = new Array[Int]
1024 var out_fds = new Array[Int]
1025 var fd_to_stream = new HashMap[Int,FileStream]
1028 if s isa FileReader then in_fds.add( fd )
1029 if s isa FileWriter then out_fds.add( fd )
1031 fd_to_stream[fd] = s
1034 var polled_fd = intern_poll( in_fds, out_fds )
1036 if polled_fd == null then
1039 return fd_to_stream[polled_fd]
1043 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) `{
1044 int in_len
, out_len
, total_len
;
1045 struct pollfd
*c_fds
;
1048 int first_polled_fd
= -1;
1051 in_len
= Array_of_Int_length( in_fds
);
1052 out_len
= Array_of_Int_length( out_fds
);
1053 total_len
= in_len
+ out_len
;
1054 c_fds
= malloc
( sizeof
(struct pollfd
) * total_len
);
1057 for ( i
=0; i
<in_len
; i
++ ) {
1059 fd
= Array_of_Int__index( in_fds
, i
);
1062 c_fds
[i
].events
= POLLIN;
1065 /* output streams
*/
1066 for ( i
=0; i
<out_len
; i
++ ) {
1068 fd
= Array_of_Int__index( out_fds
, i
);
1071 c_fds
[i
].events
= POLLOUT;
1074 /* poll all fds
, unlimited timeout
*/
1075 result
= poll
( c_fds
, total_len
, -1 );
1078 /* analyse results
*/
1079 for ( i
=0; i
<total_len
; i
++ )
1080 if ( c_fds
[i
].revents
& c_fds
[i
].events
|| /* awaited event
*/
1081 c_fds
[i
].revents
& POLLHUP ) /* closed
*/
1083 first_polled_fd
= c_fds
[i
].fd
;
1087 return Int_as_nullable( first_polled_fd
);
1089 else if ( result
< 0 )
1090 fprintf
( stderr
, "Error in Stream:poll: %s\n", strerror
( errno
) );
1097 # Print `objects
` on the standard output (`stdout
`).
1098 protected fun printn(objects: Object...)
1100 sys.stdout.write(objects.to_s)
1103 # Print an `object
` on the standard output (`stdout
`) and add a newline.
1104 protected fun print(object: Object)
1106 sys.stdout.write(object.to_s)
1107 sys.stdout.write("\n")
1110 # Read a character from the standard input (`stdin
`).
1111 protected fun getc: Char
1113 return sys.stdin.read_char.ascii
1116 # Read a line from the standard input (`stdin
`).
1117 protected fun gets: String
1119 return sys.stdin.read_line
1122 # Return the working (current) directory
1123 protected fun getcwd: String do return file_getcwd.to_s
1124 private fun file_getcwd: NativeString is extern "string_NativeString_NativeString_file_getcwd_0"