///|
/// A value that is not a valid limit.
#derive(Eq, Debug)
pub suberror LimitError {
  /// A time limit must be more than 0 milliseconds.
  NotPositiveTime(milliseconds~ : Int64)
  /// A count limit must be more than 0.
  NotPositiveCount(count~ : Int32)
  /// A size limit must be more than 0 bytes.
  NotPositiveSize(bytes~ : Int32)
}

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

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

///|
/// Text for people that describes the fault.
pub fn LimitError::message(self : LimitError) -> String {
  match self {
    NotPositiveTime(milliseconds~) =>
      "Invalid time limit \{milliseconds} ms: it must be more than 0"
    NotPositiveCount(count~) =>
      "Invalid count limit \{count}: it must be more than 0"
    NotPositiveSize(bytes~) =>
      "Invalid size limit \{bytes} bytes: it must be more than 0"
  }
}

///|
/// A time limit of more than 0 milliseconds, for keep-alive, timeouts and the
/// drain.
#derive(Eq, Compare, Hash, Debug)
pub struct TimeLimit {
  priv milliseconds : Int64
}

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

///|
pub extend TimeLimit with Compare::{compare}

///|
pub extend TimeLimit with Hash::{hash, hash_combine}

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

///|
/// A time limit of `milliseconds`.
pub fn TimeLimit::milliseconds(
  milliseconds : Int64,
) -> TimeLimit raise LimitError {
  guard milliseconds > 0L else { raise NotPositiveTime(milliseconds~) }
  { milliseconds, }
}

///|
/// A time limit of `seconds`.
pub fn TimeLimit::seconds(seconds : Int32) -> TimeLimit raise LimitError {
  TimeLimit::milliseconds(seconds.to_int64() * 1000L)
}

///|
/// A time limit with a value that is valid by construction.
fn TimeLimit::of_seconds(seconds : Int32) -> TimeLimit {
  { milliseconds: seconds.to_int64() * 1000L, }
}

///|
/// The limit in milliseconds.
pub fn TimeLimit::to_milliseconds(self : TimeLimit) -> Int64 {
  self.milliseconds
}

///|
pub impl Show for TimeLimit with fn output(self, logger) {
  logger.write_string("\{self.milliseconds} ms")
}

///|
pub extend TimeLimit with Show::{output, to_string}

///|
/// The default keep-alive interval of ASP.NET Core SignalR: 15 seconds.
pub fn TimeLimit::default_keep_alive() -> TimeLimit {
  TimeLimit::of_seconds(15)
}

///|
/// The default client timeout of ASP.NET Core SignalR: 30 seconds.
pub fn TimeLimit::default_client_timeout() -> TimeLimit {
  TimeLimit::of_seconds(30)
}

///|
/// The default handshake timeout of ASP.NET Core SignalR: 15 seconds.
pub fn TimeLimit::default_handshake_timeout() -> TimeLimit {
  TimeLimit::of_seconds(15)
}

///|
/// The default time that a graceful drain waits for the open calls: 5 seconds.
pub fn TimeLimit::default_drain() -> TimeLimit {
  TimeLimit::of_seconds(5)
}

///|
/// A size limit of more than 0 bytes.
#derive(Eq, Compare, Hash, Debug)
pub struct SizeLimit {
  priv bytes : Int32
}

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

///|
pub extend SizeLimit with Compare::{compare}

///|
pub extend SizeLimit with Hash::{hash, hash_combine}

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

///|
/// A size limit of `bytes`.
pub fn SizeLimit::bytes(bytes : Int32) -> SizeLimit raise LimitError {
  guard bytes > 0 else { raise NotPositiveSize(bytes~) }
  { bytes, }
}

///|
/// The limit in bytes.
pub fn SizeLimit::to_bytes(self : SizeLimit) -> Int32 {
  self.bytes
}

///|
/// The default maximum size of a received hub message of ASP.NET Core SignalR:
/// 32768 bytes.
pub fn SizeLimit::default_message_size() -> SizeLimit {
  { bytes: 32768, }
}

///|
pub impl Show for SizeLimit with fn output(self, logger) {
  logger.write_string("\{self.bytes} bytes")
}

///|
pub extend SizeLimit with Show::{output, to_string}

///|
/// A limit of a number of items, 1 or more: queued messages or parallel calls.
#derive(Eq, Compare, Hash, Debug)
pub struct CountLimit {
  priv count : Int32
}

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

///|
pub extend CountLimit with Compare::{compare}

///|
pub extend CountLimit with Hash::{hash, hash_combine}

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

///|
/// A limit of `count` items.
pub fn CountLimit::of(count : Int32) -> CountLimit raise LimitError {
  guard count > 0 else { raise NotPositiveCount(count~) }
  { count, }
}

///|
/// The limit as a number.
pub fn CountLimit::to_int(self : CountLimit) -> Int32 {
  self.count
}

///|
/// The default number of calls of one connection that run at the same time, as
/// in ASP.NET Core SignalR: 1, so that the calls run in the order of arrival.
pub fn CountLimit::default_parallel_calls() -> CountLimit {
  { count: 1, }
}

///|
/// The default number of outgoing messages that wait for one connection: 128.
pub fn CountLimit::default_outgoing_messages() -> CountLimit {
  { count: 128, }
}

///|
/// The number of UTF-8 bytes of `text`.
pub fn utf8_length(text : StringView) -> Int32 {
  let mut count = 0
  for char in text {
    let code = char.to_int()
    count += if code < 0x80 {
      1
    } else if code < 0x800 {
      2
    } else if code < 0x10000 {
      3
    } else {
      4
    }
  }
  count
}