diff options
author | sobolevn <mail@sobolevn.me> | 2024-08-17 22:36:32 +0300 |
---|---|---|
committer | Louis Pilfold <louis@lpil.uk> | 2024-08-24 13:07:53 +0100 |
commit | 905e8d6e6db8ad0dfc061861cef5ccb96f84012b (patch) | |
tree | 6dce1ee2917442010323455ab8b5bde5cd9fa38a /src | |
parent | 2cd7f6e8d4ae7c1e2763d466e5adde562652fdae (diff) | |
download | gleam_stdlib-905e8d6e6db8ad0dfc061861cef5ccb96f84012b.tar.gz gleam_stdlib-905e8d6e6db8ad0dfc061861cef5ccb96f84012b.zip |
Add `bit_array.compare`
Diffstat (limited to 'src')
-rw-r--r-- | src/gleam/bit_array.gleam | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/src/gleam/bit_array.gleam b/src/gleam/bit_array.gleam index 23b243a..e0cf4f2 100644 --- a/src/gleam/bit_array.gleam +++ b/src/gleam/bit_array.gleam @@ -1,6 +1,7 @@ //// BitArrays are a sequence of binary data of any length. import gleam/int +import gleam/order import gleam/string /// Converts a UTF-8 `String` type into a `BitArray`. @@ -187,3 +188,39 @@ fn do_inspect(input: BitArray, accumulator: String) -> String { _ -> accumulator } } + +/// Compare two bit arrays as sequences of bytes. +/// +/// ## Examples +/// +/// ```gleam +/// compare(<<1>>, <<2>>) +/// // -> Lt +/// +/// compare(<<"AB":utf8>>, <<"AA":utf8>>) +/// // -> Gt +/// +/// compare(<<1, 2:size(2)>>, <<1, 2:size(2)>>) +/// // -> Eq +/// ``` +/// +pub fn compare(first: BitArray, second: BitArray) -> order.Order { + do_compare(first, second, 0) +} + +fn do_compare(first: BitArray, second: BitArray, index: Int) -> order.Order { + case slice(first, index, 1), slice(second, index, 1) { + Ok(<<first_byte>>), Ok(<<second_byte>>) -> + int.compare(first_byte, second_byte) + |> order.lazy_break_tie(fn() { + do_compare(first, second, index + 1) + }) + + // First has more items, example: "AB" > "A": + Ok(_), Error(_) -> order.Gt + // Second has more items, example: "A" < "AB": + Error(_), Ok(_) -> order.Lt + // Both have the same length, fallback: + _, _ -> order.Eq + } +} |