From 8f96800d9acafaa90490988c6d5a199ae6732738 Mon Sep 17 00:00:00 2001 From: Jcparkyn <51850908+Jcparkyn@users.noreply.github.com> Date: Fri, 3 Nov 2023 09:15:16 +0000 Subject: [PATCH] Switch to base64Url --- elm.json | 1 + src/UrlBase64.elm | 70 +++++++++++++++++++++++++++++++++++++++++++++++ src/UrlState.elm | 3 ++ 3 files changed, 74 insertions(+) create mode 100644 src/UrlBase64.elm diff --git a/elm.json b/elm.json index 787a10f..a9a4ad9 100644 --- a/elm.json +++ b/elm.json @@ -13,6 +13,7 @@ "elm/html": "1.0.0", "elm/json": "1.1.3", "elm/random": "1.0.0", + "elm/regex": "1.0.0", "elm/svg": "1.0.1", "elm/url": "1.0.0", "elm-community/array-extra": "2.6.0", diff --git a/src/UrlBase64.elm b/src/UrlBase64.elm new file mode 100644 index 0000000..afa289a --- /dev/null +++ b/src/UrlBase64.elm @@ -0,0 +1,70 @@ +module UrlBase64 exposing (fromUrl, toUrl) + +import Maybe +import Regex exposing (Regex) + + + +-- Simplified version of https://github.com/prozacchiwawa/elm-urlbase64/blob/1.0.6/src/UrlBase64.elm + + +replaceForUrl : Regex +replaceForUrl = + Regex.fromString "[\\+/=]" |> Maybe.withDefault Regex.never + + +{-| Convert from the standard base64 alphabet to urlBase64, and trim trailing '=' characters. +-} +toUrl : String -> String +toUrl t = + let + replaceChar rematch = + case rematch.match of + "+" -> + "-" + + "/" -> + "_" + + _ -> + "" + in + Regex.replace replaceForUrl replaceChar t + + +replaceFromUrl : Regex +replaceFromUrl = + Regex.fromString "[-_]" |> Maybe.withDefault Regex.never + + +{-| Convert from urlBase64 to standard base64 +-} +fromUrl : String -> String +fromUrl e = + let + replaceChar rematch = + case rematch.match of + "-" -> + "+" + + _ -> + "/" + + strlen = + String.length e + + hanging = + if strlen == 0 then + 4 + + else + modBy 4 strlen + + ilen = + if hanging == 0 then + 0 + + else + 4 - hanging + in + Regex.replace replaceFromUrl replaceChar (e ++ String.repeat ilen "=") diff --git a/src/UrlState.elm b/src/UrlState.elm index f9cc2d6..82faf0a 100644 --- a/src/UrlState.elm +++ b/src/UrlState.elm @@ -12,6 +12,7 @@ import Point exposing (Point) import Url import Url.Parser import Url.Parser.Query +import UrlBase64 type alias UrlModel = @@ -33,6 +34,7 @@ compressToBase64 str = |> BE.encode |> deflate |> Base64.fromBytes + |> Maybe.map UrlBase64.toUrl |> Maybe.withDefault "" @@ -43,6 +45,7 @@ decompressFromBase64 str = BD.decode (BD.string (Bytes.width buffer)) buffer in str + |> UrlBase64.fromUrl |> Base64.toBytes |> Result.fromMaybe Base64Error |> Result.andThen (inflate >> Result.fromMaybe InflateError)