Fuzion Logo
fuzion-lang.dev — The Fuzion Language Portal
JavaScript seems to be disabled. Functionality is limited.

io/file/use.fz


# This file is part of the Fuzion language implementation.
#
# The Fuzion language implementation is free software: you can redistribute it
# and/or modify it under the terms of the GNU General Public License as published
# by the Free Software Foundation, version 3 of the License.
#
# The Fuzion language implementation is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
# License for more details.
#
# You should have received a copy of the GNU General Public License along with The
# Fuzion language implementation.  If not, see <https://www.gnu.org/licenses/>.


# -----------------------------------------------------------------------
#
#  Tokiwa Software GmbH, Germany
#
#  Source code of Fuzion standard library feature io.file.use
#
# -----------------------------------------------------------------------


# the mode to use when opening a file
#
public mode is

  public read is
  public write is
  public append is

  module:public val : choice mode.read mode.write append is



# this opens a file with the given mode and installs
# effect (open T) to be used in `code()`.
#
# usage example:
#
#     use some_type file_name mode.read ()->
#       match (open some_type).read
#         e error => e
#         a array => String.from_bytes a
#
public use(R type, LM type : mutate, file_name String, m mode.val, code ()-> outcome R) outcome R =>

  # definition of read handler for file
  #
  read_handler(desc fuzion.sys.Pointer) : io.Read_Handler is
    redef read(count i32) choice (array u8) io.end_of_file error =>
      match fuzion.sys.fileio.read desc count.as_u64
        a array u8 => if a.is_empty then io.end_of_file else a
        e error => e

  # definition of write handler for file
  #
  write_handler (desc fuzion.sys.Pointer) : io.Write_Handler is
    redef write (bytes Sequence u8) outcome unit =>
      fuzion.sys.fileio.write desc bytes.as_array


  mode_num := match m
                mode.read => i8 0
                mode.write => i8 1
                mode.append => i8 2

  (fuzion.sys.fileio.open file_name mode_num).bind R fd->
    # install effect `open T` and run `code`
    r := (open fd file_name) ! ()->
          (io.buffered LM).reader (read_handler fd) 1024 ! ()->
            (io.buffered LM).writer (write_handler fd) 1024 ! ()->
              tmp := code.call
              # NYI: handle error once signature of with is changed
              _ := (io.buffered LM).writer.env.flush
              tmp

    # close file
    _ := fuzion.sys.fileio.close fd

    # return result
    r
      # NYI: UNDER DEVELOPMENT: nested outcomes
      .bind (outcome R) x->x
      .bind R x->x
last changed: 2025-01-23