#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Region {
pub province: String,
pub city: String,
pub district: Option<String>,
}
impl Region {
pub fn new(
province: impl Into<String>,
city: impl Into<String>,
district: Option<String>,
) -> Self {
Self {
province: province.into(),
city: city.into(),
district,
}
}
pub fn full_name(&self) -> String {
match &self.district {
Some(d) => format!("{}{}{}", self.province, self.city, d),
None => format!("{}{}", self.province, self.city),
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ParsedAddress {
pub province: Option<String>,
pub city: Option<String>,
pub district: Option<String>,
pub detail: String,
}
impl ParsedAddress {
pub fn empty() -> Self {
Self::default()
}
pub fn has_province(&self) -> bool {
self.province.is_some()
}
pub fn has_city(&self) -> bool {
self.city.is_some()
}
pub fn has_district(&self) -> bool {
self.district.is_some()
}
pub fn is_complete(&self) -> bool {
self.province.is_some() && self.city.is_some() && self.district.is_some()
}
pub fn full_address(&self) -> String {
let mut result = String::new();
if let Some(ref p) = self.province {
result.push_str(p);
}
if let Some(ref c) = self.city {
if self.province.as_ref() != Some(c) {
result.push_str(c);
}
}
if let Some(ref d) = self.district {
result.push_str(d);
}
if !self.detail.is_empty() {
result.push_str(&self.detail);
}
result
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_region_full_name() {
let region = Region::new("广东省", "深圳市", Some("南山区".to_string()));
assert_eq!(region.full_name(), "广东省深圳市南山区");
let region = Region::new("广东省", "东莞市", None);
assert_eq!(region.full_name(), "广东省东莞市");
}
#[test]
fn test_parsed_address() {
let addr = ParsedAddress {
province: Some("广东省".to_string()),
city: Some("深圳市".to_string()),
district: Some("南山区".to_string()),
detail: "科技园".to_string(),
};
assert!(addr.is_complete());
assert_eq!(addr.full_address(), "广东省深圳市南山区科技园");
}
#[test]
fn test_municipality_address() {
let addr = ParsedAddress {
province: Some("北京市".to_string()),
city: Some("北京市".to_string()),
district: Some("朝阳区".to_string()),
detail: "望京".to_string(),
};
assert_eq!(addr.full_address(), "北京市朝阳区望京");
}
}