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

io/Read_Handler.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 Read_Handler
#
# -----------------------------------------------------------------------

# An implementation of a Read_Handler
# needs to implement how to do a blocking
# read from an I/O device.
#
public Read_Handler ref is

  # read up to count bytes
  #
  # returns either an array of the bytes read, end_of_file or an error
  #
  public read(max_count i32) choice (Sequence u8) io.end_of_file error
    post debug: (result ? s Sequence => s.count<=max_count | * => true)
         debug 10 : (result ? s Sequence => s.is_array_backed | * => true)
  => abstract


  # Read_Handler that only ever returns end_of_file
  #
  public fixed type.empty io.Read_Handler =>
    _ : io.Read_Handler is
      public redef read(c i32) choice (Sequence u8) io.end_of_file error => io.end_of_file


  # create a Read_Handler from a Sequence of bytes
  #
  type.from_array_backed_u8(LM type : mutate, arr Sequence u8) io.Read_Handler =>
    _ : io.Read_Handler is

      # the current position in the array
      #
      pos := LM.env.new 0

      public redef read(max_count i32) choice (Sequence u8) io.end_of_file error =>
        p := pos.get
        if p >= arr.count
          io.end_of_file
        else
          pos <- p + max_count
          arr.drop p .take max_count


  # create a Read_Handler from data
  # where data may bytes or a String
  #
  public type.from(LM type : mutate, data choice (Sequence u8) String) io.Read_Handler =>

    match data
      bytes Sequence u8 => io.Read_Handler.from_array_backed_u8 LM bytes.as_array_backed
      str String => io.Read_Handler.from_array_backed_u8 LM str.utf8.as_array_backed

last changed: 2026-04-29