/
chars.ex
62 lines (51 loc) · 1.33 KB
/
chars.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import Kernel, except: [to_string: 1]
defprotocol String.Chars do
@moduledoc ~S"""
The `String.Chars` protocol is responsible for
converting a structure to a binary (only if applicable).
The only function required to be implemented is
`to_string/1`, which does the conversion.
The `to_string/1` function automatically imported
by `Kernel` invokes this protocol. String
interpolation also invokes `to_string/1` in its
arguments. For example, `"foo#{bar}"` is the same
as `"foo" <> to_string(bar)`.
"""
@doc """
Converts `term` to a string.
"""
@spec to_string(t) :: String.t()
def to_string(term)
end
defimpl String.Chars, for: Atom do
def to_string(nil) do
""
end
def to_string(atom) do
Atom.to_string(atom)
end
end
defimpl String.Chars, for: BitString do
def to_string(term) when is_binary(term) do
term
end
def to_string(term) do
raise Protocol.UndefinedError,
protocol: @protocol,
value: term,
description: "cannot convert a bitstring to a string"
end
end
defimpl String.Chars, for: List do
def to_string(charlist), do: List.to_string(charlist)
end
defimpl String.Chars, for: Integer do
def to_string(term) do
Integer.to_string(term)
end
end
defimpl String.Chars, for: Float do
def to_string(term) do
:erlang.float_to_binary(term, [:short])
end
end