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()`.
#
# type parameter T is used to distinguish between several open files.
#
# 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(T, R type, file_name String, m mode.val, code ()-> outcome R) outcome R =>

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

  match fuzion.sys.fileio.open file_name mode_num
    fd i64 =>
      # install effect `open T` and run `code`
      r := open T fd file_name
        .go code
      # close file
      fuzion.sys.fileio.close fd
      # return result
      r
    e error =>
      e



# short hand for use when
# it is not necessary to distinguish between opens
#
# usage example:
# ```
# use file_name mode.read ()->
#   match open.read
#     e error => e
#     a array => String.from_bytes a
# ```
public use(R type, file_name String, m mode.val, code ()-> outcome R) outcome R =>
  use open_unique_type R file_name m code