s2n_quic_core/application/server_name.rs
1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4use bytes::Bytes;
5
6/// ServerName holds a negotiated
7/// [Server Name Indication](https://en.wikipedia.org/wiki/Server_Name_Indication)
8/// value, encoded as UTF-8.
9///
10/// ServerName should be a valid UTF-8 string, therefore this struct can only be
11/// constructed from a `&str` or `String`.
12///
13/// ```rust
14/// # use s2n_quic_core::application::ServerName;
15/// let string: String = String::from("a valid utf-8 string");
16/// let name: ServerName = string.into();
17///
18/// let str_arr: &str = &"a valid utf-8 str array";
19/// let name: ServerName = str_arr.into();
20/// ```
21///
22/// `ServerName` serves a dual purpose:
23/// - It can be converted into [`Bytes`] which supports zero-copy slicing and
24/// reference counting.
25/// - It can be accessed as `&str` so that applications can reason about the string value.
26#[derive(Clone, PartialEq, Eq, Hash)]
27pub struct ServerName(Bytes);
28
29/// A static value for localhost
30#[allow(dead_code)] // this is used by conditional modules so don't warn
31pub(crate) static LOCALHOST: ServerName = ServerName(Bytes::from_static(b"localhost"));
32
33impl ServerName {
34 #[inline]
35 pub fn into_bytes(self) -> Bytes {
36 self.0
37 }
38
39 #[inline]
40 fn as_str(&self) -> &str {
41 // Safety: the byte array is validated as a valid UTF-8 string
42 // before creating an instance of Sni.
43 unsafe { core::str::from_utf8_unchecked(&self.0) }
44 }
45}
46
47impl From<&str> for ServerName {
48 #[inline]
49 fn from(data: &str) -> Self {
50 Self(Bytes::copy_from_slice(data.as_bytes()))
51 }
52}
53
54#[cfg(feature = "alloc")]
55impl From<alloc::string::String> for ServerName {
56 #[inline]
57 fn from(data: alloc::string::String) -> Self {
58 Self(data.into_bytes().into())
59 }
60}
61
62impl core::fmt::Debug for ServerName {
63 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
64 self.as_str().fmt(f)
65 }
66}
67
68impl core::ops::Deref for ServerName {
69 type Target = str;
70
71 #[inline]
72 fn deref(&self) -> &Self::Target {
73 self.as_str()
74 }
75}