Skip to content

Commit

Permalink
Switch to base64Url
Browse files Browse the repository at this point in the history
  • Loading branch information
Jcparkyn committed Nov 3, 2023
1 parent 794cab3 commit 8f96800
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 0 deletions.
1 change: 1 addition & 0 deletions elm.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
70 changes: 70 additions & 0 deletions src/UrlBase64.elm
Original file line number Diff line number Diff line change
@@ -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 "=")
3 changes: 3 additions & 0 deletions src/UrlState.elm
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import Point exposing (Point)
import Url
import Url.Parser
import Url.Parser.Query
import UrlBase64


type alias UrlModel =
Expand All @@ -33,6 +34,7 @@ compressToBase64 str =
|> BE.encode
|> deflate
|> Base64.fromBytes
|> Maybe.map UrlBase64.toUrl
|> Maybe.withDefault ""


Expand All @@ -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)
Expand Down

0 comments on commit 8f96800

Please sign in to comment.