Use precalculated binary size

Use precalculated binary size

defmodule String do
  @moduledoc %B"""
  A String in Elixir is a UTF-8 encoded binary.

  ## String and binary operations

  The functions in this module act according to the
  Unicode Standard, version 6.2.0. For example,
  `titlecase`, `downcase`, `strip` are provided by this
  module.

  Besides this module, Elixir provides more low-level
  operations that works directly with binaries. Some
  of those can be found in the `Kernel` module, as:

  * `binary_part/2` and `binary_part/3` - retrieves part of the binary
  * `bit_size/1` and `byte_size/1` - size related functions
  * `is_bitstring/1` and `is_binary/1` - type checking function
  * Plus a bunch of conversion functions, like `binary_to_atom/2`,
    `binary_to_integer/2`, `binary_to_term/1` and their opposite
    like `integer_to_binary/2`

  Finally, [the `:binary` module](http://erlang.org/doc/man/binary.html)
  provides a couple other functions that works on the byte level.

  ## Codepoints and graphemes

  As per the Unicode Standard, a codepoint is an Unicode
  Character, which may be represented by one or more bytes.
  For example, the character "é" is represented with two
  bytes:

      iex> string = "é"
      ...> byte_size(string)
      2

  Furthermore, this module also presents the concept of
  graphemes, which are multiple characters that may be
  "perceived as a single character" by readers. For example,
  the same "é" character written above could be represented
  by the letter "e" followed by the accent ́:

      iex> string = "\x{0065}\x{0301}"
      ...> byte_size(string)
      3

  Although the example above is made of two characters, it is
  perceived by users as one.

  Graphemes can also be two characters that are interpreted
  as one by some languages. For example, some languages may
  consider "ch" as a grapheme. However, since this information
  depends on the locale, it is not taken into account by this
  module.

  In general, the functions in this module rely on the Unicode
  Standard, but does not contain any of the locale specific
  behaviour.

  ## Integer codepoints

  Although codepoints could be represented as integers, this
  module represents all codepoints as strings. For example:

      iex> String.codepoints("josé")
      ["j", "o", "s", "é"]

  There are a couple of ways to retrieve a character integer
  codepoint. One may use the `?` special macro:

      iex> ?j
      106
      iex> ?é
      233

  Or also via pattern matching:

      iex> << eacute :: utf8 >> = "é"
      ...> eacute
      233

  As we have seen above, codepoints can be inserted into
  a string by their hexadecimal code:

      "jos\x{0065}\x{0301}" #=>
      "josé"

  ## Self-synchronization

  The UTF-8 encoding is self-synchronizing. This means that
  if malformed data (i.e., data that is not possible according
  to the definition of the encoding) is encountered, only one
  codepoint needs to be rejected.

  This module relies on this behaviour to ignore such invalid
  characters. For example, `String.length` is going to return
  a correct result even if an invalid codepoint is fed into it.

  In other words, this module expects invalid data to be detected
  when retrieving data from the external source. For example, a
  driver that reads strings from a database will be the one
  responsible to check the validity of the encoding.
  """

  @type t :: binary
  @type codepoint :: t
  @type grapheme :: t

  @doc """
  Checks if a string is printable considering it is encoded
  as UTF-8. Returns true if so, false otherwise.

  ## Examples

      iex> String.printable?("abc")
      true

  """
  @spec printable?(t) :: boolean

  def printable?(<< h :: utf8, t :: binary >>)
      when h in ?\040..?\176
      when h in 0xA0..0xD7FF
      when h in 0xE000..0xFFFD
      when h in 0x10000..0x10FFFF do
    printable?(t)
  end

  def printable?(<<?\n, t :: binary>>), do: printable?(t)
  def printable?(<<?\r, t :: binary>>), do: printable?(t)
  def printable?(<<?\t, t :: binary>>), do: printable?(t)
  def printable?(<<?\v, t :: binary>>), do: printable?(t)
  def printable?(<<?\b, t :: binary>>), do: printable?(t)
  def printable?(<<?\f, t :: binary>>), do: printable?(t)
  def printable?(<<?\e, t :: binary>>), do: printable?(t)
  def printable?(<<?\a, t :: binary>>), do: printable?(t)

  def printable?(<<>>), do: true
  def printable?(_),    do: false

  @doc """
  Splits a string on sub strings at each Unicode whitespace
  occurrence with leading and trailing whitespace ignored.

  ## Examples

      iex> String.split("foo bar")
      ["foo", "bar"]
      iex> String.split("foo" <> <<194,133>> <> "bar")
      ["foo", "bar"]
      iex> String.split(" foo bar ")
      ["foo", "bar"]

  """
  @spec split(t) :: [t]
  defdelegate split(binary), to: String.Unicode

  @doc """
  Divides a string into sub strings based on a pattern,
  returning a list of these sub string. The pattern can
  be a string, a list of strings or a regular expression.

  The string is split into as many parts as possible by
  default, unless the `global` option is set to false.

  ## Examples

      iex> String.split("a,b,c", ",")
      ["a", "b", "c"]
      iex> String.split("a,b,c", ",", global: false)
      ["a", "b,c"]

      iex> String.split("1,2 3,4", [" ", ","])
      ["1", "2", "3", "4"]

      iex> String.split("a,b,c", %r{,})
      ["a", "b", "c"]
      iex> String.split("a,b,c", %r{,}, global: false)
      ["a", "b,c"]
      iex> String.split("a,b", %r{\\.})
      ["a,b"]

  """
  @spec split(t, t | [t] | Regex.t) :: [t]
  @spec split(t, t | [t] | Regex.t, Keyword.t) :: [t]
  def split(binary, pattern, options // [])

  def split(binary, pattern, options) when is_regex(pattern) do
    Regex.split(pattern, binary, global: options[:global])
  end

  def split(binary, pattern, options) do
    opts = if options[:global] != false, do: [:global], else: []
    :binary.split(binary, pattern, opts)
  end

  @doc """
  Convert all characters on the given string to upcase.

  ## Examples

      iex> String.upcase("abcd")
      "ABCD"
      iex> String.upcase("ab 123 xpto")
      "AB 123 XPTO"
      iex> String.upcase("josé")
      "JOSÉ"

  """
  @spec upcase(t) :: t
  defdelegate upcase(binary), to: String.Unicode

  @doc """
  Convert all characters on the given string to downcase.

  ## Examples

      iex> String.downcase("ABCD")
      "abcd"
      iex> String.downcase("AB 123 XPTO")
      "ab 123 xpto"
      iex> String.downcase("JOSÉ")
      "josé"

  """
  @spec downcase(t) :: t
  defdelegate downcase(binary), to: String.Unicode

  @doc """
  Converts the first character in the given string to
  titlecase and the remaining to downcase.

  This relies on the titlecase information provided
  by the Unicode Standard. Note this function makes
  no attempt in capitalizing all words in the string
  (usually known as titlecase).

  ## Examples

      iex> String.capitalize("abcd")
      "Abcd"
      iex> String.capitalize("ﬁn")
      "Fin"
      iex> String.capitalize("josé")
      "José"

  """
  @spec capitalize(t) :: t
  def capitalize(string) when is_binary(string) do
    { char, rest } = String.Unicode.titlecase_once(string)
    char <> downcase(rest)
  end

  @doc """
  Returns a string where trailing Unicode whitespace
  has been removed.

  ## Examples

      iex> String.rstrip("   abc  ")
      "   abc"

  """
  @spec rstrip(t) :: t
  defdelegate rstrip(binary), to: String.Unicode

  @doc """
  Returns a string where trailing `char` have been removed.

  ## Examples

      iex> String.rstrip("   abc _", ?_)
      "   abc "

  """
  @spec rstrip(t, char) :: t

  def rstrip("", _char), do: ""

  # Do a quick check before we traverse the whole
  # binary. :binary.last is a fast operation (it
  # does not traverse the whole binary).
  def rstrip(string, char) do
    if :binary.last(string) == char do
      do_rstrip(string, "", char)
    else
      string
    end
  end

  defp do_rstrip(<<char, string :: binary>>, buffer, char) do
    do_rstrip(string, <<char, buffer :: binary>>, char)
  end

  defp do_rstrip(<<char, string :: binary>>, buffer, another_char) do
    <<buffer :: binary, char, do_rstrip(string, "", another_char) :: binary>>
  end

  defp do_rstrip(<<>>, _, _) do
    <<>>
  end

  @doc """
  Returns a string where leading Unicode whitespace
  has been removed.

  ## Examples

      iex> String.lstrip("   abc  ")
      "abc  "

  """
  defdelegate lstrip(binary), to: String.Unicode

  @doc """
  Returns a string where leading `char` have been removed.

  ## Examples

      iex> String.lstrip("_  abc  _", ?_)
      "  abc  _"

  """

  @spec lstrip(t, char) :: t

  def lstrip(<<char, rest :: binary>>, char) do
    <<lstrip(rest, char) :: binary>>
  end

  def lstrip(other, _char) do
    other
  end

  @doc """
  Returns a string where leading/trailing Unicode whitespace
  has been removed.

  ## Examples

      iex> String.strip("   abc  ")
      "abc"

  """
  @spec strip(t) :: t

  def strip(string) do
    rstrip(lstrip(string))
  end

  @doc """
  Returns a string where leading/trailing `char` have been
  removed.

  ## Examples

      iex> String.strip("a  abc  a", ?a)
      "  abc  "

  """
  @spec strip(t, char) :: t

  def strip(string, char) do
    rstrip(lstrip(string, char), char)
  end

  @doc """
  Returns a new binary based on `subject` by replacing the parts
  matching `pattern` for `replacement`. By default, it replaces
  all entries, except if the `global` option is set to false.

  If the replaced part must be used in `replacement`, then the
  position or the positions where it is to be inserted must be
  specified by using the option `insert_replaced`.

  ## Examples

      iex> String.replace("a,b,c", ",", "-")
      "a-b-c"
      iex> String.replace("a,b,c", ",", "-", global: false)
      "a-b,c"
      iex> String.replace("a,b,c", "b", "[]", insert_replaced: 1)
      "a,[b],c"
      iex> String.replace("a,b,c", ",", "[]", insert_replaced: 2)
      "a[],b[],c"
      iex> String.replace("a,b,c", ",", "[]", insert_replaced: [1,1])
      "a[,,]b[,,]c"

  """
  @spec replace(t, t, t) :: t
  @spec replace(t, t, t, Keyword.t) :: t

  def replace(subject, pattern, replacement, options // []) do
    opts = translate_replace_options(options)
    :binary.replace(subject, pattern, replacement, opts)
  end

  defp translate_replace_options(options) do
    opts = if options[:global] != false, do: [:global], else: []

    if insert = options[:insert_replaced] do
      opts = [{:insert_replaced,insert}|opts]
    end

    opts
  end

  @doc """
  Returns a binary `subject` duplicated `n` times.

  ## Examples

      iex> String.duplicate("abc", 1)
      "abc"
      iex> String.duplicate("abc", 2)
      "abcabc"

  """
  @spec duplicate(t, pos_integer) :: t
  def duplicate(subject, n) when is_integer(n) and n > 0 do
    :binary.copy(subject, n)
  end

  @doc """
  Returns all codepoints in the string.

  ## Examples

      iex> String.codepoints("josé")
      ["j", "o", "s", "é"]
      iex> String.codepoints("оптими зации")
      ["о","п","т","и","м","и"," ","з","а","ц","и","и"]
      iex> String.codepoints("ἅἪῼ")
      ["ἅ","Ἢ","ῼ"]

  """
  @spec codepoints(t) :: [codepoint]
  defdelegate codepoints(string), to: String.Unicode

  @doc """
  Returns the next codepoint in a String.

  The result is a tuple with the codepoint and the
  remaining of the string or `:no_codepoint` in case
  the string reached its end.

  As the other functions in the String module, this
  function does not check for the validity of the codepoint.
  That said, if an invalid codepoint is found, it will
  be returned by this function.

  ## Examples

      iex> String.next_codepoint("josé")
      { "j", "osé" }

  """
  @spec next_codepoint(t) :: {codepoint, t} | :no_codepoint
  defdelegate next_codepoint(string), to: String.Unicode

  @doc %B"""
  Checks whether `str` contains only valid characters.

  ## Examples

      iex> String.valid?("a")
      true
      iex> String.valid?("ø")
      true
      iex> String.valid?(<<0xffff :: 16>>)
      false
      iex> String.valid?("asd" <> <<0xffff :: 16>>)
      false

  """
  @spec valid?(t) :: boolean

  noncharacters = Enum.to_list(?\x{FDD0}..?\x{FDEF}) ++
    [ ?\x{0FFFE}, ?\x{0FFFF}, ?\x{1FFFE}, ?\x{1FFFF}, ?\x{2FFFE}, ?\x{2FFFF},
      ?\x{3FFFE}, ?\x{3FFFF}, ?\x{4FFFE}, ?\x{4FFFF}, ?\x{5FFFE}, ?\x{5FFFF},
      ?\x{6FFFE}, ?\x{6FFFF}, ?\x{7FFFE}, ?\x{7FFFF}, ?\x{8FFFE}, ?\x{8FFFF},
      ?\x{9FFFE}, ?\x{9FFFF}, ?\x{10FFFE}, ?\x{10FFFF} ]

  lc noncharacter inlist noncharacters do
    def valid?(<< unquote(noncharacter) :: utf8, _ :: binary >>), do: false
  end

  def valid?(<<_ :: utf8, t :: binary>>), do: valid?(t)
  def valid?(<<>>), do: true
  def valid?(_), do: false

  @doc %B"""
  Checks whether `str` is a valid character.

  All characters are codepoints, but some codepoints
  are not valid characters. They may be reserved, private,
  or other.

  More info at: http://en.wikipedia.org/wiki/Mapping_of_Unicode_characters#Noncharacters

  ## Examples

      iex> String.valid_character?("a")
      true
      iex> String.valid_character?("ø")
      true
      iex> String.valid_character?("\x{ffff}")
      false

  """
  @spec valid_character?(t) :: boolean

  def valid_character?(<<_ :: utf8>> = codepoint), do: valid?(codepoint)
  def valid_character?(_), do: false

  @doc %B"""
  Checks whether `str` is a valid codepoint.

  Note that the empty string is considered invalid, as are
  strings containing multiple codepoints.

  ## Examples

      iex> String.valid_codepoint?("a")
      true
      iex> String.valid_codepoint?("ø")
      true
      iex> String.valid_codepoint?(<<0xffff :: 16>>)
      false
      iex> String.valid_codepoint?("asdf")
      false

  """
  @spec valid_codepoint?(codepoint) :: boolean
  def valid_codepoint?(<<_ :: utf8>>), do: true
  def valid_codepoint?(_), do: false

  @doc """
  Returns unicode graphemes in the string.

  ## Examples

      iex> String.graphemes("Ā̀stute")
      ["Ā̀","s","t","u","t","e"]

  """
  @spec graphemes(t) :: [grapheme]
  defdelegate graphemes(string), to: String.Unicode

  @doc """
  Returns the next grapheme in a String.

  The result is a tuple with the grapheme and the
  remaining of the string or `:no_grapheme` in case
  the String reached its end.

  ## Examples

      iex> String.next_grapheme("josé")
      { "j", "osé" }

  """
  @spec next_grapheme(t) :: { grapheme, t } | :no_grapheme
  defdelegate next_grapheme(string), to: String.Unicode

  @doc """
  Returns the first grapheme from an utf8 string,
  nil if the string is empty.

  ## Examples

      iex> String.first("elixir")
      "e"
      iex> String.first("եոգլի")
      "ե"

  """
  @spec first(t) :: grapheme | nil
  def first(string) do
    case next_grapheme(string) do
      { char, _ } -> char
      :no_grapheme -> nil
    end
  end

  @doc """
  Returns the last grapheme from an utf8 string,
  nil if the string is empty.

  ## Examples

      iex> String.last("elixir")
      "r"
      iex> String.last("եոգլի")
      "ի"

  """
  @spec last(t) :: grapheme | nil
  def last(string) do
    do_last(next_grapheme(string), nil)
  end

  defp do_last({char, rest}, _) do
    do_last(next_grapheme(rest), char)
  end

  defp do_last(:no_grapheme, last_char), do: last_char

  @doc """
  Returns the number of unicode graphemes in an utf8 string.

  ## Examples

      iex> String.length("elixir")
      6
      iex> String.length("եոգլի")
      5

  """
  @spec length(t) :: non_neg_integer
  def length(string) do
    do_length(next_grapheme(string))
  end

  defp do_length({_, rest}) do
    1 + do_length(next_grapheme(rest))
  end

  defp do_length(:no_grapheme), do: 0

  @doc """
  Returns the grapheme in the `position` of the given utf8 `string`.
  If `position` is greater than `string` length, than it returns `nil`.

  ## Examples

      iex> String.at("elixir", 0)
      "e"
      iex> String.at("elixir", 1)
      "l"
      iex> String.at("elixir", 10)
      nil
      iex> String.at("elixir", -1)
      "r"
      iex> String.at("elixir", -10)
      nil

  """
  @spec at(t, integer) :: grapheme | nil

  def at(string, position) when position >= 0 do
    do_at(next_grapheme(string), position, 0)
  end

  def at(string, position) when position < 0 do
    real_pos = do_length(next_grapheme(string)) - abs(position)
    case real_pos >= 0 do
      true  -> do_at(next_grapheme(string), real_pos, 0)
      false -> nil
    end
  end

  defp do_at({_ , rest}, desired_pos, current_pos) when desired_pos > current_pos do
    do_at(next_grapheme(rest), desired_pos, current_pos + 1)
  end

  defp do_at({char, _}, desired_pos, current_pos) when desired_pos == current_pos do
    char
  end

  defp do_at(:no_grapheme, _, _), do: nil

  @doc """
  Returns a substring starting at the offset given by the first, and
  a length given by the second.
  If the offset is greater than string length, than it returns nil.

  ## Examples

      iex> String.slice("elixir", 1, 3)
      "lix"
      iex> String.slice("elixir", 1, 10)
      "lixir"
      iex> String.slice("elixir", 10, 3)
      nil
      iex> String.slice("elixir", -4, 4)
      "ixir"
      iex> String.slice("elixir", -10, 3)
      nil
      iex> String.slice("a", 0, 1500)
      "a"
      iex> String.slice("a", 1, 1500)
      ""
      iex> String.slice("a", 2, 1500)
      nil

  """
  @spec slice(t, integer, integer) :: grapheme | nil

  def slice(string, start, len) when start >= 0 do
    do_slice(next_grapheme(string), start, start + len - 1, 0, "")
  end

  def slice(string, start, len) when start < 0 do
    real_start_pos = do_length(next_grapheme(string)) - abs(start)
    case real_start_pos >= 0 do
      true -> do_slice(next_grapheme(string), real_start_pos, real_start_pos + len - 1, 0, "")
      false -> nil
    end
  end

  defp do_slice(_, start_pos, last_pos, _, _) when start_pos > last_pos do
    nil
  end

  defp do_slice({_, rest}, start_pos, last_pos, current_pos, acc) when current_pos < start_pos do
    do_slice(next_grapheme(rest), start_pos, last_pos, current_pos + 1, acc)
  end

  defp do_slice({char, rest}, start_pos, last_pos, current_pos, acc) when current_pos >= start_pos and current_pos < last_pos do
    do_slice(next_grapheme(rest), start_pos, last_pos, current_pos + 1, acc <> char)
  end

  defp do_slice({char, _}, start_pos, last_pos, current_pos, acc) when current_pos >= start_pos and current_pos == last_pos do
    acc <> char
  end

  defp do_slice(:no_grapheme, start_pos, _, current_pos, acc) when start_pos == current_pos do
    acc
  end

  defp do_slice(:no_grapheme, _, _, _, acc) do
    case acc do
      "" -> nil
      _ -> acc
    end
  end

  @doc """
  Converts a string to an integer. If successful, returns a
  tuple of form {integer, remainder of string}. If unsuccessful,
  returns :error.

  ## Examples

      iex> String.to_integer("34")
      {34,""}
      iex> String.to_integer("34.5")
      {34,".5"}
      iex> String.to_integer("three")
      :error

  """
  @spec to_integer(t) :: {integer, t} | :error

  def to_integer(string) do
    {result, remainder} = :string.to_integer(binary_to_list(string))
    case result do
      :error -> :error
      _ -> {result, list_to_binary(remainder)}
    end
  end

  @doc """
  Converts a string to a float. If successful, returns a
  tuple of form {float, remainder of string}. If unsuccessful,
  returns :error. If given an integer value, will return
  same as to_integer/1.

  ## Examples

      iex> String.to_float("34")
      {34.0,""}
      iex> String.to_float("34.25")
      {34.25,""}
	    iex> String.to_float("56.5xyz")
	    {56.5,"xyz"}
      iex> String.to_float("pi")
      :error

  """
  @spec to_float(t) :: {integer, t} | :error

  def to_float(string) do
    charlist = binary_to_list(string)
    {result, remainder} = :string.to_float(charlist)
    case result do
      :error ->
        {int_result, int_remainder} = :string.to_integer(charlist)
        case int_result do
          :error -> :error
          _ -> {float(int_result), list_to_binary(int_remainder)}
        end
      _ -> {result, list_to_binary(remainder)}
    end
  end

  @doc """
  Returns true if `string` starts with any of the prefixes given, otherwise
  false. `prefixes` can be either a single prefix or a list of prefixes.

  ## Examples

      iex> String.starts_with? "elixir", "eli"
      true
      iex> String.starts_with? "elixir", ["erlang", "elixir"]
      true
      iex> String.starts_with? "elixir", ["erlang", "ruby"]
      false

  """
  @spec starts_with?(t, t | [t]) :: boolean

  def starts_with?(string, prefixes) do
    case :binary.match(string, prefixes) do
      :nomatch -> false
      {0, _}   -> true
      _        -> false
    end
  end

  @doc """
  Returns true if `string` ends with any of the suffixes given, otherwise
  false. `suffixes` can be either a single suffix or a list of suffixes.

  ## Examples

      iex> String.ends_with? "language", "age"
      true
      iex> String.ends_with? "language", ["youth", "age"]
      true
      iex> String.ends_with? "language", ["youth", "elixir"]
      false

  """
  @spec ends_with?(t, t | [t]) :: boolean

  def ends_with?(string, suffixes) when is_list(suffixes) do
    string_size = size(string)
    Enum.any? suffixes, fn suffix ->
      suffix_size = size(suffix)
      (suffix_size <= string_size) and suffix == :binary.part(string, {string_size, -suffix_size})
    end
  end

  def ends_with?(string, suffix), do: ends_with?(string, [ suffix ])

end

defmodule String do
  @moduledoc %B"""
  A String in Elixir is a UTF-8 encoded binary.

  ## String and binary operations

  The functions in this module act according to the
  Unicode Standard, version 6.2.0. For example,
  `titlecase`, `downcase`, `strip` are provided by this
  module.

  Besides this module, Elixir provides more low-level
  operations that works directly with binaries. Some
  of those can be found in the `Kernel` module, as:

  * `binary_part/2` and `binary_part/3` - retrieves part of the binary
  * `bit_size/1` and `byte_size/1` - size related functions
  * `is_bitstring/1` and `is_binary/1` - type checking function
  * Plus a bunch of conversion functions, like `binary_to_atom/2`,
    `binary_to_integer/2`, `binary_to_term/1` and their opposite
    like `integer_to_binary/2`

  Finally, [the `:binary` module](http://erlang.org/doc/man/binary.html)
  provides a couple other functions that works on the byte level.

  ## Codepoints and graphemes

  As per the Unicode Standard, a codepoint is an Unicode
  Character, which may be represented by one or more bytes.
  For example, the character "é" is represented with two
  bytes:

      iex> string = "é"
      ...> byte_size(string)
      2

  Furthermore, this module also presents the concept of
  graphemes, which are multiple characters that may be
  "perceived as a single character" by readers. For example,
  the same "é" character written above could be represented
  by the letter "e" followed by the accent ́:

      iex> string = "\x{0065}\x{0301}"
      ...> byte_size(string)
      3

  Although the example above is made of two characters, it is
  perceived by users as one.

  Graphemes can also be two characters that are interpreted
  as one by some languages. For example, some languages may
  consider "ch" as a grapheme. However, since this information
  depends on the locale, it is not taken into account by this
  module.

  In general, the functions in this module rely on the Unicode
  Standard, but does not contain any of the locale specific
  behaviour.

  ## Integer codepoints

  Although codepoints could be represented as integers, this
  module represents all codepoints as strings. For example:

      iex> String.codepoints("josé")
      ["j", "o", "s", "é"]

  There are a couple of ways to retrieve a character integer
  codepoint. One may use the `?` special macro:

      iex> ?j
      106
      iex> ?é
      233

  Or also via pattern matching:

      iex> << eacute :: utf8 >> = "é"
      ...> eacute
      233

  As we have seen above, codepoints can be inserted into
  a string by their hexadecimal code:

      "jos\x{0065}\x{0301}" #=>
      "josé"

  ## Self-synchronization

  The UTF-8 encoding is self-synchronizing. This means that
  if malformed data (i.e., data that is not possible according
  to the definition of the encoding) is encountered, only one
  codepoint needs to be rejected.

  This module relies on this behaviour to ignore such invalid
  characters. For example, `String.length` is going to return
  a correct result even if an invalid codepoint is fed into it.

  In other words, this module expects invalid data to be detected
  when retrieving data from the external source. For example, a
  driver that reads strings from a database will be the one
  responsible to check the validity of the encoding.
  """

  @type t :: binary
  @type codepoint :: t
  @type grapheme :: t

  @doc """
  Checks if a string is printable considering it is encoded
  as UTF-8. Returns true if so, false otherwise.

  ## Examples

      iex> String.printable?("abc")
      true

  """
  @spec printable?(t) :: boolean

  def printable?(<< h :: utf8, t :: binary >>)
      when h in ?\040..?\176
      when h in 0xA0..0xD7FF
      when h in 0xE000..0xFFFD
      when h in 0x10000..0x10FFFF do
    printable?(t)
  end

  def printable?(<<?\n, t :: binary>>), do: printable?(t)
  def printable?(<<?\r, t :: binary>>), do: printable?(t)
  def printable?(<<?\t, t :: binary>>), do: printable?(t)
  def printable?(<<?\v, t :: binary>>), do: printable?(t)
  def printable?(<<?\b, t :: binary>>), do: printable?(t)
  def printable?(<<?\f, t :: binary>>), do: printable?(t)
  def printable?(<<?\e, t :: binary>>), do: printable?(t)
  def printable?(<<?\a, t :: binary>>), do: printable?(t)

  def printable?(<<>>), do: true
  def printable?(_),    do: false

  @doc """
  Splits a string on sub strings at each Unicode whitespace
  occurrence with leading and trailing whitespace ignored.

  ## Examples

      iex> String.split("foo bar")
      ["foo", "bar"]
      iex> String.split("foo" <> <<194,133>> <> "bar")
      ["foo", "bar"]
      iex> String.split(" foo bar ")
      ["foo", "bar"]

  """
  @spec split(t) :: [t]
  defdelegate split(binary), to: String.Unicode

  @doc """
  Divides a string into sub strings based on a pattern,
  returning a list of these sub string. The pattern can
  be a string, a list of strings or a regular expression.

  The string is split into as many parts as possible by
  default, unless the `global` option is set to false.

  ## Examples

      iex> String.split("a,b,c", ",")
      ["a", "b", "c"]
      iex> String.split("a,b,c", ",", global: false)
      ["a", "b,c"]

      iex> String.split("1,2 3,4", [" ", ","])
      ["1", "2", "3", "4"]

      iex> String.split("a,b,c", %r{,})
      ["a", "b", "c"]
      iex> String.split("a,b,c", %r{,}, global: false)
      ["a", "b,c"]
      iex> String.split("a,b", %r{\\.})
      ["a,b"]

  """
  @spec split(t, t | [t] | Regex.t) :: [t]
  @spec split(t, t | [t] | Regex.t, Keyword.t) :: [t]
  def split(binary, pattern, options // [])

  def split(binary, pattern, options) when is_regex(pattern) do
    Regex.split(pattern, binary, global: options[:global])
  end

  def split(binary, pattern, options) do
    opts = if options[:global] != false, do: [:global], else: []
    :binary.split(binary, pattern, opts)
  end

  @doc """
  Convert all characters on the given string to upcase.

  ## Examples

      iex> String.upcase("abcd")
      "ABCD"
      iex> String.upcase("ab 123 xpto")
      "AB 123 XPTO"
      iex> String.upcase("josé")
      "JOSÉ"

  """
  @spec upcase(t) :: t
  defdelegate upcase(binary), to: String.Unicode

  @doc """
  Convert all characters on the given string to downcase.

  ## Examples

      iex> String.downcase("ABCD")
      "abcd"
      iex> String.downcase("AB 123 XPTO")
      "ab 123 xpto"
      iex> String.downcase("JOSÉ")
      "josé"

  """
  @spec downcase(t) :: t
  defdelegate downcase(binary), to: String.Unicode

  @doc """
  Converts the first character in the given string to
  titlecase and the remaining to downcase.

  This relies on the titlecase information provided
  by the Unicode Standard. Note this function makes
  no attempt in capitalizing all words in the string
  (usually known as titlecase).

  ## Examples

      iex> String.capitalize("abcd")
      "Abcd"
      iex> String.capitalize("ﬁn")
      "Fin"
      iex> String.capitalize("josé")
      "José"

  """
  @spec capitalize(t) :: t
  def capitalize(string) when is_binary(string) do
    { char, rest } = String.Unicode.titlecase_once(string)
    char <> downcase(rest)
  end

  @doc """
  Returns a string where trailing Unicode whitespace
  has been removed.

  ## Examples

      iex> String.rstrip("   abc  ")
      "   abc"

  """
  @spec rstrip(t) :: t
  defdelegate rstrip(binary), to: String.Unicode

  @doc """
  Returns a string where trailing `char` have been removed.

  ## Examples

      iex> String.rstrip("   abc _", ?_)
      "   abc "

  """
  @spec rstrip(t, char) :: t

  def rstrip("", _char), do: ""

  # Do a quick check before we traverse the whole
  # binary. :binary.last is a fast operation (it
  # does not traverse the whole binary).
  def rstrip(string, char) do
    if :binary.last(string) == char do
      do_rstrip(string, "", char)
    else
      string
    end
  end

  defp do_rstrip(<<char, string :: binary>>, buffer, char) do
    do_rstrip(string, <<char, buffer :: binary>>, char)
  end

  defp do_rstrip(<<char, string :: binary>>, buffer, another_char) do
    <<buffer :: binary, char, do_rstrip(string, "", another_char) :: binary>>
  end

  defp do_rstrip(<<>>, _, _) do
    <<>>
  end

  @doc """
  Returns a string where leading Unicode whitespace
  has been removed.

  ## Examples

      iex> String.lstrip("   abc  ")
      "abc  "

  """
  defdelegate lstrip(binary), to: String.Unicode

  @doc """
  Returns a string where leading `char` have been removed.

  ## Examples

      iex> String.lstrip("_  abc  _", ?_)
      "  abc  _"

  """

  @spec lstrip(t, char) :: t

  def lstrip(<<char, rest :: binary>>, char) do
    <<lstrip(rest, char) :: binary>>
  end

  def lstrip(other, _char) do
    other
  end

  @doc """
  Returns a string where leading/trailing Unicode whitespace
  has been removed.

  ## Examples

      iex> String.strip("   abc  ")
      "abc"

  """
  @spec strip(t) :: t

  def strip(string) do
    rstrip(lstrip(string))
  end

  @doc """
  Returns a string where leading/trailing `char` have been
  removed.

  ## Examples

      iex> String.strip("a  abc  a", ?a)
      "  abc  "

  """
  @spec strip(t, char) :: t

  def strip(string, char) do
    rstrip(lstrip(string, char), char)
  end

  @doc """
  Returns a new binary based on `subject` by replacing the parts
  matching `pattern` for `replacement`. By default, it replaces
  all entries, except if the `global` option is set to false.

  If the replaced part must be used in `replacement`, then the
  position or the positions where it is to be inserted must be
  specified by using the option `insert_replaced`.

  ## Examples

      iex> String.replace("a,b,c", ",", "-")
      "a-b-c"
      iex> String.replace("a,b,c", ",", "-", global: false)
      "a-b,c"
      iex> String.replace("a,b,c", "b", "[]", insert_replaced: 1)
      "a,[b],c"
      iex> String.replace("a,b,c", ",", "[]", insert_replaced: 2)
      "a[],b[],c"
      iex> String.replace("a,b,c", ",", "[]", insert_replaced: [1,1])
      "a[,,]b[,,]c"

  """
  @spec replace(t, t, t) :: t
  @spec replace(t, t, t, Keyword.t) :: t

  def replace(subject, pattern, replacement, options // []) do
    opts = translate_replace_options(options)
    :binary.replace(subject, pattern, replacement, opts)
  end

  defp translate_replace_options(options) do
    opts = if options[:global] != false, do: [:global], else: []

    if insert = options[:insert_replaced] do
      opts = [{:insert_replaced,insert}|opts]
    end

    opts
  end

  @doc """
  Returns a binary `subject` duplicated `n` times.

  ## Examples

      iex> String.duplicate("abc", 1)
      "abc"
      iex> String.duplicate("abc", 2)
      "abcabc"

  """
  @spec duplicate(t, pos_integer) :: t
  def duplicate(subject, n) when is_integer(n) and n > 0 do
    :binary.copy(subject, n)
  end

  @doc """
  Returns all codepoints in the string.

  ## Examples

      iex> String.codepoints("josé")
      ["j", "o", "s", "é"]
      iex> String.codepoints("оптими зации")
      ["о","п","т","и","м","и"," ","з","а","ц","и","и"]
      iex> String.codepoints("ἅἪῼ")
      ["ἅ","Ἢ","ῼ"]

  """
  @spec codepoints(t) :: [codepoint]
  defdelegate codepoints(string), to: String.Unicode

  @doc """
  Returns the next codepoint in a String.

  The result is a tuple with the codepoint and the
  remaining of the string or `:no_codepoint` in case
  the string reached its end.

  As the other functions in the String module, this
  function does not check for the validity of the codepoint.
  That said, if an invalid codepoint is found, it will
  be returned by this function.

  ## Examples

      iex> String.next_codepoint("josé")
      { "j", "osé" }

  """
  @spec next_codepoint(t) :: {codepoint, t} | :no_codepoint
  defdelegate next_codepoint(string), to: String.Unicode

  @doc %B"""
  Checks whether `str` contains only valid characters.

  ## Examples

      iex> String.valid?("a")
      true
      iex> String.valid?("ø")
      true
      iex> String.valid?(<<0xffff :: 16>>)
      false
      iex> String.valid?("asd" <> <<0xffff :: 16>>)
      false

  """
  @spec valid?(t) :: boolean

  noncharacters = Enum.to_list(?\x{FDD0}..?\x{FDEF}) ++
    [ ?\x{0FFFE}, ?\x{0FFFF}, ?\x{1FFFE}, ?\x{1FFFF}, ?\x{2FFFE}, ?\x{2FFFF},
      ?\x{3FFFE}, ?\x{3FFFF}, ?\x{4FFFE}, ?\x{4FFFF}, ?\x{5FFFE}, ?\x{5FFFF},
      ?\x{6FFFE}, ?\x{6FFFF}, ?\x{7FFFE}, ?\x{7FFFF}, ?\x{8FFFE}, ?\x{8FFFF},
      ?\x{9FFFE}, ?\x{9FFFF}, ?\x{10FFFE}, ?\x{10FFFF} ]

  lc noncharacter inlist noncharacters do
    def valid?(<< unquote(noncharacter) :: utf8, _ :: binary >>), do: false
  end

  def valid?(<<_ :: utf8, t :: binary>>), do: valid?(t)
  def valid?(<<>>), do: true
  def valid?(_), do: false

  @doc %B"""
  Checks whether `str` is a valid character.

  All characters are codepoints, but some codepoints
  are not valid characters. They may be reserved, private,
  or other.

  More info at: http://en.wikipedia.org/wiki/Mapping_of_Unicode_characters#Noncharacters

  ## Examples

      iex> String.valid_character?("a")
      true
      iex> String.valid_character?("ø")
      true
      iex> String.valid_character?("\x{ffff}")
      false

  """
  @spec valid_character?(t) :: boolean

  def valid_character?(<<_ :: utf8>> = codepoint), do: valid?(codepoint)
  def valid_character?(_), do: false

  @doc %B"""
  Checks whether `str` is a valid codepoint.

  Note that the empty string is considered invalid, as are
  strings containing multiple codepoints.

  ## Examples

      iex> String.valid_codepoint?("a")
      true
      iex> String.valid_codepoint?("ø")
      true
      iex> String.valid_codepoint?(<<0xffff :: 16>>)
      false
      iex> String.valid_codepoint?("asdf")
      false

  """
  @spec valid_codepoint?(codepoint) :: boolean
  def valid_codepoint?(<<_ :: utf8>>), do: true
  def valid_codepoint?(_), do: false

  @doc """
  Returns unicode graphemes in the string.

  ## Examples

      iex> String.graphemes("Ā̀stute")
      ["Ā̀","s","t","u","t","e"]

  """
  @spec graphemes(t) :: [grapheme]
  defdelegate graphemes(string), to: String.Unicode

  @doc """
  Returns the next grapheme in a String.

  The result is a tuple with the grapheme and the
  remaining of the string or `:no_grapheme` in case
  the String reached its end.

  ## Examples

      iex> String.next_grapheme("josé")
      { "j", "osé" }

  """
  @spec next_grapheme(t) :: { grapheme, t } | :no_grapheme
  defdelegate next_grapheme(string), to: String.Unicode

  @doc """
  Returns the first grapheme from an utf8 string,
  nil if the string is empty.

  ## Examples

      iex> String.first("elixir")
      "e"
      iex> String.first("եոգլի")
      "ե"

  """
  @spec first(t) :: grapheme | nil
  def first(string) do
    case next_grapheme(string) do
      { char, _ } -> char
      :no_grapheme -> nil
    end
  end

  @doc """
  Returns the last grapheme from an utf8 string,
  nil if the string is empty.

  ## Examples

      iex> String.last("elixir")
      "r"
      iex> String.last("եոգլի")
      "ի"

  """
  @spec last(t) :: grapheme | nil
  def last(string) do
    do_last(next_grapheme(string), nil)
  end

  defp do_last({char, rest}, _) do
    do_last(next_grapheme(rest), char)
  end

  defp do_last(:no_grapheme, last_char), do: last_char

  @doc """
  Returns the number of unicode graphemes in an utf8 string.

  ## Examples

      iex> String.length("elixir")
      6
      iex> String.length("եոգլի")
      5

  """
  @spec length(t) :: non_neg_integer
  def length(string) do
    do_length(next_grapheme(string))
  end

  defp do_length({_, rest}) do
    1 + do_length(next_grapheme(rest))
  end

  defp do_length(:no_grapheme), do: 0

  @doc """
  Returns the grapheme in the `position` of the given utf8 `string`.
  If `position` is greater than `string` length, than it returns `nil`.

  ## Examples

      iex> String.at("elixir", 0)
      "e"
      iex> String.at("elixir", 1)
      "l"
      iex> String.at("elixir", 10)
      nil
      iex> String.at("elixir", -1)
      "r"
      iex> String.at("elixir", -10)
      nil

  """
  @spec at(t, integer) :: grapheme | nil

  def at(string, position) when position >= 0 do
    do_at(next_grapheme(string), position, 0)
  end

  def at(string, position) when position < 0 do
    real_pos = do_length(next_grapheme(string)) - abs(position)
    case real_pos >= 0 do
      true  -> do_at(next_grapheme(string), real_pos, 0)
      false -> nil
    end
  end

  defp do_at({_ , rest}, desired_pos, current_pos) when desired_pos > current_pos do
    do_at(next_grapheme(rest), desired_pos, current_pos + 1)
  end

  defp do_at({char, _}, desired_pos, current_pos) when desired_pos == current_pos do
    char
  end

  defp do_at(:no_grapheme, _, _), do: nil

  @doc """
  Returns a substring starting at the offset given by the first, and
  a length given by the second.
  If the offset is greater than string length, than it returns nil.

  ## Examples

      iex> String.slice("elixir", 1, 3)
      "lix"
      iex> String.slice("elixir", 1, 10)
      "lixir"
      iex> String.slice("elixir", 10, 3)
      nil
      iex> String.slice("elixir", -4, 4)
      "ixir"
      iex> String.slice("elixir", -10, 3)
      nil
      iex> String.slice("a", 0, 1500)
      "a"
      iex> String.slice("a", 1, 1500)
      ""
      iex> String.slice("a", 2, 1500)
      nil

  """
  @spec slice(t, integer, integer) :: grapheme | nil

  def slice(string, start, len) when start >= 0 do
    do_slice(next_grapheme(string), start, start + len - 1, 0, "")
  end

  def slice(string, start, len) when start < 0 do
    real_start_pos = do_length(next_grapheme(string)) - abs(start)
    case real_start_pos >= 0 do
      true -> do_slice(next_grapheme(string), real_start_pos, real_start_pos + len - 1, 0, "")
      false -> nil
    end
  end

  defp do_slice(_, start_pos, last_pos, _, _) when start_pos > last_pos do
    nil
  end

  defp do_slice({_, rest}, start_pos, last_pos, current_pos, acc) when current_pos < start_pos do
    do_slice(next_grapheme(rest), start_pos, last_pos, current_pos + 1, acc)
  end

  defp do_slice({char, rest}, start_pos, last_pos, current_pos, acc) when current_pos >= start_pos and current_pos < last_pos do
    do_slice(next_grapheme(rest), start_pos, last_pos, current_pos + 1, acc <> char)
  end

  defp do_slice({char, _}, start_pos, last_pos, current_pos, acc) when current_pos >= start_pos and current_pos == last_pos do
    acc <> char
  end

  defp do_slice(:no_grapheme, start_pos, _, current_pos, acc) when start_pos == current_pos do
    acc
  end

  defp do_slice(:no_grapheme, _, _, _, acc) do
    case acc do
      "" -> nil
      _ -> acc
    end
  end

  @doc """
  Converts a string to an integer. If successful, returns a
  tuple of form {integer, remainder of string}. If unsuccessful,
  returns :error.

  ## Examples

      iex> String.to_integer("34")
      {34,""}
      iex> String.to_integer("34.5")
      {34,".5"}
      iex> String.to_integer("three")
      :error

  """
  @spec to_integer(t) :: {integer, t} | :error

  def to_integer(string) do
    {result, remainder} = :string.to_integer(binary_to_list(string))
    case result do
      :error -> :error
      _ -> {result, list_to_binary(remainder)}
    end
  end

  @doc """
  Converts a string to a float. If successful, returns a
  tuple of form {float, remainder of string}. If unsuccessful,
  returns :error. If given an integer value, will return
  same as to_integer/1.

  ## Examples

      iex> String.to_float("34")
      {34.0,""}
      iex> String.to_float("34.25")
      {34.25,""}
	    iex> String.to_float("56.5xyz")
	    {56.5,"xyz"}
      iex> String.to_float("pi")
      :error

  """
  @spec to_float(t) :: {integer, t} | :error

  def to_float(string) do
    charlist = binary_to_list(string)
    {result, remainder} = :string.to_float(charlist)
    case result do
      :error ->
        {int_result, int_remainder} = :string.to_integer(charlist)
        case int_result do
          :error -> :error
          _ -> {float(int_result), list_to_binary(int_remainder)}
        end
      _ -> {result, list_to_binary(remainder)}
    end
  end

  @doc """
  Returns true if `string` starts with any of the prefixes given, otherwise
  false. `prefixes` can be either a single prefix or a list of prefixes.

  ## Examples

      iex> String.starts_with? "elixir", "eli"
      true
      iex> String.starts_with? "elixir", ["erlang", "elixir"]
      true
      iex> String.starts_with? "elixir", ["erlang", "ruby"]
      false

  """
  @spec starts_with?(t, t | [t]) :: boolean

  def starts_with?(string, prefixes) do
    case :binary.match(string, prefixes) do
      :nomatch -> false
      {0, _}   -> true
      _        -> false
    end
  end

  @doc """
  Returns true if `string` ends with any of the suffixes given, otherwise
  false. `suffixes` can be either a single suffix or a list of suffixes.

  ## Examples

      iex> String.ends_with? "language", "age"
      true
      iex> String.ends_with? "language", ["youth", "age"]
      true
      iex> String.ends_with? "language", ["youth", "elixir"]
      false

  """
  @spec ends_with?(t, t | [t]) :: boolean

  def ends_with?(string, suffixes) when is_list(suffixes) do
    string_size = size(string)
    Enum.any? suffixes, fn suffix ->
      suffix_size = size(suffix)
      (suffix_size <= string_size) and suffix == :binary.part(string, {string_size, -size(suffix)})
    end
  end

  def ends_with?(string, suffix), do: ends_with?(string, [ suffix ])

end


Add System.stop/1 over :init.stop/1 (#5578)

defmodule System do
  @moduledoc """
  The `System` module provides functions that interact directly
  with the VM or the host system.

  ## Time

  The `System` module also provides functions that work with time,
  returning different times kept by the system with support for
  different time units.

  One of the complexities in relying on system times is that they
  may be adjusted. For example, when you enter and leave daylight
  saving time, the system clock will be adjusted, often adding
  or removing one hour. We call such changes "time warps". In
  order to understand how such changes may be harmful, imagine
  the following code:

      ## DO NOT DO THIS
      prev = System.os_time()
      # ... execute some code ...
      next = System.os_time()
      diff = next - prev

  If, while the code is executing, the system clock changes,
  some code that executed in 1 second may be reported as taking
  over 1 hour! To address such concerns, the VM provides a
  monotonic time via `System.monotonic_time/0` which never
  decreases and does not leap:

      ## DO THIS
      prev = System.monotonic_time()
      # ... execute some code ...
      next = System.monotonic_time()
      diff = next - prev

  Generally speaking, the VM provides three time measurements:

    * `os_time/0` - the time reported by the OS. This time may be
      adjusted forwards or backwards in time with no limitation;

    * `system_time/0` - the VM view of the `os_time/0`. The system time and OS
      time may not match in case of time warps although the VM works towards
      aligning them. This time is not monotonic (i.e., it may decrease)
      as its behaviour is configured [by the VM time warp
      mode](http://www.erlang.org/doc/apps/erts/time_correction.html#Time_Warp_Modes);

    * `monotonic_time/0` - a monotonically increasing time provided
      by the Erlang VM.

  The time functions in this module work in the `:native` unit
  (unless specified otherwise), which is OS dependent. Most of
  the time, all calculations are done in the `:native` unit, to
  avoid loss of precision, with `convert_time_unit/3` being
  invoked at the end to convert to a specific time unit like
  `:millisecond` or `:microsecond`. See the `t:time_unit/0` type for
  more information.

  For a more complete rundown on the VM support for different
  times, see the [chapter on time and time
  correction](http://www.erlang.org/doc/apps/erts/time_correction.html)
  in the Erlang docs.
  """

  @typedoc """
  The time unit to be passed to functions like `monotonic_time/1` and others.

  The `:second`, `:millisecond`, `:microsecond` and `:nanosecond` time
  units controls the return value of the functions that accept a time unit.

  A time unit can also be a strictly positive integer. In this case, it
  represents the "parts per second": the time will be returned in `1 /
  parts_per_second` seconds. For example, using the `:millisecond` time unit
  is equivalent to using `1000` as the time unit (as the time will be returned
  in 1/1000 seconds - milliseconds).

  Keep in mind the Erlang API prior to version 19.1 will use `:milli_seconds`,
  `:micro_seconds` and `:nano_seconds` as time units although Elixir normalizes
  their spelling to match the SI convention.
  """
  @type time_unit ::
    :second
    | :millisecond
    | :microsecond
    | :nanosecond
    | pos_integer
    # TODO: Deprecate these in Elixir 2.0
    | :seconds
    | :milliseconds
    | :microseconds
    | :nanoseconds

  @base_dir     :filename.join(__DIR__, "../../..")
  @version_file :filename.join(@base_dir, "VERSION")

  defp strip(iodata) do
    :re.replace(iodata, "^[\s\r\n\t]+|[\s\r\n\t]+$", "", [:global, return: :binary])
  end

  defp read_stripped(path) do
    case :file.read_file(path) do
      {:ok, binary} ->
        strip(binary)
      _ ->
        ""
    end
  end

  # Read and strip the version from the VERSION file.
  defmacrop get_version do
    case read_stripped(@version_file) do
      ""   -> raise RuntimeError, message: "could not read the version number from VERSION"
      data -> data
    end
  end

  # Tries to run "git rev-parse --short HEAD". In the case of success returns
  # the short revision hash. If that fails, returns an empty string.
  defmacrop get_revision do
    null =
      case :os.type do
        {:win32, _} -> 'NUL'
        _ -> '/dev/null'
      end

    'git rev-parse --short HEAD 2> '
    |> Kernel.++(null)
    |> :os.cmd()
    |> strip
  end

  defp revision, do: get_revision()

  # Get the date at compilation time.
  defmacrop get_date do
    IO.iodata_to_binary :httpd_util.rfc1123_date
  end

  @doc """
  Returns the endianness.
  """
  def endianness do
    :erlang.system_info(:endian)
  end

  @doc """
  Returns the endianness the system was compiled with.
  """
  @endianness :erlang.system_info(:endian)
  def compiled_endianness do
    @endianness
  end

  @doc """
  Elixir version information.

  Returns Elixir's version as binary.
  """
  @spec version() :: String.t
  def version, do: get_version()

  @doc """
  Elixir build information.

  Returns a keyword list with Elixir version, Git short revision hash and compilation date.
  """
  @spec build_info() :: map
  def build_info do
    %{build:    build(),
      date:     get_date(),
      revision: revision(),
      version:  version()}
  end

  # Returns a string of the build info
  defp build do
    {:ok, v} = Version.parse(version())

    cond do
      ([] == v.pre) or ("" == revision()) ->
        version()
      true ->
        "#{version()} (#{revision()})"
    end
  end

  @doc """
  Lists command line arguments.

  Returns the list of command line arguments passed to the program.
  """
  @spec argv() :: [String.t]
  def argv do
    :elixir_config.get(:argv)
  end

  @doc """
  Modifies command line arguments.

  Changes the list of command line arguments. Use it with caution,
  as it destroys any previous argv information.
  """
  @spec argv([String.t]) :: :ok
  def argv(args) do
    :elixir_config.put(:argv, args)
  end

  @doc """
  Current working directory.

  Returns the current working directory or `nil` if one
  is not available.
  """
  def cwd do
    case :file.get_cwd do
      {:ok, base} -> IO.chardata_to_string(fix_drive_letter(base))
      _ -> nil
    end
  end

  defp fix_drive_letter([l, ?:, ?/ | rest] = original) when l in ?A..?Z do
    case :os.type() do
      {:win32, _} -> [l + ?a - ?A, ?:, ?/ | rest]
      _ -> original
    end
  end

  defp fix_drive_letter(original), do: original

  @doc """
  Current working directory, exception on error.

  Returns the current working directory or raises `RuntimeError`.
  """
  def cwd! do
    cwd() ||
      raise RuntimeError, message: "could not get a current working directory, the current location is not accessible"
  end

  @doc """
  User home directory.

  Returns the user home directory (platform independent).
  """
  def user_home do
    :elixir_config.get(:home)
  end

  @doc """
  User home directory, exception on error.

  Same as `user_home/0` but raises `RuntimeError`
  instead of returning `nil` if no user home is set.
  """
  def user_home! do
    user_home() ||
      raise RuntimeError, message: "could not find the user home, please set the HOME environment variable"
  end

  @doc ~S"""
  Writable temporary directory.

  Returns a writable temporary directory.
  Searches for directories in the following order:

    1. the directory named by the TMPDIR environment variable
    2. the directory named by the TEMP environment variable
    3. the directory named by the TMP environment variable
    4. `C:\TMP` on Windows or `/tmp` on Unix
    5. as a last resort, the current working directory

  Returns `nil` if none of the above are writable.
  """
  def tmp_dir do
    write_env_tmp_dir('TMPDIR') ||
      write_env_tmp_dir('TEMP') ||
      write_env_tmp_dir('TMP')  ||
      write_tmp_dir('/tmp')     ||
      ((cwd = cwd()) && write_tmp_dir(cwd))
  end

  @doc """
  Writable temporary directory, exception on error.

  Same as `tmp_dir/0` but raises `RuntimeError`
  instead of returning `nil` if no temp dir is set.
  """
  def tmp_dir! do
    tmp_dir() ||
      raise RuntimeError, message: "could not get a writable temporary directory, " <>
                                   "please set the TMPDIR environment variable"
  end

  defp write_env_tmp_dir(env) do
    case :os.getenv(env) do
      false -> nil
      tmp   -> write_tmp_dir(tmp)
    end
  end

  defp write_tmp_dir(dir) do
    case File.stat(dir) do
      {:ok, stat} ->
        case {stat.type, stat.access} do
          {:directory, access} when access in [:read_write, :write] ->
            IO.chardata_to_string(dir)
          _ ->
            nil
        end
      {:error, _} -> nil
    end
  end

  @doc """
  Registers a program exit handler function.

  Registers a function that will be invoked at the end of program execution.
  Useful for invoking a hook in "script" mode.

  The handler always executes in a different process from the one it was
  registered in. As a consequence, any resources managed by the calling process
  (ETS tables, open files, etc.) won't be available by the time the handler
  function is invoked.

  The function must receive the exit status code as an argument.
  """
  def at_exit(fun) when is_function(fun, 1) do
    :elixir_config.update :at_exit, &[fun | &1]
  end

  @doc """
  Locates an executable on the system.

  This function looks up an executable program given
  its name using the environment variable PATH on Unix
  and Windows. It also considers the proper executable
  extension for each OS, so for Windows it will try to
  lookup files with `.com`, `.cmd` or similar extensions.
  """
  @spec find_executable(binary) :: binary | nil
  def find_executable(program) when is_binary(program) do
    case :os.find_executable(String.to_charlist(program)) do
      false -> nil
      other -> List.to_string(other)
    end
  end

  @doc """
  System environment variables.

  Returns a list of all environment variables. Each variable is given as a
  `{name, value}` tuple where both `name` and `value` are strings.
  """
  @spec get_env() :: %{optional(String.t) => String.t}
  def get_env do
    Enum.into(:os.getenv, %{}, fn var ->
      var = IO.chardata_to_string var
      [k, v] = String.split var, "=", parts: 2
      {k, v}
    end)
  end

  @doc """
  Environment variable value.

  Returns the value of the environment variable
  `varname` as a binary, or `nil` if the environment
  variable is undefined.
  """
  @spec get_env(binary) :: binary | nil
  def get_env(varname) when is_binary(varname) do
    case :os.getenv(String.to_charlist(varname)) do
      false -> nil
      other -> List.to_string(other)
    end
  end

  @doc """
  Erlang VM process identifier.

  Returns the process identifier of the current Erlang emulator
  in the format most commonly used by the operating system environment.

  For more information, see [`:os.getpid/0`](http://www.erlang.org/doc/man/os.html#getpid-0).
  """
  @spec get_pid() :: binary
  def get_pid, do: IO.iodata_to_binary(:os.getpid)

  @doc """
  Sets an environment variable value.

  Sets a new `value` for the environment variable `varname`.
  """
  @spec put_env(binary, binary) :: :ok
  def put_env(varname, value) when is_binary(varname) and is_binary(value) do
   :os.putenv String.to_charlist(varname), String.to_charlist(value)
   :ok
  end

  @doc """
  Sets multiple environment variables.

  Sets a new value for each environment variable corresponding
  to each key in `dict`.
  """
  @spec put_env(Enumerable.t) :: :ok
  def put_env(enum) do
    Enum.each enum, fn {key, val} -> put_env key, val end
  end

  @doc """
  Deletes an environment variable.

  Removes the variable `varname` from the environment.
  """
  @spec delete_env(String.t) :: :ok
  def delete_env(varname) do
    :os.unsetenv(String.to_charlist(varname))
    :ok
  end

  @doc """
  Last exception stacktrace.

  Note that the Erlang VM (and therefore this function) does not
  return the current stacktrace but rather the stacktrace of the
  latest exception.

  Inlined by the compiler into `:erlang.get_stacktrace/0`.
  """
  def stacktrace do
    :erlang.get_stacktrace
  end

  @doc """
  Immediately halts the Erlang runtime system.

  Terminates the Erlang runtime system without properly shutting down
  applications and ports. Please see `stop/1` for a careful shutdown of the
  system.

  `status` must be a non-negative integer, the atom `:abort` or a binary.

    * If an integer, the runtime system exits with the integer value which
      is returned to the operating system.

    * If `:abort`, the runtime system aborts producing a core dump, if that is
      enabled in the operating system.

    * If a string, an Erlang crash dump is produced with status as slogan,
      and then the runtime system exits with status code 1.

  Note that on many platforms, only the status codes 0-255 are supported
  by the operating system.

  For more information, see [`:erlang.halt/1`](http://www.erlang.org/doc/man/erlang.html#halt-1).

  ## Examples

      System.halt(0)
      System.halt(1)
      System.halt(:abort)

  """
  @spec halt() :: no_return
  @spec halt(non_neg_integer | binary | :abort) :: no_return
  def halt(status \\ 0)

  def halt(status) when is_integer(status) or status == :abort do
    :erlang.halt(status)
  end

  def halt(status) when is_binary(status) do
    :erlang.halt(String.to_charlist(status))
  end

  @doc """
  Carefully stops the Erlang runtime system.

  All applications are taken down smoothly, all code is unloaded, and all ports
  are closed before the system terminates by calling `halt/1`.

  `status` must be a non-negative integer value which is returned by the
  runtime system to the operating system.

  Note that on many platforms, only the status codes 0-255 are supported
  by the operating system.

  For more information, see [`:init.stop/1`](http://erlang.org/doc/man/init.html#stop-1).

  ## Examples

      System.stop(0)
      System.stop(1)

  """
  @spec stop() :: no_return
  @spec stop(non_neg_integer | binary) :: no_return
  def stop(status \\ 0)

  def stop(status) when is_integer(status) do
    :init.stop(status)
  end

  def stop(status) when is_binary(status) do
    :init.stop(String.to_charlist(status))
  end

  @doc ~S"""
  Executes the given `command` with `args`.

  `command` is expected to be an executable available in PATH
  unless an absolute path is given.

  `args` must be a list of binaries which the executable will receive
  as its arguments as is. This means that:

    * environment variables will not be interpolated
    * wildcard expansion will not happen (unless `Path.wildcard/2` is used
      explicitly)
    * arguments do not need to be escaped or quoted for shell safety

  This function returns a tuple containing the collected result
  and the command exit status.

  Internally, this function uses a `Port` for interacting with the
  outside world. However, if you plan to run a long-running program,
  ports guarantee stdin/stdout devices will be closed but it does not
  automatically terminate the problem. The documentation for the
  `Port` module describes this problem and possible solutions under
  the "Zombie processes" section.

  ## Examples

      iex> System.cmd "echo", ["hello"]
      {"hello\n", 0}

      iex> System.cmd "echo", ["hello"], env: [{"MIX_ENV", "test"}]
      {"hello\n", 0}

      iex> System.cmd "echo", ["hello"], into: IO.stream(:stdio, :line)
      hello
      {%IO.Stream{}, 0}

  ## Options

    * `:into` - injects the result into the given collectable, defaults to `""`
    * `:cd` - the directory to run the command in
    * `:env` - an enumerable of tuples containing environment key-value as binary
    * `:arg0` - sets the command arg0
    * `:stderr_to_stdout` - redirects stderr to stdout when `true`
    * `:parallelism` - when `true`, the VM will schedule port tasks to improve
      parallelism in the system. If set to `false`, the VM will try to perform
      commands immediately, improving latency at the expense of parallelism.
      The default can be set on system startup by passing the "+spp" argument
      to `--erl`.

  ## Error reasons

  If invalid arguments are given, `ArgumentError` is raised by
  `System.cmd/3`. `System.cmd/3` also expects a strict set of
  options and will raise if unknown or invalid options are given.

  Furthermore, `System.cmd/3` may fail with one of the POSIX reasons
  detailed below:

    * `:system_limit` - all available ports in the Erlang emulator are in use

    * `:enomem` - there was not enough memory to create the port

    * `:eagain` - there are no more available operating system processes

    * `:enametoolong` - the external command given was too long

    * `:emfile` - there are no more available file descriptors
      (for the operating system process that the Erlang emulator runs in)

    * `:enfile` - the file table is full (for the entire operating system)

    * `:eacces` - the command does not point to an executable file

    * `:enoent` - the command does not point to an existing file

  ## Shell commands

  If you desire to execute a trusted command inside a shell, with pipes,
  redirecting and so on, please check
  [`:os.cmd/1`](http://www.erlang.org/doc/man/os.html#cmd-1).
  """
  @spec cmd(binary, [binary], Keyword.t) ::
        {Collectable.t, exit_status :: non_neg_integer}
  def cmd(command, args, opts \\ []) when is_binary(command) and is_list(args) do
    cmd = String.to_charlist(command)

    cmd =
      if Path.type(cmd) == :absolute do
        cmd
      else
        :os.find_executable(cmd) || :erlang.error(:enoent, [command, args, opts])
      end

    {into, opts} = cmd_opts(opts, [:use_stdio, :exit_status, :binary, :hide, args: args], "")
    {initial, fun} = Collectable.into(into)
    try do
      do_cmd Port.open({:spawn_executable, cmd}, opts), initial, fun
    catch
      kind, reason ->
        stacktrace = System.stacktrace
        fun.(initial, :halt)
        :erlang.raise(kind, reason, stacktrace)
    else
      {acc, status} -> {fun.(acc, :done), status}
    end
  end

  defp do_cmd(port, acc, fun) do
    receive do
      {^port, {:data, data}} ->
        do_cmd(port, fun.(acc, {:cont, data}), fun)
      {^port, {:exit_status, status}} ->
        {acc, status}
    end
  end

  defp cmd_opts([{:into, any} | t], opts, _into),
    do: cmd_opts(t, opts, any)

  defp cmd_opts([{:cd, bin} | t], opts, into) when is_binary(bin),
    do: cmd_opts(t, [{:cd, bin} | opts], into)

  defp cmd_opts([{:arg0, bin} | t], opts, into) when is_binary(bin),
    do: cmd_opts(t, [{:arg0, bin} | opts], into)

  defp cmd_opts([{:stderr_to_stdout, true} | t], opts, into),
    do: cmd_opts(t, [:stderr_to_stdout | opts], into)

  defp cmd_opts([{:stderr_to_stdout, false} | t], opts, into),
    do: cmd_opts(t, opts, into)

  defp cmd_opts([{:parallelism, bool} | t], opts, into) when is_boolean(bool),
    do: cmd_opts(t, [{:parallelism, bool} | opts], into)

  defp cmd_opts([{:env, enum} | t], opts, into),
    do: cmd_opts(t, [{:env, validate_env(enum)} | opts], into)

  defp cmd_opts([{key, val} | _], _opts, _into),
    do: raise(ArgumentError, "invalid option #{inspect key} with value #{inspect val}")

  defp cmd_opts([], opts, into),
    do: {into, opts}

  defp validate_env(enum) do
    Enum.map enum, fn
      {k, nil} ->
        {String.to_charlist(k), false}
      {k, v} ->
        {String.to_charlist(k), String.to_charlist(v)}
      other ->
        raise ArgumentError, "invalid environment key-value #{inspect other}"
    end
  end

  @doc """
  Returns the current monotonic time in the `:native` time unit.

  This time is monotonically increasing and starts in an unspecified
  point in time.

  Inlined by the compiler into `:erlang.monotonic_time/0`.
  """
  @spec monotonic_time() :: integer
  def monotonic_time do
    :erlang.monotonic_time()
  end

  @doc """
  Returns the current monotonic time in the given time unit.

  This time is monotonically increasing and starts in an unspecified
  point in time.
  """
  @spec monotonic_time(time_unit) :: integer
  def monotonic_time(unit) do
    :erlang.monotonic_time(normalize_time_unit(unit))
  end

  @doc """
  Returns the current system time in the `:native` time unit.

  It is the VM view of the `os_time/0`. They may not match in
  case of time warps although the VM works towards aligning
  them. This time is not monotonic.

  Inlined by the compiler into `:erlang.system_time/0`.
  """
  @spec system_time() :: integer
  def system_time do
    :erlang.system_time()
  end

  @doc """
  Returns the current system time in the given time unit.

  It is the VM view of the `os_time/0`. They may not match in
  case of time warps although the VM works towards aligning
  them. This time is not monotonic.
  """
  @spec system_time(time_unit) :: integer
  def system_time(unit) do
    :erlang.system_time(normalize_time_unit(unit))
  end

  @doc """
  Converts `time` from time unit `from_unit` to time unit `to_unit`.

  The result is rounded via the floor function.

  `convert_time_unit/3` accepts an additional time unit (other than the
  ones in the `t:time_unit/0` type) called `:native`. `:native` is the time
  unit used by the Erlang runtime system. It's determined when the runtime
  starts and stays the same until the runtime is stopped. To determine what
  the `:native` unit amounts to in a system, you can call this function to
  convert 1 second to the `:native` time unit (i.e.,
  `System.convert_time_unit(1, :second, :native)`).
  """
  @spec convert_time_unit(integer, time_unit | :native, time_unit | :native) :: integer
  def convert_time_unit(time, from_unit, to_unit) do
    :erlang.convert_time_unit(time, normalize_time_unit(from_unit), normalize_time_unit(to_unit))
  end

  @doc """
  Returns the current time offset between the Erlang VM monotonic
  time and the Erlang VM system time.

  The result is returned in the `:native` time unit.

  See `time_offset/1` for more information.

  Inlined by the compiler into `:erlang.time_offset/0`.
  """
  @spec time_offset() :: integer
  def time_offset do
    :erlang.time_offset()
  end

  @doc """
  Returns the current time offset between the Erlang VM monotonic
  time and the Erlang VM system time.

  The result is returned in the given time unit `unit`. The returned
  offset, added to an Erlang monotonic time (e.g., obtained with
  `monotonic_time/1`), gives the Erlang system time that corresponds
  to that monotonic time.
  """
  @spec time_offset(time_unit) :: integer
  def time_offset(unit) do
    :erlang.time_offset(normalize_time_unit(unit))
  end

  @doc """
  Returns the current OS time.

  The result is returned in the `:native` time unit.

  This time may be adjusted forwards or backwards in time
  with no limitation and is not monotonic.

  Inlined by the compiler into `:os.system_time/0`.
  """
  @spec os_time() :: integer
  def os_time do
    :os.system_time()
  end

  @doc """
  Returns the current OS time in the given time `unit`.

  This time may be adjusted forwards or backwards in time
  with no limitation and is not monotonic.
  """
  @spec os_time(time_unit) :: integer
  def os_time(unit) do
    :os.system_time(normalize_time_unit(unit))
  end

  @doc """
  Returns the OTP release number.
  """
  @spec otp_release :: String.t
  def otp_release do
    :erlang.list_to_binary :erlang.system_info(:otp_release)
  end

  @doc """
  Returns the number of schedulers in the VM.
  """
  @spec schedulers :: pos_integer
  def schedulers do
    :erlang.system_info(:schedulers)
  end

  @doc """
  Returns the number of schedulers online in the VM.
  """
  @spec schedulers_online :: pos_integer
  def schedulers_online do
    :erlang.system_info(:schedulers_online)
  end

  @doc """
  Generates and returns an integer that is unique in the current runtime
  instance.

  "Unique" means that this function, called with the same list of `modifiers`,
  will never return the same integer more than once on the current runtime
  instance.

  If `modifiers` is `[]`, then a unique integer (that can be positive or negative) is returned.
  Other modifiers can be passed to change the properties of the returned integer:

    * `:positive` - the returned integer is guaranteed to be positive.
    * `:monotonic` - the returned integer is monotonically increasing. This
      means that, on the same runtime instance (but even on different
      processes), integers returned using the `:monotonic` modifier will always
      be strictly less than integers returned by successive calls with the
      `:monotonic` modifier.

  All modifiers listed above can be combined; repeated modifiers in `modifiers`
  will be ignored.

  Inlined by the compiler into `:erlang.unique_integer/1`.
  """
  @spec unique_integer([:positive | :monotonic]) :: integer
  def unique_integer(modifiers \\ []) do
    :erlang.unique_integer(modifiers)
  end

  defp normalize_time_unit(:native),
    do: :native

  # TODO: Remove these mappings once Elixir requires Erlang/OTP 19.1
  defp normalize_time_unit(:second),
    do: :seconds
  defp normalize_time_unit(:millisecond),
    do: :milli_seconds
  defp normalize_time_unit(:microsecond),
    do: :micro_seconds
  defp normalize_time_unit(:nanosecond),
    do: :nano_seconds

  # TODO: Warn on Elixir 1.5
  defp normalize_time_unit(:seconds),
    do: :seconds
  defp normalize_time_unit(:milliseconds),
    do: :milli_seconds
  defp normalize_time_unit(:microseconds),
    do: :micro_seconds
  defp normalize_time_unit(:nanoseconds),
    do: :nano_seconds

  defp normalize_time_unit(unit) when is_integer(unit) and unit > 0,
    do: unit

  # TODO: Warn on Elixir 1.5
  defp normalize_time_unit(erlang_unit)
      when erlang_unit in [:milli_seconds, :micro_seconds, :nano_seconds] do
    erlang_unit
  end

  defp normalize_time_unit(other) do
    raise ArgumentError,
      "unsupported time unit. Expected :second, :millisecond, " <>
      ":microsecond, :nanosecond, or a positive integer, " <>
      "got #{inspect other}"
  end
end

defmodule System do
  @moduledoc """
  The `System` module provides functions that interact directly
  with the VM or the host system.

  ## Time

  The `System` module also provides functions that work with time,
  returning different times kept by the system with support for
  different time units.

  One of the complexities in relying on system times is that they
  may be adjusted. For example, when you enter and leave daylight
  saving time, the system clock will be adjusted, often adding
  or removing one hour. We call such changes "time warps". In
  order to understand how such changes may be harmful, imagine
  the following code:

      ## DO NOT DO THIS
      prev = System.os_time()
      # ... execute some code ...
      next = System.os_time()
      diff = next - prev

  If, while the code is executing, the system clock changes,
  some code that executed in 1 second may be reported as taking
  over 1 hour! To address such concerns, the VM provides a
  monotonic time via `System.monotonic_time/0` which never
  decreases and does not leap:

      ## DO THIS
      prev = System.monotonic_time()
      # ... execute some code ...
      next = System.monotonic_time()
      diff = next - prev

  Generally speaking, the VM provides three time measurements:

    * `os_time/0` - the time reported by the OS. This time may be
      adjusted forwards or backwards in time with no limitation;

    * `system_time/0` - the VM view of the `os_time/0`. The system time and OS
      time may not match in case of time warps although the VM works towards
      aligning them. This time is not monotonic (i.e., it may decrease)
      as its behaviour is configured [by the VM time warp
      mode](http://www.erlang.org/doc/apps/erts/time_correction.html#Time_Warp_Modes);

    * `monotonic_time/0` - a monotonically increasing time provided
      by the Erlang VM.

  The time functions in this module work in the `:native` unit
  (unless specified otherwise), which is OS dependent. Most of
  the time, all calculations are done in the `:native` unit, to
  avoid loss of precision, with `convert_time_unit/3` being
  invoked at the end to convert to a specific time unit like
  `:millisecond` or `:microsecond`. See the `t:time_unit/0` type for
  more information.

  For a more complete rundown on the VM support for different
  times, see the [chapter on time and time
  correction](http://www.erlang.org/doc/apps/erts/time_correction.html)
  in the Erlang docs.
  """

  @typedoc """
  The time unit to be passed to functions like `monotonic_time/1` and others.

  The `:second`, `:millisecond`, `:microsecond` and `:nanosecond` time
  units controls the return value of the functions that accept a time unit.

  A time unit can also be a strictly positive integer. In this case, it
  represents the "parts per second": the time will be returned in `1 /
  parts_per_second` seconds. For example, using the `:millisecond` time unit
  is equivalent to using `1000` as the time unit (as the time will be returned
  in 1/1000 seconds - milliseconds).

  Keep in mind the Erlang API prior to version 19.1 will use `:milli_seconds`,
  `:micro_seconds` and `:nano_seconds` as time units although Elixir normalizes
  their spelling to match the SI convention.
  """
  @type time_unit ::
    :second
    | :millisecond
    | :microsecond
    | :nanosecond
    | pos_integer
    # TODO: Deprecate these in Elixir 2.0
    | :seconds
    | :milliseconds
    | :microseconds
    | :nanoseconds

  @base_dir     :filename.join(__DIR__, "../../..")
  @version_file :filename.join(@base_dir, "VERSION")

  defp strip(iodata) do
    :re.replace(iodata, "^[\s\r\n\t]+|[\s\r\n\t]+$", "", [:global, return: :binary])
  end

  defp read_stripped(path) do
    case :file.read_file(path) do
      {:ok, binary} ->
        strip(binary)
      _ ->
        ""
    end
  end

  # Read and strip the version from the VERSION file.
  defmacrop get_version do
    case read_stripped(@version_file) do
      ""   -> raise RuntimeError, message: "could not read the version number from VERSION"
      data -> data
    end
  end

  # Tries to run "git rev-parse --short HEAD". In the case of success returns
  # the short revision hash. If that fails, returns an empty string.
  defmacrop get_revision do
    null =
      case :os.type do
        {:win32, _} -> 'NUL'
        _ -> '/dev/null'
      end

    'git rev-parse --short HEAD 2> '
    |> Kernel.++(null)
    |> :os.cmd()
    |> strip
  end

  defp revision, do: get_revision()

  # Get the date at compilation time.
  defmacrop get_date do
    IO.iodata_to_binary :httpd_util.rfc1123_date
  end

  @doc """
  Returns the endianness.
  """
  def endianness do
    :erlang.system_info(:endian)
  end

  @doc """
  Returns the endianness the system was compiled with.
  """
  @endianness :erlang.system_info(:endian)
  def compiled_endianness do
    @endianness
  end

  @doc """
  Elixir version information.

  Returns Elixir's version as binary.
  """
  @spec version() :: String.t
  def version, do: get_version()

  @doc """
  Elixir build information.

  Returns a keyword list with Elixir version, Git short revision hash and compilation date.
  """
  @spec build_info() :: map
  def build_info do
    %{build:    build(),
      date:     get_date(),
      revision: revision(),
      version:  version()}
  end

  # Returns a string of the build info
  defp build do
    {:ok, v} = Version.parse(version())

    cond do
      ([] == v.pre) or ("" == revision()) ->
        version()
      true ->
        "#{version()} (#{revision()})"
    end
  end

  @doc """
  Lists command line arguments.

  Returns the list of command line arguments passed to the program.
  """
  @spec argv() :: [String.t]
  def argv do
    :elixir_config.get(:argv)
  end

  @doc """
  Modifies command line arguments.

  Changes the list of command line arguments. Use it with caution,
  as it destroys any previous argv information.
  """
  @spec argv([String.t]) :: :ok
  def argv(args) do
    :elixir_config.put(:argv, args)
  end

  @doc """
  Current working directory.

  Returns the current working directory or `nil` if one
  is not available.
  """
  def cwd do
    case :file.get_cwd do
      {:ok, base} -> IO.chardata_to_string(fix_drive_letter(base))
      _ -> nil
    end
  end

  defp fix_drive_letter([l, ?:, ?/ | rest] = original) when l in ?A..?Z do
    case :os.type() do
      {:win32, _} -> [l + ?a - ?A, ?:, ?/ | rest]
      _ -> original
    end
  end

  defp fix_drive_letter(original), do: original

  @doc """
  Current working directory, exception on error.

  Returns the current working directory or raises `RuntimeError`.
  """
  def cwd! do
    cwd() ||
      raise RuntimeError, message: "could not get a current working directory, the current location is not accessible"
  end

  @doc """
  User home directory.

  Returns the user home directory (platform independent).
  """
  def user_home do
    :elixir_config.get(:home)
  end

  @doc """
  User home directory, exception on error.

  Same as `user_home/0` but raises `RuntimeError`
  instead of returning `nil` if no user home is set.
  """
  def user_home! do
    user_home() ||
      raise RuntimeError, message: "could not find the user home, please set the HOME environment variable"
  end

  @doc ~S"""
  Writable temporary directory.

  Returns a writable temporary directory.
  Searches for directories in the following order:

    1. the directory named by the TMPDIR environment variable
    2. the directory named by the TEMP environment variable
    3. the directory named by the TMP environment variable
    4. `C:\TMP` on Windows or `/tmp` on Unix
    5. as a last resort, the current working directory

  Returns `nil` if none of the above are writable.
  """
  def tmp_dir do
    write_env_tmp_dir('TMPDIR') ||
      write_env_tmp_dir('TEMP') ||
      write_env_tmp_dir('TMP')  ||
      write_tmp_dir('/tmp')     ||
      ((cwd = cwd()) && write_tmp_dir(cwd))
  end

  @doc """
  Writable temporary directory, exception on error.

  Same as `tmp_dir/0` but raises `RuntimeError`
  instead of returning `nil` if no temp dir is set.
  """
  def tmp_dir! do
    tmp_dir() ||
      raise RuntimeError, message: "could not get a writable temporary directory, " <>
                                   "please set the TMPDIR environment variable"
  end

  defp write_env_tmp_dir(env) do
    case :os.getenv(env) do
      false -> nil
      tmp   -> write_tmp_dir(tmp)
    end
  end

  defp write_tmp_dir(dir) do
    case File.stat(dir) do
      {:ok, stat} ->
        case {stat.type, stat.access} do
          {:directory, access} when access in [:read_write, :write] ->
            IO.chardata_to_string(dir)
          _ ->
            nil
        end
      {:error, _} -> nil
    end
  end

  @doc """
  Registers a program exit handler function.

  Registers a function that will be invoked at the end of program execution.
  Useful for invoking a hook in "script" mode.

  The handler always executes in a different process from the one it was
  registered in. As a consequence, any resources managed by the calling process
  (ETS tables, open files, etc.) won't be available by the time the handler
  function is invoked.

  The function must receive the exit status code as an argument.
  """
  def at_exit(fun) when is_function(fun, 1) do
    :elixir_config.update :at_exit, &[fun | &1]
  end

  @doc """
  Locates an executable on the system.

  This function looks up an executable program given
  its name using the environment variable PATH on Unix
  and Windows. It also considers the proper executable
  extension for each OS, so for Windows it will try to
  lookup files with `.com`, `.cmd` or similar extensions.
  """
  @spec find_executable(binary) :: binary | nil
  def find_executable(program) when is_binary(program) do
    case :os.find_executable(String.to_charlist(program)) do
      false -> nil
      other -> List.to_string(other)
    end
  end

  @doc """
  System environment variables.

  Returns a list of all environment variables. Each variable is given as a
  `{name, value}` tuple where both `name` and `value` are strings.
  """
  @spec get_env() :: %{optional(String.t) => String.t}
  def get_env do
    Enum.into(:os.getenv, %{}, fn var ->
      var = IO.chardata_to_string var
      [k, v] = String.split var, "=", parts: 2
      {k, v}
    end)
  end

  @doc """
  Environment variable value.

  Returns the value of the environment variable
  `varname` as a binary, or `nil` if the environment
  variable is undefined.
  """
  @spec get_env(binary) :: binary | nil
  def get_env(varname) when is_binary(varname) do
    case :os.getenv(String.to_charlist(varname)) do
      false -> nil
      other -> List.to_string(other)
    end
  end

  @doc """
  Erlang VM process identifier.

  Returns the process identifier of the current Erlang emulator
  in the format most commonly used by the operating system environment.

  For more information, see [`:os.getpid/0`](http://www.erlang.org/doc/man/os.html#getpid-0).
  """
  @spec get_pid() :: binary
  def get_pid, do: IO.iodata_to_binary(:os.getpid)

  @doc """
  Sets an environment variable value.

  Sets a new `value` for the environment variable `varname`.
  """
  @spec put_env(binary, binary) :: :ok
  def put_env(varname, value) when is_binary(varname) and is_binary(value) do
   :os.putenv String.to_charlist(varname), String.to_charlist(value)
   :ok
  end

  @doc """
  Sets multiple environment variables.

  Sets a new value for each environment variable corresponding
  to each key in `dict`.
  """
  @spec put_env(Enumerable.t) :: :ok
  def put_env(enum) do
    Enum.each enum, fn {key, val} -> put_env key, val end
  end

  @doc """
  Deletes an environment variable.

  Removes the variable `varname` from the environment.
  """
  @spec delete_env(String.t) :: :ok
  def delete_env(varname) do
    :os.unsetenv(String.to_charlist(varname))
    :ok
  end

  @doc """
  Last exception stacktrace.

  Note that the Erlang VM (and therefore this function) does not
  return the current stacktrace but rather the stacktrace of the
  latest exception.

  Inlined by the compiler into `:erlang.get_stacktrace/0`.
  """
  def stacktrace do
    :erlang.get_stacktrace
  end

  @doc """
  Halts the Erlang runtime system.

  Halts the Erlang runtime system where the argument `status` must be a
  non-negative integer, the atom `:abort` or a binary.

    * If an integer, the runtime system exits with the integer value which
      is returned to the operating system.

    * If `:abort`, the runtime system aborts producing a core dump, if that is
      enabled in the operating system.

    * If a string, an Erlang crash dump is produced with status as slogan,
      and then the runtime system exits with status code 1.

  Note that on many platforms, only the status codes 0-255 are supported
  by the operating system.

  For more information, see [`:erlang.halt/1`](http://www.erlang.org/doc/man/erlang.html#halt-1).

  ## Examples

      System.halt(0)
      System.halt(1)
      System.halt(:abort)

  """
  @spec halt() :: no_return
  @spec halt(non_neg_integer | binary | :abort) :: no_return
  def halt(status \\ 0)

  def halt(status) when is_integer(status) or status == :abort do
    :erlang.halt(status)
  end

  def halt(status) when is_binary(status) do
    :erlang.halt(String.to_charlist(status))
  end

  @doc ~S"""
  Executes the given `command` with `args`.

  `command` is expected to be an executable available in PATH
  unless an absolute path is given.

  `args` must be a list of binaries which the executable will receive
  as its arguments as is. This means that:

    * environment variables will not be interpolated
    * wildcard expansion will not happen (unless `Path.wildcard/2` is used
      explicitly)
    * arguments do not need to be escaped or quoted for shell safety

  This function returns a tuple containing the collected result
  and the command exit status.

  Internally, this function uses a `Port` for interacting with the
  outside world. However, if you plan to run a long-running program,
  ports guarantee stdin/stdout devices will be closed but it does not
  automatically terminate the problem. The documentation for the
  `Port` module describes this problem and possible solutions under
  the "Zombie processes" section.

  ## Examples

      iex> System.cmd "echo", ["hello"]
      {"hello\n", 0}

      iex> System.cmd "echo", ["hello"], env: [{"MIX_ENV", "test"}]
      {"hello\n", 0}

      iex> System.cmd "echo", ["hello"], into: IO.stream(:stdio, :line)
      hello
      {%IO.Stream{}, 0}

  ## Options

    * `:into` - injects the result into the given collectable, defaults to `""`
    * `:cd` - the directory to run the command in
    * `:env` - an enumerable of tuples containing environment key-value as binary
    * `:arg0` - sets the command arg0
    * `:stderr_to_stdout` - redirects stderr to stdout when `true`
    * `:parallelism` - when `true`, the VM will schedule port tasks to improve
      parallelism in the system. If set to `false`, the VM will try to perform
      commands immediately, improving latency at the expense of parallelism.
      The default can be set on system startup by passing the "+spp" argument
      to `--erl`.

  ## Error reasons

  If invalid arguments are given, `ArgumentError` is raised by
  `System.cmd/3`. `System.cmd/3` also expects a strict set of
  options and will raise if unknown or invalid options are given.

  Furthermore, `System.cmd/3` may fail with one of the POSIX reasons
  detailed below:

    * `:system_limit` - all available ports in the Erlang emulator are in use

    * `:enomem` - there was not enough memory to create the port

    * `:eagain` - there are no more available operating system processes

    * `:enametoolong` - the external command given was too long

    * `:emfile` - there are no more available file descriptors
      (for the operating system process that the Erlang emulator runs in)

    * `:enfile` - the file table is full (for the entire operating system)

    * `:eacces` - the command does not point to an executable file

    * `:enoent` - the command does not point to an existing file

  ## Shell commands

  If you desire to execute a trusted command inside a shell, with pipes,
  redirecting and so on, please check
  [`:os.cmd/1`](http://www.erlang.org/doc/man/os.html#cmd-1).
  """
  @spec cmd(binary, [binary], Keyword.t) ::
        {Collectable.t, exit_status :: non_neg_integer}
  def cmd(command, args, opts \\ []) when is_binary(command) and is_list(args) do
    cmd = String.to_charlist(command)

    cmd =
      if Path.type(cmd) == :absolute do
        cmd
      else
        :os.find_executable(cmd) || :erlang.error(:enoent, [command, args, opts])
      end

    {into, opts} = cmd_opts(opts, [:use_stdio, :exit_status, :binary, :hide, args: args], "")
    {initial, fun} = Collectable.into(into)
    try do
      do_cmd Port.open({:spawn_executable, cmd}, opts), initial, fun
    catch
      kind, reason ->
        stacktrace = System.stacktrace
        fun.(initial, :halt)
        :erlang.raise(kind, reason, stacktrace)
    else
      {acc, status} -> {fun.(acc, :done), status}
    end
  end

  defp do_cmd(port, acc, fun) do
    receive do
      {^port, {:data, data}} ->
        do_cmd(port, fun.(acc, {:cont, data}), fun)
      {^port, {:exit_status, status}} ->
        {acc, status}
    end
  end

  defp cmd_opts([{:into, any} | t], opts, _into),
    do: cmd_opts(t, opts, any)

  defp cmd_opts([{:cd, bin} | t], opts, into) when is_binary(bin),
    do: cmd_opts(t, [{:cd, bin} | opts], into)

  defp cmd_opts([{:arg0, bin} | t], opts, into) when is_binary(bin),
    do: cmd_opts(t, [{:arg0, bin} | opts], into)

  defp cmd_opts([{:stderr_to_stdout, true} | t], opts, into),
    do: cmd_opts(t, [:stderr_to_stdout | opts], into)

  defp cmd_opts([{:stderr_to_stdout, false} | t], opts, into),
    do: cmd_opts(t, opts, into)

  defp cmd_opts([{:parallelism, bool} | t], opts, into) when is_boolean(bool),
    do: cmd_opts(t, [{:parallelism, bool} | opts], into)

  defp cmd_opts([{:env, enum} | t], opts, into),
    do: cmd_opts(t, [{:env, validate_env(enum)} | opts], into)

  defp cmd_opts([{key, val} | _], _opts, _into),
    do: raise(ArgumentError, "invalid option #{inspect key} with value #{inspect val}")

  defp cmd_opts([], opts, into),
    do: {into, opts}

  defp validate_env(enum) do
    Enum.map enum, fn
      {k, nil} ->
        {String.to_charlist(k), false}
      {k, v} ->
        {String.to_charlist(k), String.to_charlist(v)}
      other ->
        raise ArgumentError, "invalid environment key-value #{inspect other}"
    end
  end

  @doc """
  Returns the current monotonic time in the `:native` time unit.

  This time is monotonically increasing and starts in an unspecified
  point in time.

  Inlined by the compiler into `:erlang.monotonic_time/0`.
  """
  @spec monotonic_time() :: integer
  def monotonic_time do
    :erlang.monotonic_time()
  end

  @doc """
  Returns the current monotonic time in the given time unit.

  This time is monotonically increasing and starts in an unspecified
  point in time.
  """
  @spec monotonic_time(time_unit) :: integer
  def monotonic_time(unit) do
    :erlang.monotonic_time(normalize_time_unit(unit))
  end

  @doc """
  Returns the current system time in the `:native` time unit.

  It is the VM view of the `os_time/0`. They may not match in
  case of time warps although the VM works towards aligning
  them. This time is not monotonic.

  Inlined by the compiler into `:erlang.system_time/0`.
  """
  @spec system_time() :: integer
  def system_time do
    :erlang.system_time()
  end

  @doc """
  Returns the current system time in the given time unit.

  It is the VM view of the `os_time/0`. They may not match in
  case of time warps although the VM works towards aligning
  them. This time is not monotonic.
  """
  @spec system_time(time_unit) :: integer
  def system_time(unit) do
    :erlang.system_time(normalize_time_unit(unit))
  end

  @doc """
  Converts `time` from time unit `from_unit` to time unit `to_unit`.

  The result is rounded via the floor function.

  `convert_time_unit/3` accepts an additional time unit (other than the
  ones in the `t:time_unit/0` type) called `:native`. `:native` is the time
  unit used by the Erlang runtime system. It's determined when the runtime
  starts and stays the same until the runtime is stopped. To determine what
  the `:native` unit amounts to in a system, you can call this function to
  convert 1 second to the `:native` time unit (i.e.,
  `System.convert_time_unit(1, :second, :native)`).
  """
  @spec convert_time_unit(integer, time_unit | :native, time_unit | :native) :: integer
  def convert_time_unit(time, from_unit, to_unit) do
    :erlang.convert_time_unit(time, normalize_time_unit(from_unit), normalize_time_unit(to_unit))
  end

  @doc """
  Returns the current time offset between the Erlang VM monotonic
  time and the Erlang VM system time.

  The result is returned in the `:native` time unit.

  See `time_offset/1` for more information.

  Inlined by the compiler into `:erlang.time_offset/0`.
  """
  @spec time_offset() :: integer
  def time_offset do
    :erlang.time_offset()
  end

  @doc """
  Returns the current time offset between the Erlang VM monotonic
  time and the Erlang VM system time.

  The result is returned in the given time unit `unit`. The returned
  offset, added to an Erlang monotonic time (e.g., obtained with
  `monotonic_time/1`), gives the Erlang system time that corresponds
  to that monotonic time.
  """
  @spec time_offset(time_unit) :: integer
  def time_offset(unit) do
    :erlang.time_offset(normalize_time_unit(unit))
  end

  @doc """
  Returns the current OS time.

  The result is returned in the `:native` time unit.

  This time may be adjusted forwards or backwards in time
  with no limitation and is not monotonic.

  Inlined by the compiler into `:os.system_time/0`.
  """
  @spec os_time() :: integer
  def os_time do
    :os.system_time()
  end

  @doc """
  Returns the current OS time in the given time `unit`.

  This time may be adjusted forwards or backwards in time
  with no limitation and is not monotonic.
  """
  @spec os_time(time_unit) :: integer
  def os_time(unit) do
    :os.system_time(normalize_time_unit(unit))
  end

  @doc """
  Returns the OTP release number.
  """
  @spec otp_release :: String.t
  def otp_release do
    :erlang.list_to_binary :erlang.system_info(:otp_release)
  end

  @doc """
  Returns the number of schedulers in the VM.
  """
  @spec schedulers :: pos_integer
  def schedulers do
    :erlang.system_info(:schedulers)
  end

  @doc """
  Returns the number of schedulers online in the VM.
  """
  @spec schedulers_online :: pos_integer
  def schedulers_online do
    :erlang.system_info(:schedulers_online)
  end

  @doc """
  Generates and returns an integer that is unique in the current runtime
  instance.

  "Unique" means that this function, called with the same list of `modifiers`,
  will never return the same integer more than once on the current runtime
  instance.

  If `modifiers` is `[]`, then a unique integer (that can be positive or negative) is returned.
  Other modifiers can be passed to change the properties of the returned integer:

    * `:positive` - the returned integer is guaranteed to be positive.
    * `:monotonic` - the returned integer is monotonically increasing. This
      means that, on the same runtime instance (but even on different
      processes), integers returned using the `:monotonic` modifier will always
      be strictly less than integers returned by successive calls with the
      `:monotonic` modifier.

  All modifiers listed above can be combined; repeated modifiers in `modifiers`
  will be ignored.

  Inlined by the compiler into `:erlang.unique_integer/1`.
  """
  @spec unique_integer([:positive | :monotonic]) :: integer
  def unique_integer(modifiers \\ []) do
    :erlang.unique_integer(modifiers)
  end

  defp normalize_time_unit(:native),
    do: :native

  # TODO: Remove these mappings once Elixir requires Erlang/OTP 19.1
  defp normalize_time_unit(:second),
    do: :seconds
  defp normalize_time_unit(:millisecond),
    do: :milli_seconds
  defp normalize_time_unit(:microsecond),
    do: :micro_seconds
  defp normalize_time_unit(:nanosecond),
    do: :nano_seconds

  # TODO: Warn on Elixir 1.5
  defp normalize_time_unit(:seconds),
    do: :seconds
  defp normalize_time_unit(:milliseconds),
    do: :milli_seconds
  defp normalize_time_unit(:microseconds),
    do: :micro_seconds
  defp normalize_time_unit(:nanoseconds),
    do: :nano_seconds

  defp normalize_time_unit(unit) when is_integer(unit) and unit > 0,
    do: unit

  # TODO: Warn on Elixir 1.5
  defp normalize_time_unit(erlang_unit)
      when erlang_unit in [:milli_seconds, :micro_seconds, :nano_seconds] do
    erlang_unit
  end

  defp normalize_time_unit(other) do
    raise ArgumentError,
      "unsupported time unit. Expected :second, :millisecond, " <>
      ":microsecond, :nanosecond, or a positive integer, " <>
      "got #{inspect other}"
  end
end