aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorRichard Viney <richard.viney@gmail.com>2024-11-11 23:00:37 +1300
committerLouis Pilfold <louis@lpil.uk>2024-11-11 10:56:27 +0000
commitc982361167325650ff4546d62c52f6b3feed24ab (patch)
treebea400e693e3449cf5e654a5d73fab23f7458812 /src
parent978afd77909904c87dd0306f9905586bfd5c1cc2 (diff)
downloadgleam_stdlib-c982361167325650ff4546d62c52f6b3feed24ab.tar.gz
gleam_stdlib-c982361167325650ff4546d62c52f6b3feed24ab.zip
Add `bit_size()` and `starts_with()` to `gleam/bit_array`
Diffstat (limited to 'src')
-rw-r--r--src/gleam/bit_array.gleam28
-rw-r--r--src/gleam_stdlib.mjs14
2 files changed, 40 insertions, 2 deletions
diff --git a/src/gleam/bit_array.gleam b/src/gleam/bit_array.gleam
index 2c70d14..e31709c 100644
--- a/src/gleam/bit_array.gleam
+++ b/src/gleam/bit_array.gleam
@@ -10,6 +10,13 @@ import gleam/string
@external(javascript, "../gleam_stdlib.mjs", "bit_array_from_string")
pub fn from_string(x: String) -> BitArray
+/// Returns an integer which is the number of bits in the bit array.
+///
+@external(erlang, "erlang", "bit_size")
+pub fn bit_size(x: BitArray) -> Int {
+ byte_size(x) * 8
+}
+
/// Returns an integer which is the number of bytes in the bit array.
///
@external(erlang, "erlang", "byte_size")
@@ -203,8 +210,6 @@ fn inspect_loop(input: BitArray, accumulator: String) -> String {
/// // -> Eq
/// ```
///
-/// Only supported on Erlang target for now.
-///
@external(javascript, "../gleam_stdlib.mjs", "bit_array_compare")
pub fn compare(a: BitArray, with b: BitArray) -> order.Order {
case a, b {
@@ -235,3 +240,22 @@ pub fn compare(a: BitArray, with b: BitArray) -> order.Order {
@external(erlang, "gleam_stdlib", "bit_array_to_int_and_size")
fn bit_array_to_int_and_size(a: BitArray) -> #(Int, Int)
+
+/// Checks whether the first `BitArray` starts with the second one.
+///
+/// ## Examples
+///
+/// ```gleam
+/// starts_with(<<1, 2, 3, 4>>, <<1, 2>>)
+/// // -> True
+/// ```
+///
+@external(javascript, "../gleam_stdlib.mjs", "bit_array_starts_with")
+pub fn starts_with(bits: BitArray, prefix: BitArray) -> Bool {
+ let prefix_size = bit_size(prefix)
+
+ case bits {
+ <<pref:bits-size(prefix_size), _:bits>> if pref == prefix -> True
+ _ -> False
+ }
+}
diff --git a/src/gleam_stdlib.mjs b/src/gleam_stdlib.mjs
index 74df3d0..4d198cb 100644
--- a/src/gleam_stdlib.mjs
+++ b/src/gleam_stdlib.mjs
@@ -990,3 +990,17 @@ export function bit_array_compare(first, second) {
}
return new Lt(); // second has more items
}
+
+export function bit_array_starts_with(bits, prefix) {
+ if (prefix.length > bits.length) {
+ return false;
+ }
+
+ for (let i = 0; i < prefix.length; i++) {
+ if (bits.buffer[i] !== prefix.buffer[i]) {
+ return false;
+ }
+ }
+
+ return true;
+}