aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorSebastian Porto <s@porto5.com>2020-10-31 22:20:20 +1100
committerGitHub <noreply@github.com>2020-10-31 12:20:20 +0100
commit33fd0fb3130bf1f11947385c42e8bfadb3c753e1 (patch)
treebb05d3c339787f796add38add8ad932f5c0ee7be /src
parent8e421527ad59a4bcea656ca1cdd6c643c99771c9 (diff)
downloadgleam_stdlib-33fd0fb3130bf1f11947385c42e8bfadb3c753e1.tar.gz
gleam_stdlib-33fd0fb3130bf1f11947385c42e8bfadb3c753e1.zip
Add percent_encode and percent_decode (#121)
Diffstat (limited to 'src')
-rw-r--r--src/gleam/uri.gleam28
1 files changed, 28 insertions, 0 deletions
diff --git a/src/gleam/uri.gleam b/src/gleam/uri.gleam
index 32910b5..2ff542a 100644
--- a/src/gleam/uri.gleam
+++ b/src/gleam/uri.gleam
@@ -14,6 +14,7 @@ import gleam/string
import gleam/dynamic.{Dynamic}
import gleam/map.{Map}
import gleam/function
+import gleam/pair
/// Type representing holding the parsed components of an URI.
/// All components of a URI are optional, except the path.
@@ -119,6 +120,33 @@ pub fn query_to_string(query: List(tuple(String, String))) -> String {
|> result.unwrap("")
}
+/// Encode a string into a percent encoded representation.
+/// Note that this encodes space as +.
+///
+/// ## Example
+///
+/// percent_encode("100% great")
+/// > "100%25+great"
+///
+pub fn percent_encode(value: String) -> String {
+ query_to_string([tuple("k", value)])
+ |> string.replace(each: "k=", with: "")
+}
+
+/// Decode a percent encoded string.
+///
+/// ## Example
+///
+/// percent_decode("100%25+great")
+/// > Ok("100% great")
+///
+pub fn percent_decode(value: String) -> Result(String, Nil) {
+ string.concat(["k=", value])
+ |> parse_query
+ |> result.then(list.head)
+ |> result.map(pair.second)
+}
+
fn do_remove_dot_segments(
input: List(String),
accumulator: List(String),