Skip to content

Commit

Permalink
Merge pull request #1058 from meh/string-valid
Browse files Browse the repository at this point in the history
Add String.valid?
  • Loading branch information
José Valim committed May 14, 2013
2 parents baf5fcf + 1d6fd3c commit 26aee95
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
30 changes: 29 additions & 1 deletion lib/elixir/lib/string.ex
Original file line number Diff line number Diff line change
Expand Up @@ -458,6 +458,34 @@ defmodule String do
@spec next_codepoint(t) :: {codepoint, t} | :no_codepoint
defdelegate next_codepoint(string), to: String.Unicode

@doc %B"""
Checks whether `str` is a valid UTF-8 string.
## 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
def valid?(<<_ :: utf8, t :: binary>>) do
valid?(t)
end

def valid?(<<>>) do
true
end

def valid?(_) do
false
end

@doc %B"""
Checks whether `str` is a valid codepoint.
Expand All @@ -470,7 +498,7 @@ defmodule String do
true
iex> String.valid_codepoint?("ø")
true
iex> String.valid_codepoint?("\xffff")
iex> String.valid_codepoint?(<<0xffff :: 16>>)
false
iex> String.valid_codepoint?("asdf")
false
Expand Down
11 changes: 10 additions & 1 deletion lib/elixir/test/elixir/string_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -228,12 +228,21 @@ defmodule StringTest do
assert String.slice("", 0, 1) == nil
end

test :valid? do
assert String.valid?("afds")
assert String.valid?("øsdfh")
assert String.valid?("dskfjあska")

refute String.valid?(<<0xffff :: 16>>)
refute String.valid?("asd" <> <<0xffff :: 16>>)
end

test :valid_codepoint? do
assert String.valid_codepoint?("a")
assert String.valid_codepoint?("ø")
assert String.valid_codepoint?("あ")

refute String.valid_codepoint?("\xffff")
refute String.valid_codepoint?(<<0xffff :: 16>>)
refute String.valid_codepoint?("ab")
end

Expand Down

0 comments on commit 26aee95

Please sign in to comment.