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

io/file/write.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 write
#
#  Author: Wael Youssfi (wael.youssfi@tokiwa.software)
#
# -----------------------------------------------------------------------

# write -- effect providing writing operations for files
#
public write(fwh Write_Handler) : simple_effect is

  # writes the content of an array of bytes to a file opened as fd
  #
  # this might overwrite parts or all of an existing file.
  #
  module write(fd i64, content array u8) =>
    tmp := fwh.write fd content unit
    replace
    tmp

  # creates a directory using the specified path
  # parent directories in the path should exist otherwise, no creation will take place and an error will be the outcome
  # in case of successful creation a unit type will be the outcome
  #
  public create_dir(
             # the (relative or absolute) dir name, using platform specific path separators
             path String) =>
    tmp := fwh.mkdir path
    replace
    tmp


  # the default file writing handler writing bytes into files via fuzion.sys.fileio.write
  #
  type.default_write_handler : io.file.Write_Handler is
    # dummy parameter for overloading
    write(fd i64, content array u8, _ unit) =>
      fuzion.sys.fileio.write fd content
        .bind unit r->
          if fuzion.sys.fileio.flush fd = 0 then r else error "flushing failed"


    mkdir(path String) =>
      fuzion.sys.fileio.create_dir path


  # install default effect io.file.write
  #
  type.install_default =>
    (io.file.write default_write_handler).default


# short-hand for accessing write effect in current environment
#
public write =>
  write.install_default
  write.env


# reference to the writing operations that could take place
#
private:public Write_Handler ref is
  write(fd i64, content array u8, _ unit) outcome unit => abstract

  mkdir(path String) outcome unit => abstract