aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--CHANGELOG.md1
-rw-r--r--src/gleam/bit_array.gleam52
-rw-r--r--test/gleam/bit_array_test.gleam22
3 files changed, 75 insertions, 0 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 94ba0d5..173b83d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,7 @@
## Unreleased
+- The `bit_array` module gains the `inspect` and `inspect_base16` functions.
- The `set` module gains the `difference` function.
- The deprecated `bit_string`, `bit_builder`, `base`, and `map` modules have
been removed.
diff --git a/src/gleam/bit_array.gleam b/src/gleam/bit_array.gleam
index 1a94679..2f8a07e 100644
--- a/src/gleam/bit_array.gleam
+++ b/src/gleam/bit_array.gleam
@@ -1,5 +1,6 @@
//// BitArrays are a sequence of binary data of any length.
+import gleam/int
import gleam/string
/// Converts a UTF-8 `String` type into a `BitArray`.
@@ -155,3 +156,54 @@ pub fn base16_encode(input: BitArray) -> String
@external(erlang, "gleam_stdlib", "base16_decode")
@external(javascript, "../gleam_stdlib.mjs", "base16_decode")
pub fn base16_decode(input: String) -> Result(BitArray, Nil)
+
+/// Converts a bit array to a string containing the decimal value of each byte.
+///
+/// ## Examples
+///
+/// ```gleam
+/// inspect(<<0, 20, 0x20, 255>>)
+/// // -> "<<0, 20, 32, 255>>"
+/// ```
+///
+pub fn inspect(input: BitArray) -> String {
+ "<<"
+ <> input
+ |> do_inspect(int.to_string)
+ |> string.join(", ")
+ <> ">>"
+}
+
+/// Converts a bit array to a string containing the hexadecimal value of each
+/// byte.
+///
+/// ## Examples
+///
+/// ```gleam
+/// inspect(<<0, 20, 0x20, 255>>)
+/// // -> "<<00 14 20 FF>>"
+/// ```
+///
+pub fn inspect_base16(input: BitArray) -> String {
+ let byte_to_hex_string = fn(b) {
+ b
+ |> int.to_base16
+ |> string.pad_left(2, "0")
+ }
+
+ "<<"
+ <> input
+ |> do_inspect(byte_to_hex_string)
+ |> string.join(" ")
+ <> ">>"
+}
+
+fn do_inspect(
+ input: BitArray,
+ byte_to_string: fn(Int) -> String,
+) -> List(String) {
+ case input {
+ <<b, rest:bytes>> -> [byte_to_string(b), ..do_inspect(rest, byte_to_string)]
+ _ -> []
+ }
+}
diff --git a/test/gleam/bit_array_test.gleam b/test/gleam/bit_array_test.gleam
index 903b0c8..ca94f1a 100644
--- a/test/gleam/bit_array_test.gleam
+++ b/test/gleam/bit_array_test.gleam
@@ -279,3 +279,25 @@ pub fn base16_decode_test() {
bit_array.base16_decode("a1b2c3d4e5f67891")
|> should.equal(Ok(<<161, 178, 195, 212, 229, 246, 120, 145>>))
}
+
+pub fn inspect_test() {
+ bit_array.inspect(<<>>)
+ |> should.equal("<<>>")
+
+ bit_array.inspect(<<80>>)
+ |> should.equal("<<80>>")
+
+ bit_array.inspect(<<0, 20, 0x20, 255>>)
+ |> should.equal("<<0, 20, 32, 255>>")
+}
+
+pub fn inspect_base16_test() {
+ bit_array.inspect_base16(<<>>)
+ |> should.equal("<<>>")
+
+ bit_array.inspect_base16(<<0x80>>)
+ |> should.equal("<<80>>")
+
+ bit_array.inspect_base16(<<0, 20, 0x20, 255>>)
+ |> should.equal("<<00 14 20 FF>>")
+}