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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
// Copyright 2021 Palantir Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! A URI builder.

use bytes::BytesMut;
use conjure_object::{Plain, ToPlain};
use http::Uri;
use percent_encoding::{utf8_percent_encode, AsciiSet};
use std::collections::BTreeSet;

// https://url.spec.whatwg.org/#query-percent-encode-set
const QUERY: &AsciiSet = &percent_encoding::CONTROLS
    .add(b' ')
    .add(b'"')
    .add(b'#')
    .add(b'<')
    .add(b'>');

// https://url.spec.whatwg.org/#path-percent-encode-set
const PATH: &AsciiSet = &QUERY.add(b'?').add(b'`').add(b'{').add(b'}');

// https://url.spec.whatwg.org/#userinfo-percent-encode-set
const USERINFO: &AsciiSet = &PATH
    .add(b'/')
    .add(b':')
    .add(b';')
    .add(b'=')
    .add(b'@')
    .add(b'[')
    .add(b'\\')
    .add(b']')
    .add(b'^')
    .add(b'|');

// https://url.spec.whatwg.org/#component-percent-encode-set
const COMPONENT: &AsciiSet = &USERINFO.add(b'$').add(b'%').add(b'&').add(b'+').add(b',');

pub struct UriBuilder {
    buf: BytesMut,
    in_path: bool,
}

impl Default for UriBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl UriBuilder {
    pub fn new() -> Self {
        UriBuilder {
            buf: BytesMut::new(),
            in_path: true,
        }
    }

    pub fn push_literal(&mut self, components: &str) {
        debug_assert!(components.starts_with('/'));
        debug_assert!(!components.ends_with('/'));
        debug_assert!(self.in_path);

        self.buf.extend_from_slice(components.as_bytes());
    }

    pub fn push_path_parameter(&mut self, parameter: &dyn Plain) {
        self.push_path_parameter_raw(&parameter.to_plain());
    }

    pub fn push_path_parameter_raw(&mut self, parameter: &str) {
        debug_assert!(self.in_path);

        self.buf.extend_from_slice(b"/");
        self.push_escaped(parameter);
    }

    pub fn push_query_parameter(&mut self, key: &str, value: &dyn Plain) {
        self.push_query_parameter_raw(key, &value.to_plain())
    }

    pub fn push_query_parameter_raw(&mut self, key: &str, value: &str) {
        let prefix = if self.in_path { b"?" } else { b"&" };
        self.in_path = false;

        self.buf.extend_from_slice(prefix);
        self.buf.extend_from_slice(key.as_bytes());
        self.buf.extend_from_slice(b"=");
        self.push_escaped(value);
    }

    pub fn push_optional_query_parameter<T>(&mut self, key: &str, value: &Option<T>)
    where
        T: Plain,
    {
        if let Some(value) = value {
            self.push_query_parameter(key, value);
        }
    }

    pub fn push_list_query_parameter<T>(&mut self, key: &str, values: &[T])
    where
        T: Plain,
    {
        for value in values {
            self.push_query_parameter(key, value);
        }
    }

    pub fn push_set_query_parameter<T>(&mut self, key: &str, values: &BTreeSet<T>)
    where
        T: Plain,
    {
        for value in values {
            self.push_query_parameter(key, value);
        }
    }

    fn push_escaped(&mut self, value: &str) {
        for chunk in utf8_percent_encode(value, COMPONENT) {
            self.buf.extend_from_slice(chunk.as_bytes());
        }
    }

    pub fn build(self) -> Uri {
        debug_assert!(!self.buf.is_empty());

        Uri::from_maybe_shared(self.buf.freeze()).unwrap()
    }
}