about summary refs log tree commit diff
path: root/users/sterni/nix/url/default.nix
blob: ce7ed9b8343731a139da929498961474cc307316 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
{ depot, lib, ... }:

let

  inherit (depot.users.sterni.nix)
    char
    int
    string
    ;

  reserved = c: builtins.elem c [
    "!" "#" "$" "&" "'" "(" ")"
    "*" "+" "," "/" ":" ";" "="
    "?" "@" "[" "]"
  ];

  unreserved = c: char.asciiAlphaNum c
    || builtins.elem c [ "-" "_" "." "~" ];

  percentEncode = c:
    if unreserved c
    then c
    else "%" + (string.fit {
      width = 2;
      char = "0";
      side = "left";
    } (int.toHex (char.ord c)));

  encode = { leaveReserved ? false }: s:
    let
      chars = lib.stringToCharacters s;
      tr = c:
        if leaveReserved && reserved c
        then c
        else percentEncode c;
    in lib.concatStrings (builtins.map tr chars);

in {
  inherit
    encode
    ;
}