Skip to main content

typedb_driver/common/address/
address.rs

1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements.  See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership.  The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License.  You may obtain a copy of the License at
9 *
10 *   http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied.  See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20use std::{fmt, str::FromStr};
21
22use http::{Uri, uri::PathAndQuery};
23
24use crate::{
25    common::{Error, Result},
26    error::ConnectionError,
27};
28
29#[derive(Clone, Hash, PartialEq, Eq, Default)]
30pub struct Address {
31    uri: Uri,
32}
33
34impl Address {
35    const DEFAULT_PATH: &'static str = "/";
36
37    pub(crate) fn into_uri(self) -> Uri {
38        self.uri
39    }
40
41    pub(crate) fn uri_scheme(&self) -> Option<&http::uri::Scheme> {
42        self.uri.scheme()
43    }
44
45    pub(crate) fn with_scheme(&self, scheme: http::uri::Scheme) -> Self {
46        let mut parts = self.uri.clone().into_parts();
47        parts.scheme = Some(scheme);
48        if parts.path_and_query.is_none() {
49            parts.path_and_query = Some(PathAndQuery::from_static(Self::DEFAULT_PATH));
50        }
51        Self { uri: Uri::from_parts(parts).expect("Expected valid URI after scheme change") }
52    }
53}
54
55impl FromStr for Address {
56    type Err = Error;
57
58    fn from_str(address: &str) -> Result<Self> {
59        let uri = address.parse::<Uri>()?;
60        if uri.port().is_none() {
61            return Err(Error::Connection(ConnectionError::MissingPort { address: address.to_owned() }));
62        }
63        Ok(Self { uri })
64    }
65}
66
67impl fmt::Display for Address {
68    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69        write!(f, "{}", self.uri.authority().unwrap())
70    }
71}
72
73impl fmt::Debug for Address {
74    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75        write!(f, "{:?}", self.uri)
76    }
77}