///|
fn minimum(a : Int32, b : Int32) -> Int32 {
  if a < b {
    a
  } else {
    b
  }
}

///|
fn spaces(count : Int32) -> String {
  let out = StringBuilder()
  for i = 0; i < count; i = i + 1 {
    out.write_char(' ')
  }
  out.to_string()
}

///|
fn Writer::wrapped(
  self : Writer,
  text : String,
  width : Int32,
  first : Int32,
  rest : Int32,
) -> Unit {
  let mut column = first
  self.write(spaces(first))
  let mut word = StringBuilder()
  let mut word_size = 0
  let mut pending_space = false
  // Explicit newlines survive; ordinary horizontal whitespace separates words.
  for c in text.iter().concat(Iter::singleton('\u{0000}')) {
    if c == ' ' || c == '\t' || c == '\n' || c == '\u{0000}' {
      if word_size > 0 {
        let gap = if pending_space { 1 } else { 0 }
        if column > rest && column + gap + word_size > width {
          self.write("\n" + spaces(rest))
          column = rest
        } else if pending_space {
          self.write(" ")
          column = column + 1
        }
        self.write(word.to_string())
        column = column + word_size
        word = StringBuilder()
        word_size = 0
      }
      pending_space = column > rest
      if c == '\n' {
        self.write("\n" + spaces(rest))
        column = rest
        pending_space = false
      }
    } else {
      word.write_char(c)
      word_size = word_size + 1
    }
    if self.failed {
      return
    }
  }
  self.write("\n")
}

///|
/// Wrap by Unicode scalar count, preserving explicit breaks and literal lines.
pub fn render_plain(
  doc : Document,
  options~ : RenderOptions = RenderOptions::default(),
) -> Result[String, Diagnostic] {
  if options.validate() is Some(d) {
    return Err(d)
  }
  if validate_document(doc) is Err(d) {
    return Err(d)
  }
  let writer = Writer::new(options.max_output_chars)
  if options.include_title && doc.metadata.title != "" {
    writer.write(doc.metadata.title)
    if doc.metadata.section != "" {
      writer.write("(" + doc.metadata.section + ")")
    }
    writer.write("\n\n")
  }
  for block in doc.blocks {
    if writer.failed {
      break
    }
    let margin = minimum(block.indent, options.width - 10)
    let text = inline_text(block.inlines)
    match block.kind {
      Heading(_) => writer.wrapped(text, options.width, margin, margin)
      Tagged(term) => {
        writer.wrapped(inline_text(term), options.width, margin, margin)
        let body_margin = minimum(margin + 4, options.width - 4)
        writer.wrapped(text, options.width, body_margin, body_margin)
      }
      Hanging(amount) =>
        writer.wrapped(
          text,
          options.width,
          margin,
          minimum(margin + amount, options.width - 4),
        )
      Literal | Synopsis => {
        writer.write(spaces(margin))
        for c in text.iter() {
          writer.write(c.to_string())
          if c == '\n' {
            writer.write(spaces(margin))
          }
          if writer.failed {
            break
          }
        }
        writer.write("\n")
      }
      Rule => writer.write(spaces(margin) + "---\n")
      Paragraph => writer.wrapped(text, options.width, margin, margin)
    }
    writer.write("\n")
  }
  writer.finish()
}