diff --git a/lib/elixir/lib/access.ex b/lib/elixir/lib/access.ex index bba463b85d8..ff5f20a80f5 100644 --- a/lib/elixir/lib/access.ex +++ b/lib/elixir/lib/access.ex @@ -8,10 +8,10 @@ defprotocol Access do invokes the `Access.access` protocol. This protocol is limited and is implemented only for the - following built-in types: keywords, records and functions. + following built-in types: keywords, records, functions and bitstrings. """ - @only [List, Function, Record, Atom] + @only [List, Function, Record, Atom, BitString] @doc """ Receives the element being accessed and the access item. @@ -62,3 +62,13 @@ defimpl Access, for: Function do function.(item) end end + +defimpl Access, for: BitString do + @doc """ + The access protocol for bitstrings invokes + String.at/2. + """ + def access(string, position) when is_integer(position) do + String.at(string, position) + end +end diff --git a/lib/elixir/test/elixir/access_test.exs b/lib/elixir/test/elixir/access_test.exs index fdc0854fc50..7d56b05344d 100644 --- a/lib/elixir/test/elixir/access_test.exs +++ b/lib/elixir/test/elixir/access_test.exs @@ -19,6 +19,16 @@ defmodule AccessTest do assert function[:bar] == false end + test :bitstring do + assert "abc"[1] == "b" + assert "がガちゃ"[2] == "ち" + assert <<1, 2>>[1] == <<2>> + assert "abc"[3] == nil + assert "がガちゃ"[4] == nil + assert <<1, 2>>[2] == nil + assert <<1, 2, 3>>[-1] == <<3>> + end + # Test nil at compilation time does not fail # and that @config[:foo] has proper precedence. nil = @config[:foo]