use crate::errors::BigQueryError;
use crate::BigQueryResult;
use serde::{Deserialize, Serialize, Serializer};
use std::borrow::Cow;
use std::fmt::{Display, Formatter};
use std::str::FromStr;
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize)]
#[serde(try_from = "String")]
pub struct BigQueryLocation(Cow<'static, str>);
impl BigQueryLocation {
pub fn new(location: impl Into<String>) -> BigQueryResult<Self> {
let location = location.into();
if location.is_empty() {
return Err(BigQueryError::invalid_parameters(
"location",
"must not be empty",
));
}
Ok(Self(Cow::Owned(location)))
}
pub const fn from_static(location: &'static str) -> Self {
assert!(!location.is_empty(), "a location must not be empty");
Self(Cow::Borrowed(location))
}
pub(crate) fn reported(location: String) -> Option<Self> {
(!location.is_empty()).then_some(Self(Cow::Owned(location)))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl Display for BigQueryLocation {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
Display::fmt(self.0.as_ref(), f)
}
}
impl TryFrom<&str> for BigQueryLocation {
type Error = BigQueryError;
fn try_from(location: &str) -> Result<Self, Self::Error> {
Self::new(location)
}
}
impl TryFrom<String> for BigQueryLocation {
type Error = BigQueryError;
fn try_from(location: String) -> Result<Self, Self::Error> {
Self::new(location)
}
}
impl FromStr for BigQueryLocation {
type Err = BigQueryError;
fn from_str(location: &str) -> Result<Self, Self::Err> {
Self::new(location)
}
}
impl Serialize for BigQueryLocation {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_empty_location_is_refused_everywhere_it_can_be_built() {
match BigQueryLocation::new("") {
Err(BigQueryError::InvalidParametersError(err)) => {
assert_eq!(err.public.field, "location")
}
other => panic!("expected an invalid location, got {other:?}"),
}
assert!("".parse::<BigQueryLocation>().is_err());
assert!(serde_json::from_str::<BigQueryLocation>(r#""""#).is_err());
assert_eq!(
serde_json::from_str::<BigQueryLocation>(r#""EU""#).expect("a location"),
BigQueryLocation::from_static("EU")
);
}
}