From 905e8d6e6db8ad0dfc061861cef5ccb96f84012b Mon Sep 17 00:00:00 2001 From: sobolevn Date: Sat, 17 Aug 2024 22:36:32 +0300 Subject: Add `bit_array.compare` --- src/gleam/bit_array.gleam | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) (limited to 'src') 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(<>), Ok(<>) -> + 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 + } +} -- cgit v1.2.3