Skip to content

Instantly share code, notes, and snippets.

@kipcole9
Last active November 25, 2018 11:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kipcole9/3249987f8a9064b874aa645bf14e965d to your computer and use it in GitHub Desktop.
Save kipcole9/3249987f8a9064b874aa645bf14e965d to your computer and use it in GitHub Desktop.
Case incentive String comparison for ASCII strings
defmodule InsensitiveString do
@moduledoc """
Case insensitive string functions for
ASCII string
"""
@doc """
Compare two ascii strings in a case insensitive
manner
## Example
iex> InsensitiveString.cmp "aaa", "bbb"
:lt
iex> InsensitiveString.cmp "aaa", "BBB"
:lt
"""
def cmp("", "") do
:eq
end
def cmp(<< h1 :: 3, c1 :: 5, rest1 :: binary>>, << h2 :: 3, c2 :: 5, rest2 :: binary>>)
when c1 < 128 and c2 < 128 and c1 == c2 and h1 in [2,3] and h2 in [2,3] do
cmp(rest1, rest2)
end
def cmp(<< h1 :: 3, c1 :: 5, _rest1 :: binary>>, << h2 :: 3, c2 :: 5, _rest2 :: binary>>)
when c1 < 128 and c2 < 128 and c1 > c2 and h1 in [2,3] and h2 in [2,3] do
:gt
end
def cmp(<< h1 :: 3, c1 :: 5, _rest1 :: binary>>, << h2 :: 3, c2 :: 5, _rest2 :: binary>>)
when c1 < 128 and c2 < 128 and c1 < c2 and h1 in [2,3] and h2 in [2,3] do
:lt
end
def cmp(<< c1 :: 8, rest1 :: binary>>, << c2 :: 8, rest2 :: binary>>)
when c1 < 128 and c2 < 128 and c1 == c2 do
cmp(rest1, rest2)
end
def cmp(<< c1 :: 8, _rest1 :: binary>>, << c2 :: 8, _rest2 :: binary>>)
when c1 < 128 and c2 < 128 and c1 > c2 do
:gt
end
def cmp(<< c1 :: 8, _rest1 :: binary>>, << c2 :: 8, _rest2 :: binary>>)
when c1 < 128 and c2 < 128 and c1 < c2 do
:lt
end
def cmp2(a, b) do
raise ArgumentError, "String #{inspect a} or #{inspect b} is not ASCII"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment