Skip to content

Implement access protocol for BitString #708

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions lib/elixir/lib/access.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
10 changes: 10 additions & 0 deletions lib/elixir/test/elixir/access_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down