| /* | |
| * Licensed to the Apache Software Foundation (ASF) under one | |
| * or more contributor license agreements. See the NOTICE file | |
| * distributed with this work for additional information | |
| * regarding copyright ownership. The ASF licenses this file | |
| * to you 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. | |
| */ | |
| use maka_remote_pairing::directory::{InvalidRegisteredRootId, RegisteredRootId}; | |
| use serde::{Deserialize, Serialize, de}; | |
| use std::{fmt, str::FromStr}; | |
| use thiserror::Error; | |
| /// An explicit Root address segment used by URIs and the router. | |
| #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)] | |
| #[serde(transparent)] | |
| pub struct RootId(String); | |
| #[derive(Clone, Copy, Debug, Error, PartialEq, Eq)] | |
| #[error("Root ID must contain only ASCII letters, digits, '_' or '-' and must not be empty")] | |
| pub struct InvalidRootId; | |
| impl RootId { | |
| pub fn as_str(&self) -> &str { | |
| &self.0 | |
| } | |
| } | |
| impl fmt::Display for RootId { | |
| fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
| f.write_str(self.as_str()) | |
| } | |
| } | |
| impl FromStr for RootId { | |
| type Err = InvalidRootId; | |
| fn from_str(value: &str) -> Result<Self, Self::Err> { | |
| if value.is_empty() | |
| || !value | |
| .bytes() | |
| .all(|b| b.is_ascii_alphanumeric() || b"_-".contains(&b)) | |
| { | |
| return Err(InvalidRootId); | |
| } | |
| Ok(Self(value.to_owned())) | |
| } | |
| } | |
| impl From<RegisteredRootId> for RootId { | |
| fn from(id: RegisteredRootId) -> Self { | |
| Self(id.into()) | |
| } | |
| } | |
| impl TryFrom<RootId> for RegisteredRootId { | |
| type Error = InvalidRegisteredRootId; | |
| fn try_from(id: RootId) -> Result<Self, Self::Error> { | |
| id.0.try_into() | |
| } | |
| } | |
| impl<'de> Deserialize<'de> for RootId { | |
| fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { | |
| String::deserialize(deserializer)? | |
| .parse() | |
| .map_err(de::Error::custom) | |
| } | |
| } |