Created
July 9, 2015 21:34
-
-
Save aerosol/e390233b7a207cc7ee62 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Xbp do | |
@moduledoc ~S""" | |
Dumps binaries in a similar way to xxd | |
""" | |
import Enum, only: [chunk: 4, join: 2, map: 2, with_index: 1, zip: 2] | |
@chunk_len 16 | |
@offset_len 8 | |
def dump(bx) when is_binary bx do | |
map(fragments(bx), | |
fn {{l,idx},{r,idx}} -> | |
(String.ljust Integer.to_string(idx), @offset_len) | |
<> (String.ljust join(l, " "), 2+@chunk_len*3) | |
<> r | |
end) | |
:ok | |
end | |
def chunk(l, n \\ @chunk_len), do: with_index chunk(l, n, n, []) | |
def fragments(bx) when is_binary bx do | |
zip chunk(bin_to_hexstr bx), chunk(bin_to_printable bx) | |
end | |
defp byte_to_hex(b) when b in 0..255, do: Integer.to_string(b, 16) | |
defp byte_to_printable(b) when b in 32..?~, do: b | |
defp byte_to_printable(_), do: "." | |
defp bin_to_printable(bx) when is_binary bx do | |
for <<b <- bx>>, do: byte_to_printable b | |
end | |
defp bin_to_hexstr(bx) when is_binary bx do | |
for <<b <- bx>>, do: maybe_add_leading_0 (byte_to_hex b) | |
end | |
defp maybe_add_leading_0(<<_::size(8)>>=b), do: "0" <> b | |
defp maybe_add_leading_0(<<_::size(16)>>=b), do: b | |
defimpl Inspect, for: BitString do | |
def inspect(bs, _) do | |
Xbp.dump(bs) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment