///|
/// The record separator `0x1E` that ends each message of the JSON hub protocol.
pub let record_separator : Char = '\u{1E}'

///|
/// The parts of an incomplete message, the last part first.
priv enum Parts {
  Nothing
  Part(StringView, Parts)
}

///|
/// The text of the messages that arrived on a connection and do not end yet. The
/// value is immutable: `push` gives a new buffer. It keeps the parts of an
/// incomplete message, so many small frames cost no more than one large frame.
pub struct FrameBuffer {
  priv parts : Parts
  /// The length of the parts in UTF-16 code units.
  priv units : Int32
  /// The length of the parts in UTF-8 bytes.
  priv bytes : Int32
}

///|
/// The text that waits for its record separator.
fn FrameBuffer::pending(self : FrameBuffer) -> String {
  let parts = []
  for rest = self.parts {
    match rest {
      Nothing => break
      Part(text, more) => {
        parts.push(text)
        continue more
      }
    }
  }
  parts.rev_in_place()
  parts.join("")
}

///|
/// Two buffers are equal when the same text waits.
pub impl Eq for FrameBuffer with fn equal(self, other) {
  self.units == other.units && self.pending() == other.pending()
}

///|
pub extend FrameBuffer with Eq::{equal, not_equal}

///|
pub impl @debug.Debug for FrameBuffer with fn to_repr(self) {
  @debug.Repr(self.pending())
}

///|
pub extend FrameBuffer with @debug.Debug::{to_repr}

///|
/// The buffer with no text.
pub fn FrameBuffer::empty() -> FrameBuffer {
  { parts: Nothing, units: 0, bytes: 0, }
}

///|
/// Add the text of one frame, or a part of it that ends between two characters.
/// The result gives the new buffer and the complete messages, in order, without
/// their record separators. An incomplete trailing message stays in the buffer
/// until more text arrives.
pub fn FrameBuffer::push(
  self : FrameBuffer,
  text : StringView,
) -> (FrameBuffer, Array[String]) {
  let messages = []
  let mut buffer = self
  let mut rest = text
  while rest.find("\u{1E}") is Some(at) {
    messages.push(buffer.add(rest[:at]).pending())
    buffer = FrameBuffer::empty()
    rest = rest[at + 1:]
  }
  (buffer.add(rest), messages)
}

///|
/// Add text with no record separator.
fn FrameBuffer::add(self : FrameBuffer, text : StringView) -> FrameBuffer {
  if text.is_empty() {
    self
  } else {
    {
      parts: Part(text, self.parts),
      units: self.units + text.length(),
      bytes: self.bytes + utf8_length(text),
    }
  }
}

///|
/// The length, in UTF-16 code units, of the text that waits for its record
/// separator.
pub fn FrameBuffer::pending_length(self : FrameBuffer) -> Int32 {
  self.units
}

///|
/// The length, in UTF-8 bytes, of the text that waits for its record separator.
pub fn FrameBuffer::pending_utf8_length(self : FrameBuffer) -> Int32 {
  self.bytes
}

///|
/// The text of one message followed by the record separator.
pub fn frame(text : StringView) -> String {
  text.to_owned() + record_separator.to_string()
}