use std::fmt;
use std::str::FromStr;
use crate::error::{DecodeError, ParseError};
use crate::plmn::{Mcc, PlmnId};
const fn is_reserved_area(value: u32, bits: u8) -> bool {
value == 0 || value == (1u32 << bits) - 2
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Lac(u16);
impl Lac {
#[must_use]
pub const fn is_reserved(value: u16) -> bool {
is_reserved_area(value as u32, 16)
}
#[must_use]
pub const fn new(value: u16) -> Option<Self> {
if Self::is_reserved(value) {
None
} else {
Some(Self(value))
}
}
#[must_use]
pub const fn get(self) -> u16 {
self.0
}
}
impl fmt::Display for Lac {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:04X}", self.0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CellId(u16);
impl CellId {
#[must_use]
pub const fn new(value: u16) -> Self {
Self(value)
}
#[must_use]
pub const fn get(self) -> u16 {
self.0
}
}
impl fmt::Display for CellId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:04X}", self.0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ServiceAreaCode(u16);
impl ServiceAreaCode {
#[must_use]
pub const fn new(value: u16) -> Self {
Self(value)
}
#[must_use]
pub const fn get(self) -> u16 {
self.0
}
}
impl fmt::Display for ServiceAreaCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:04X}", self.0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Cgi {
plmn: PlmnId,
lac: Lac,
cell: CellId,
}
impl Cgi {
#[must_use]
pub const fn new(plmn: PlmnId, lac: Lac, cell: CellId) -> Self {
Self { plmn, lac, cell }
}
#[must_use]
pub const fn plmn(self) -> PlmnId {
self.plmn
}
#[must_use]
pub const fn lac(self) -> Lac {
self.lac
}
#[must_use]
pub const fn cell(self) -> CellId {
self.cell
}
}
impl fmt::Display for Cgi {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}-{}-{}", self.plmn, self.lac, self.cell)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Sai {
plmn: PlmnId,
lac: Lac,
sac: ServiceAreaCode,
}
impl Sai {
#[must_use]
pub const fn new(plmn: PlmnId, lac: Lac, sac: ServiceAreaCode) -> Self {
Self { plmn, lac, sac }
}
#[must_use]
pub const fn plmn(self) -> PlmnId {
self.plmn
}
#[must_use]
pub const fn lac(self) -> Lac {
self.lac
}
#[must_use]
pub const fn sac(self) -> ServiceAreaCode {
self.sac
}
}
impl fmt::Display for Sai {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}-{}-{}", self.plmn, self.lac, self.sac)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RoutingAreaCode(u8);
impl RoutingAreaCode {
#[must_use]
pub const fn new(value: u8) -> Self {
Self(value)
}
#[must_use]
pub const fn get(self) -> u8 {
self.0
}
}
impl fmt::Display for RoutingAreaCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:02X}", self.0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Lai {
plmn: PlmnId,
lac: Lac,
}
impl Lai {
#[must_use]
pub const fn new(plmn: PlmnId, lac: Lac) -> Self {
Self { plmn, lac }
}
#[must_use]
pub const fn plmn(self) -> PlmnId {
self.plmn
}
#[must_use]
pub const fn lac(self) -> Lac {
self.lac
}
}
impl fmt::Display for Lai {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}-{}", self.plmn, self.lac)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Rai {
plmn: PlmnId,
lac: Lac,
rac: RoutingAreaCode,
}
impl Rai {
#[must_use]
pub const fn new(plmn: PlmnId, lac: Lac, rac: RoutingAreaCode) -> Self {
Self { plmn, lac, rac }
}
#[must_use]
pub const fn plmn(self) -> PlmnId {
self.plmn
}
#[must_use]
pub const fn lac(self) -> Lac {
self.lac
}
#[must_use]
pub const fn rac(self) -> RoutingAreaCode {
self.rac
}
#[must_use]
pub const fn lai(self) -> Lai {
Lai::new(self.plmn, self.lac)
}
}
impl fmt::Display for Rai {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}-{}-{}", self.plmn, self.lac, self.rac)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum EnbKind {
Macro,
Home,
}
impl EnbKind {
pub const ALL: &'static [Self] = &[Self::Macro, Self::Home];
pub const CODES: &'static [&'static str] = &["MACRO", "HOME"];
#[must_use]
pub const fn id_bits(self) -> u8 {
match self {
Self::Macro => 20,
Self::Home => 28,
}
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Macro => "MACRO",
Self::Home => "HOME",
}
}
}
impl fmt::Display for EnbKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl FromStr for EnbKind {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::ALL
.iter()
.find(|k| k.as_str().eq_ignore_ascii_case(s.trim()))
.copied()
.ok_or_else(|| ParseError::format("EnbKind", s, "MACRO or HOME"))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Eci(u32);
impl Eci {
pub const BITS: u32 = 28;
const LIMIT: u32 = 1 << Self::BITS;
#[must_use]
pub const fn new(value: u32) -> Option<Self> {
if value < Self::LIMIT {
Some(Self(value))
} else {
None
}
}
#[must_use]
pub const fn get(self) -> u32 {
self.0
}
#[must_use]
pub const fn enb_id(self, kind: EnbKind) -> u32 {
match kind {
EnbKind::Macro => self.0 >> 8,
EnbKind::Home => self.0,
}
}
#[must_use]
pub const fn cell_id(self, kind: EnbKind) -> Option<u8> {
match kind {
EnbKind::Macro => Some((self.0 & 0xFF) as u8),
EnbKind::Home => None,
}
}
}
impl fmt::Display for Eci {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:07X}", self.0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Ecgi {
plmn: PlmnId,
eci: Eci,
}
impl Ecgi {
#[must_use]
pub const fn new(plmn: PlmnId, eci: Eci) -> Self {
Self { plmn, eci }
}
#[must_use]
pub const fn plmn(self) -> PlmnId {
self.plmn
}
#[must_use]
pub const fn eci(self) -> Eci {
self.eci
}
}
impl fmt::Display for Ecgi {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}-{}", self.plmn, self.eci)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct GnbIdLength(u8);
impl GnbIdLength {
pub const MIN: u8 = 22;
pub const MAX: u8 = 32;
#[must_use]
pub const fn new(bits: u8) -> Option<Self> {
if bits >= Self::MIN && bits <= Self::MAX {
Some(Self(bits))
} else {
None
}
}
#[must_use]
pub const fn get(self) -> u8 {
self.0
}
#[must_use]
pub const fn cell_bits(self) -> u8 {
Nci::BITS as u8 - self.0
}
}
impl fmt::Display for GnbIdLength {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl FromStr for GnbIdLength {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let err = || ParseError::format("GnbIdLength", s, "a bit count from 22 to 32");
Self::new(s.trim().parse::<u8>().map_err(|_| err())?).ok_or_else(err)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Nci(u64);
impl Nci {
pub const BITS: u32 = 36;
const LIMIT: u64 = 1 << Self::BITS;
#[must_use]
pub const fn new(value: u64) -> Option<Self> {
if value < Self::LIMIT {
Some(Self(value))
} else {
None
}
}
#[must_use]
pub const fn get(self) -> u64 {
self.0
}
#[must_use]
pub const fn gnb_id(self, length: GnbIdLength) -> u64 {
self.0 >> length.cell_bits()
}
#[must_use]
pub const fn cell_id(self, length: GnbIdLength) -> u64 {
self.0 & ((1u64 << length.cell_bits()) - 1)
}
}
impl fmt::Display for Nci {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:09X}", self.0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Ncgi {
plmn: PlmnId,
nci: Nci,
}
impl Ncgi {
#[must_use]
pub const fn new(plmn: PlmnId, nci: Nci) -> Self {
Self { plmn, nci }
}
#[must_use]
pub const fn plmn(self) -> PlmnId {
self.plmn
}
#[must_use]
pub const fn nci(self) -> Nci {
self.nci
}
}
impl fmt::Display for Ncgi {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}-{}", self.plmn, self.nci)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum TacWidth {
Eps,
FiveGs,
}
impl TacWidth {
pub const ALL: &'static [Self] = &[Self::Eps, Self::FiveGs];
pub const CODES: &'static [&'static str] = &["EPS", "5GS"];
#[must_use]
pub const fn bits(self) -> u8 {
match self {
Self::Eps => 16,
Self::FiveGs => 24,
}
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Eps => "EPS",
Self::FiveGs => "5GS",
}
}
}
impl fmt::Display for TacWidth {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl FromStr for TacWidth {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::ALL
.iter()
.find(|w| w.as_str().eq_ignore_ascii_case(s.trim()))
.copied()
.ok_or_else(|| ParseError::format("TacWidth", s, "EPS or 5GS"))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TrackingAreaCode {
value: u32,
width: TacWidth,
}
impl TrackingAreaCode {
#[must_use]
pub const fn eps(value: u16) -> Option<Self> {
if is_reserved_area(value as u32, TacWidth::Eps.bits()) {
None
} else {
Some(Self {
value: value as u32,
width: TacWidth::Eps,
})
}
}
#[must_use]
pub const fn five_gs(value: u32) -> Option<Self> {
if value > 0x00FF_FFFF || is_reserved_area(value, TacWidth::FiveGs.bits()) {
None
} else {
Some(Self {
value,
width: TacWidth::FiveGs,
})
}
}
#[must_use]
pub const fn get(self) -> u32 {
self.value
}
#[must_use]
pub const fn width(self) -> TacWidth {
self.width
}
#[must_use]
pub const fn widened(self) -> Self {
Self {
value: self.value,
width: TacWidth::FiveGs,
}
}
#[must_use]
pub const fn is_same_area(self, other: Self) -> bool {
self.value == other.value
}
}
impl fmt::Display for TrackingAreaCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.width {
TacWidth::Eps => write!(f, "{:04X}", self.value),
TacWidth::FiveGs => write!(f, "{:06X}", self.value),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Tai {
plmn: PlmnId,
tac: TrackingAreaCode,
}
impl Tai {
#[must_use]
pub const fn new(plmn: PlmnId, tac: TrackingAreaCode) -> Self {
Self { plmn, tac }
}
#[must_use]
pub const fn plmn(self) -> PlmnId {
self.plmn
}
#[must_use]
pub const fn tac(self) -> TrackingAreaCode {
self.tac
}
}
impl fmt::Display for Tai {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}-{}", self.plmn, self.tac)
}
}
fn hex_exact(field: &str, width: usize) -> Option<u32> {
if field.len() != width || !field.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
u32::from_str_radix(field, 16).ok()
}
fn split_plmn(s: &str, expected_fields: usize) -> Option<(PlmnId, Vec<&str>)> {
let fields: Vec<&str> = s.trim().split('-').collect();
if fields.len() != expected_fields {
return None;
}
let plmn = format!("{}-{}", fields[0], fields[1]).parse().ok()?;
Some((plmn, fields[2..].to_vec()))
}
macro_rules! parsed_composite {
($t:ty, $name:literal, $fields:expr, $shape:literal, $build:expr) => {
impl FromStr for $t {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let err = || ParseError::format($name, s, $shape);
let (plmn, rest) = split_plmn(s, $fields).ok_or_else(err)?;
#[allow(clippy::redundant_closure_call)]
($build)(plmn, rest.as_slice()).ok_or_else(err)
}
}
};
}
parsed_composite!(
Lai,
"Lai",
3,
"a location area identity such as 262-02-1A2B",
|plmn, rest: &[&str]| {
let lac = Lac::new(u16::try_from(hex_exact(rest[0], 4)?).ok()?)?;
Some(Lai::new(plmn, lac))
}
);
parsed_composite!(
Rai,
"Rai",
4,
"a routing area identity such as 262-02-1A2B-05",
|plmn, rest: &[&str]| {
let lac = Lac::new(u16::try_from(hex_exact(rest[0], 4)?).ok()?)?;
let rac = RoutingAreaCode::new(u8::try_from(hex_exact(rest[1], 2)?).ok()?);
Some(Rai::new(plmn, lac, rac))
}
);
parsed_composite!(
Cgi,
"Cgi",
4,
"a cell global identity such as 262-02-1A2B-00FF",
|plmn, rest: &[&str]| {
let lac = Lac::new(u16::try_from(hex_exact(rest[0], 4)?).ok()?)?;
let cell = CellId::new(u16::try_from(hex_exact(rest[1], 4)?).ok()?);
Some(Cgi::new(plmn, lac, cell))
}
);
parsed_composite!(
Sai,
"Sai",
4,
"a service area identity such as 262-02-1A2B-0007",
|plmn, rest: &[&str]| {
let lac = Lac::new(u16::try_from(hex_exact(rest[0], 4)?).ok()?)?;
let sac = ServiceAreaCode::new(u16::try_from(hex_exact(rest[1], 4)?).ok()?);
Some(Sai::new(plmn, lac, sac))
}
);
parsed_composite!(
Ecgi,
"Ecgi",
3,
"an E-UTRAN cell global identity such as 262-02-0A1B2C3",
|plmn, rest: &[&str]| Some(Ecgi::new(plmn, Eci::new(hex_exact(rest[0], 7)?)?))
);
parsed_composite!(
Ncgi,
"Ncgi",
3,
"an NR cell global identity such as 262-02-012345678",
|plmn, rest: &[&str]| {
let field = rest[0];
if field.len() != 9 || !field.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
Some(Ncgi::new(
plmn,
Nci::new(u64::from_str_radix(field, 16).ok()?)?,
))
}
);
parsed_composite!(
Tai,
"Tai",
3,
"a tracking area identity such as 262-02-002A (EPS) or 262-02-00002A (5GS)",
|plmn, rest: &[&str]| {
let field = rest[0];
let tac = match field.len() {
4 => TrackingAreaCode::eps(u16::try_from(hex_exact(field, 4)?).ok()?),
6 => TrackingAreaCode::five_gs(hex_exact(field, 6)?),
_ => None,
}?;
Some(Tai::new(plmn, tac))
}
);
const USER_LOCATION_FORMAT: &str =
"a tagged location such as ecgi:262-02-0A1B2C3, cgi:262-02-1A2B-00FF or tai:262-02-002A";
impl FromStr for UserLocation {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let err = || ParseError::format("UserLocation", s, USER_LOCATION_FORMAT);
let (tag, body) = s.trim().split_once(':').ok_or_else(err)?;
match tag.to_ascii_lowercase().as_str() {
"cgi" => body.parse().map(Self::Cgi),
"sai" => body.parse().map(Self::Sai),
"ecgi" => body.parse().map(Self::Ecgi),
"ncgi" => body.parse().map(Self::Ncgi),
"tai" => body.parse().map(Self::Tai),
"rai" => body.parse().map(Self::Rai),
"lai" => body.parse().map(Self::Lai),
_ => return Err(err()),
}
.map_err(|_| err())
}
}
const fn u16_at(bytes: &[u8], at: usize) -> u16 {
((bytes[at] as u16) << 8) | bytes[at + 1] as u16
}
fn plmn_and_lac(bytes: &[u8]) -> Result<(PlmnId, Lac), DecodeError> {
let plmn = PlmnId::from_bcd(&bytes[..3])?;
let lac = Lac::new(u16_at(bytes, 3))
.ok_or_else(|| DecodeError::new(3, "a location area code that is not reserved"))?;
Ok((plmn, lac))
}
impl Lai {
pub const OCTETS: usize = 5;
pub fn from_bytes(bytes: &[u8]) -> Result<Self, DecodeError> {
if bytes.len() != Self::OCTETS {
return Err(DecodeError::new(0, "exactly 5 octets"));
}
let (plmn, lac) = plmn_and_lac(bytes)?;
Ok(Self::new(plmn, lac))
}
#[must_use]
pub fn to_bytes(self) -> [u8; Self::OCTETS] {
let plmn = self.plmn.to_bcd();
let lac = self.lac.get().to_be_bytes();
[plmn[0], plmn[1], plmn[2], lac[0], lac[1]]
}
}
impl Cgi {
pub const OCTETS: usize = 7;
pub fn from_bytes(bytes: &[u8]) -> Result<Self, DecodeError> {
if bytes.len() != Self::OCTETS {
return Err(DecodeError::new(0, "exactly 7 octets"));
}
let (plmn, lac) = plmn_and_lac(bytes)?;
Ok(Self::new(plmn, lac, CellId::new(u16_at(bytes, 5))))
}
#[must_use]
pub fn to_bytes(self) -> [u8; Self::OCTETS] {
let plmn = self.plmn().to_bcd();
let lac = self.lac().get().to_be_bytes();
let cell = self.cell().get().to_be_bytes();
[plmn[0], plmn[1], plmn[2], lac[0], lac[1], cell[0], cell[1]]
}
}
impl Sai {
pub const OCTETS: usize = 7;
pub fn from_bytes(bytes: &[u8]) -> Result<Self, DecodeError> {
if bytes.len() != Self::OCTETS {
return Err(DecodeError::new(0, "exactly 7 octets"));
}
let (plmn, lac) = plmn_and_lac(bytes)?;
Ok(Self::new(plmn, lac, ServiceAreaCode::new(u16_at(bytes, 5))))
}
#[must_use]
pub fn to_bytes(self) -> [u8; Self::OCTETS] {
let plmn = self.plmn().to_bcd();
let lac = self.lac().get().to_be_bytes();
let sac = self.sac().get().to_be_bytes();
[plmn[0], plmn[1], plmn[2], lac[0], lac[1], sac[0], sac[1]]
}
}
impl Rai {
pub const OCTETS: usize = 7;
pub const SPARE: u8 = 0xFF;
pub fn from_bytes(bytes: &[u8]) -> Result<Self, DecodeError> {
if bytes.len() != Self::OCTETS {
return Err(DecodeError::new(0, "exactly 7 octets"));
}
let (plmn, lac) = plmn_and_lac(bytes)?;
Ok(Self::new(plmn, lac, RoutingAreaCode::new(bytes[5])))
}
#[must_use]
pub fn to_bytes(self) -> [u8; Self::OCTETS] {
let plmn = self.plmn.to_bcd();
let lac = self.lac.get().to_be_bytes();
[
plmn[0],
plmn[1],
plmn[2],
lac[0],
lac[1],
self.rac.get(),
Self::SPARE,
]
}
}
impl Tai {
pub const EPS_OCTETS: usize = 5;
pub const FIVE_GS_OCTETS: usize = 6;
pub fn from_bytes(bytes: &[u8]) -> Result<Self, DecodeError> {
let plmn_len = PlmnId::BCD_OCTETS;
let tac = match bytes.len() {
Self::EPS_OCTETS => TrackingAreaCode::eps(u16_at(bytes, plmn_len)),
Self::FIVE_GS_OCTETS => TrackingAreaCode::five_gs(
(u32::from(bytes[plmn_len]) << 16)
| (u32::from(bytes[plmn_len + 1]) << 8)
| u32::from(bytes[plmn_len + 2]),
),
_ => return Err(DecodeError::new(0, "5 octets (EPS) or 6 (5GS)")),
};
let tac = tac.ok_or_else(|| {
DecodeError::new(plmn_len, "a tracking area code that is not reserved")
})?;
Ok(Self::new(PlmnId::from_bcd(&bytes[..plmn_len])?, tac))
}
pub fn to_bytes(self, out: &mut [u8]) -> Result<usize, DecodeError> {
let needed = match self.tac().width() {
TacWidth::Eps => Self::EPS_OCTETS,
TacWidth::FiveGs => Self::FIVE_GS_OCTETS,
};
if out.len() < needed {
return Err(DecodeError::new(0, "a buffer of 5 octets (EPS) or 6 (5GS)"));
}
out[..3].copy_from_slice(&self.plmn().to_bcd());
let value = self.tac().get();
match self.tac().width() {
TacWidth::Eps => out[3..5].copy_from_slice(&(value as u16).to_be_bytes()),
TacWidth::FiveGs => {
out[3] = (value >> 16) as u8;
out[4] = (value >> 8) as u8;
out[5] = value as u8;
}
}
Ok(needed)
}
}
impl Ecgi {
pub const OCTETS: usize = 7;
pub fn from_bytes(bytes: &[u8]) -> Result<Self, DecodeError> {
if bytes.len() != Self::OCTETS {
return Err(DecodeError::new(0, "exactly 7 octets"));
}
let raw = u32::from_be_bytes([bytes[3], bytes[4], bytes[5], bytes[6]]);
let eci = Eci::new(raw & 0x0FFF_FFFF)
.ok_or_else(|| DecodeError::new(3, "a 28-bit E-UTRAN cell identity"))?;
Ok(Self::new(PlmnId::from_bcd(&bytes[..3])?, eci))
}
#[must_use]
pub fn to_bytes(self) -> [u8; Self::OCTETS] {
let plmn = self.plmn().to_bcd();
let eci = self.eci().get().to_be_bytes();
[plmn[0], plmn[1], plmn[2], eci[0], eci[1], eci[2], eci[3]]
}
}
impl Ncgi {
pub const OCTETS: usize = 8;
pub fn from_bytes(bytes: &[u8]) -> Result<Self, DecodeError> {
if bytes.len() != Self::OCTETS {
return Err(DecodeError::new(0, "exactly 8 octets"));
}
let raw = u64::from(u32::from_be_bytes([bytes[3], bytes[4], bytes[5], bytes[6]])) << 8
| u64::from(bytes[7]);
let nci =
Nci::new(raw >> 4).ok_or_else(|| DecodeError::new(3, "a 36-bit NR cell identity"))?;
Ok(Self::new(PlmnId::from_bcd(&bytes[..3])?, nci))
}
#[must_use]
pub fn to_bytes(self) -> [u8; Self::OCTETS] {
let plmn = self.plmn().to_bcd();
let shifted = self.nci().get() << 4;
[
plmn[0],
plmn[1],
plmn[2],
(shifted >> 32) as u8,
(shifted >> 24) as u8,
(shifted >> 16) as u8,
(shifted >> 8) as u8,
shifted as u8,
]
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum UserLocation {
Cgi(Cgi),
Sai(Sai),
Ecgi(Ecgi),
Ncgi(Ncgi),
Tai(Tai),
Rai(Rai),
Lai(Lai),
}
impl UserLocation {
#[must_use]
pub const fn plmn(self) -> PlmnId {
match self {
Self::Cgi(v) => v.plmn(),
Self::Sai(v) => v.plmn(),
Self::Ecgi(v) => v.plmn(),
Self::Ncgi(v) => v.plmn(),
Self::Tai(v) => v.plmn(),
Self::Rai(v) => v.plmn(),
Self::Lai(v) => v.plmn(),
}
}
#[must_use]
pub const fn mcc(self) -> Mcc {
self.plmn().mcc()
}
#[must_use]
pub const fn is_cell(self) -> bool {
matches!(
self,
Self::Cgi(_) | Self::Sai(_) | Self::Ecgi(_) | Self::Ncgi(_)
)
}
#[must_use]
pub const fn kind(self) -> &'static str {
match self {
Self::Cgi(_) => "CGI",
Self::Sai(_) => "SAI",
Self::Ecgi(_) => "ECGI",
Self::Ncgi(_) => "NCGI",
Self::Tai(_) => "TAI",
Self::Rai(_) => "RAI",
Self::Lai(_) => "LAI",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct MacroEnbId {
plmn: PlmnId,
id: u32,
}
impl MacroEnbId {
pub const OCTETS: usize = 6;
pub const BITS: u32 = 20;
#[must_use]
pub const fn new(plmn: PlmnId, id: u32) -> Option<Self> {
if id < (1 << Self::BITS) {
Some(Self { plmn, id })
} else {
None
}
}
#[must_use]
pub const fn plmn(self) -> PlmnId {
self.plmn
}
#[must_use]
pub const fn get(self) -> u32 {
self.id
}
pub fn from_bytes(bytes: &[u8]) -> Result<Self, DecodeError> {
if bytes.len() != Self::OCTETS {
return Err(DecodeError::new(0, "exactly 6 octets"));
}
let id = u32::from_be_bytes([0, bytes[3], bytes[4], bytes[5]]) & 0x000F_FFFF;
Self::new(PlmnId::from_bcd(&bytes[..3])?, id)
.ok_or_else(|| DecodeError::new(3, "a 20-bit macro eNodeB identifier"))
}
#[must_use]
pub fn to_bytes(self) -> [u8; Self::OCTETS] {
let plmn = self.plmn.to_bcd();
[
plmn[0],
plmn[1],
plmn[2],
(self.id >> 16) as u8,
(self.id >> 8) as u8,
self.id as u8,
]
}
}
impl fmt::Display for MacroEnbId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}-{:05X}", self.plmn, self.id)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ExtendedEnbKind {
Long,
Short,
}
impl ExtendedEnbKind {
#[must_use]
pub const fn bits(self) -> u32 {
match self {
Self::Long => 21,
Self::Short => 18,
}
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Long => "LONG",
Self::Short => "SHORT",
}
}
}
impl fmt::Display for ExtendedEnbKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl ExtendedEnbKind {
pub const ALL: &'static [Self] = &[Self::Long, Self::Short];
pub const CODES: &'static [&'static str] = &["LONG", "SHORT"];
}
impl FromStr for ExtendedEnbKind {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::ALL
.iter()
.find(|k| k.as_str().eq_ignore_ascii_case(s.trim()))
.copied()
.ok_or_else(|| ParseError::one_of("ExtendedEnbKind", s, Self::CODES))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ExtendedMacroEnbId {
plmn: PlmnId,
kind: ExtendedEnbKind,
id: u32,
}
impl ExtendedMacroEnbId {
pub const OCTETS: usize = 6;
#[must_use]
pub const fn new(plmn: PlmnId, kind: ExtendedEnbKind, id: u32) -> Option<Self> {
if id < (1 << kind.bits()) {
Some(Self { plmn, kind, id })
} else {
None
}
}
#[must_use]
pub const fn plmn(self) -> PlmnId {
self.plmn
}
#[must_use]
pub const fn kind(self) -> ExtendedEnbKind {
self.kind
}
#[must_use]
pub const fn get(self) -> u32 {
self.id
}
pub fn from_bytes(bytes: &[u8]) -> Result<Self, DecodeError> {
if bytes.len() != Self::OCTETS {
return Err(DecodeError::new(0, "exactly 6 octets"));
}
let raw = u32::from_be_bytes([0, bytes[3], bytes[4], bytes[5]]);
let kind = if bytes[3] & 0x80 != 0 {
ExtendedEnbKind::Short
} else {
ExtendedEnbKind::Long
};
let id = raw & ((1 << kind.bits()) - 1);
Self::new(PlmnId::from_bcd(&bytes[..3])?, kind, id)
.ok_or_else(|| DecodeError::new(3, "an extended macro eNodeB identifier"))
}
#[must_use]
pub fn to_bytes(self) -> [u8; Self::OCTETS] {
let plmn = self.plmn.to_bcd();
let flag = match self.kind {
ExtendedEnbKind::Long => 0,
ExtendedEnbKind::Short => 0x0080_0000,
};
let packed = flag | self.id;
[
plmn[0],
plmn[1],
plmn[2],
(packed >> 16) as u8,
(packed >> 8) as u8,
packed as u8,
]
}
}
impl fmt::Display for ExtendedMacroEnbId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}-{}-{:06X}", self.plmn, self.kind, self.id)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Uli {
pub cgi: Option<Cgi>,
pub sai: Option<Sai>,
pub rai: Option<Rai>,
pub tai: Option<Tai>,
pub ecgi: Option<Ecgi>,
pub lai: Option<Lai>,
pub macro_enb: Option<MacroEnbId>,
pub extended_macro_enb: Option<ExtendedMacroEnbId>,
}
impl Uli {
const FLAG_CGI: u8 = 0x01;
const FLAG_SAI: u8 = 0x02;
const FLAG_RAI: u8 = 0x04;
const FLAG_TAI: u8 = 0x08;
const FLAG_ECGI: u8 = 0x10;
const FLAG_LAI: u8 = 0x20;
const FLAG_MACRO_ENB: u8 = 0x40;
const FLAG_EXT_MACRO_ENB: u8 = 0x80;
#[must_use]
pub const fn new() -> Self {
Self {
cgi: None,
sai: None,
rai: None,
tai: None,
ecgi: None,
lai: None,
macro_enb: None,
extended_macro_enb: None,
}
}
pub fn decode(bytes: &[u8]) -> Result<Self, DecodeError> {
let (flags, rest) = bytes
.split_first()
.ok_or_else(|| DecodeError::new(0, "a flag octet"))?;
let mut at = 1usize;
let mut uli = Self::new();
macro_rules! take {
($flag:expr, $len:expr, $what:literal) => {{
if flags & $flag == 0 {
None
} else {
let from = at - 1;
if rest.len() < from + $len {
return Err(DecodeError::new(at, $what));
}
at += $len;
Some(&rest[from..from + $len])
}
}};
}
if let Some(field) = take!(Self::FLAG_CGI, Cgi::OCTETS, "a 7-octet CGI") {
uli.cgi = Some(Cgi::from_bytes(field).map_err(|e| shift(e, at - Cgi::OCTETS))?);
}
if let Some(field) = take!(Self::FLAG_SAI, Sai::OCTETS, "a 7-octet SAI") {
uli.sai = Some(Sai::from_bytes(field).map_err(|e| shift(e, at - Sai::OCTETS))?);
}
if let Some(field) = take!(Self::FLAG_RAI, Rai::OCTETS, "a 7-octet RAI") {
uli.rai = Some(Rai::from_bytes(field).map_err(|e| shift(e, at - Rai::OCTETS))?);
}
if let Some(field) = take!(Self::FLAG_TAI, Tai::EPS_OCTETS, "a 5-octet TAI") {
uli.tai = Some(Tai::from_bytes(field).map_err(|e| shift(e, at - Tai::EPS_OCTETS))?);
}
if let Some(field) = take!(Self::FLAG_ECGI, Ecgi::OCTETS, "a 7-octet ECGI") {
uli.ecgi = Some(Ecgi::from_bytes(field).map_err(|e| shift(e, at - Ecgi::OCTETS))?);
}
if let Some(field) = take!(Self::FLAG_LAI, Lai::OCTETS, "a 5-octet LAI") {
uli.lai = Some(Lai::from_bytes(field).map_err(|e| shift(e, at - Lai::OCTETS))?);
}
if let Some(field) = take!(
Self::FLAG_MACRO_ENB,
MacroEnbId::OCTETS,
"a 6-octet macro eNodeB identifier"
) {
uli.macro_enb =
Some(MacroEnbId::from_bytes(field).map_err(|e| shift(e, at - MacroEnbId::OCTETS))?);
}
if let Some(field) = take!(
Self::FLAG_EXT_MACRO_ENB,
ExtendedMacroEnbId::OCTETS,
"a 6-octet extended macro eNodeB identifier"
) {
uli.extended_macro_enb = Some(
ExtendedMacroEnbId::from_bytes(field)
.map_err(|e| shift(e, at - ExtendedMacroEnbId::OCTETS))?,
);
}
Ok(uli)
}
#[must_use]
pub fn encoded_len(&self) -> usize {
1 + self.cgi.map_or(0, |_| Cgi::OCTETS)
+ self.sai.map_or(0, |_| Sai::OCTETS)
+ self.rai.map_or(0, |_| Rai::OCTETS)
+ self.tai.map_or(0, |_| Tai::EPS_OCTETS)
+ self.ecgi.map_or(0, |_| Ecgi::OCTETS)
+ self.lai.map_or(0, |_| Lai::OCTETS)
+ self.macro_enb.map_or(0, |_| MacroEnbId::OCTETS)
+ self
.extended_macro_enb
.map_or(0, |_| ExtendedMacroEnbId::OCTETS)
}
pub fn encode(&self, out: &mut [u8]) -> Result<usize, DecodeError> {
if let Some(tai) = self.tai
&& tai.tac().width() != TacWidth::Eps
{
return Err(DecodeError::new(
1,
"an EPS tracking area; the ULI element has no 5GS TAI field",
));
}
let needed = self.encoded_len();
if out.len() < needed {
return Err(DecodeError::new(0, "a buffer of encoded_len() octets"));
}
let mut flags = 0u8;
for (present, bit) in [
(self.cgi.is_some(), Self::FLAG_CGI),
(self.sai.is_some(), Self::FLAG_SAI),
(self.rai.is_some(), Self::FLAG_RAI),
(self.tai.is_some(), Self::FLAG_TAI),
(self.ecgi.is_some(), Self::FLAG_ECGI),
(self.lai.is_some(), Self::FLAG_LAI),
(self.macro_enb.is_some(), Self::FLAG_MACRO_ENB),
(self.extended_macro_enb.is_some(), Self::FLAG_EXT_MACRO_ENB),
] {
if present {
flags |= bit;
}
}
out[0] = flags;
let mut at = 1usize;
macro_rules! put {
($value:expr) => {
if let Some(value) = $value {
let encoded = value.to_bytes();
out[at..at + encoded.len()].copy_from_slice(&encoded);
at += encoded.len();
}
};
}
put!(self.cgi);
put!(self.sai);
put!(self.rai);
if let Some(tai) = self.tai {
at += tai.to_bytes(&mut out[at..])?;
}
put!(self.ecgi);
put!(self.lai);
put!(self.macro_enb);
put!(self.extended_macro_enb);
Ok(at)
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.cgi.is_none()
&& self.sai.is_none()
&& self.rai.is_none()
&& self.tai.is_none()
&& self.ecgi.is_none()
&& self.lai.is_none()
&& self.macro_enb.is_none()
&& self.extended_macro_enb.is_none()
}
#[must_use]
pub fn most_precise(&self) -> Option<UserLocation> {
if let Some(v) = self.ecgi {
return Some(UserLocation::Ecgi(v));
}
if let Some(v) = self.cgi {
return Some(UserLocation::Cgi(v));
}
if let Some(v) = self.sai {
return Some(UserLocation::Sai(v));
}
if let Some(v) = self.tai {
return Some(UserLocation::Tai(v));
}
if let Some(v) = self.rai {
return Some(UserLocation::Rai(v));
}
self.lai.map(UserLocation::Lai)
}
pub fn mcc(&self) -> Result<Option<Mcc>, UliCountryConflict> {
let mut found: Option<Mcc> = None;
for plmn in [
self.cgi.map(Cgi::plmn),
self.sai.map(Sai::plmn),
self.rai.map(Rai::plmn),
self.tai.map(Tai::plmn),
self.ecgi.map(Ecgi::plmn),
self.lai.map(Lai::plmn),
self.macro_enb.map(MacroEnbId::plmn),
self.extended_macro_enb.map(ExtendedMacroEnbId::plmn),
]
.into_iter()
.flatten()
{
match found {
None => found = Some(plmn.mcc()),
Some(seen) if !seen.same_country(plmn.mcc()) => {
return Err(UliCountryConflict {
first: seen,
second: plmn.mcc(),
});
}
Some(_) => {}
}
}
Ok(found)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct UliCountryConflict {
pub first: Mcc,
pub second: Mcc,
}
impl fmt::Display for UliCountryConflict {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"the element names both {} and {}",
self.first, self.second
)
}
}
impl std::error::Error for UliCountryConflict {}
fn shift(error: DecodeError, by: usize) -> DecodeError {
DecodeError::new(error.at() + by, error.expected())
}
impl fmt::Display for UserLocation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Cgi(v) => write!(f, "cgi:{v}"),
Self::Sai(v) => write!(f, "sai:{v}"),
Self::Ecgi(v) => write!(f, "ecgi:{v}"),
Self::Ncgi(v) => write!(f, "ncgi:{v}"),
Self::Tai(v) => write!(f, "tai:{v}"),
Self::Rai(v) => write!(f, "rai:{v}"),
Self::Lai(v) => write!(f, "lai:{v}"),
}
}
}
#[cfg(feature = "serde")]
mod serde_impl {
use super::{
CellId, Cgi, Ecgi, Eci, EnbKind, ExtendedEnbKind, ExtendedMacroEnbId, GnbIdLength, Lac,
Lai, MacroEnbId, Ncgi, Nci, Rai, RoutingAreaCode, Sai, ServiceAreaCode, TacWidth, Tai,
TrackingAreaCode, Uli, UserLocation,
};
use crate::plmn::PlmnId;
use serde::de::{self, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
macro_rules! string_enum {
($t:ty, $expecting:literal) => {
impl Serialize for $t {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(self.as_str())
}
}
impl<'de> Deserialize<'de> for $t {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
struct V;
impl Visitor<'_> for V {
type Value = $t;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str($expecting)
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<$t, E> {
v.parse().map_err(de::Error::custom)
}
}
d.deserialize_str(V)
}
}
};
}
string_enum!(EnbKind, "MACRO or HOME");
string_enum!(TacWidth, "EPS or 5GS");
macro_rules! checked_number {
($t:ty, $raw:ty, $ctor:expr, $expecting:literal) => {
impl Serialize for $t {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
self.get().serialize(s)
}
}
impl<'de> Deserialize<'de> for $t {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let raw = <$raw>::deserialize(d)?;
#[allow(clippy::redundant_closure_call)]
($ctor)(raw)
.ok_or_else(|| de::Error::custom(format!("{raw} is not {}", $expecting)))
}
}
};
}
checked_number!(
Lac,
u16,
Lac::new,
"a location area code (0000 and FFFE are reserved)"
);
checked_number!(Eci, u32, Eci::new, "a 28-bit E-UTRAN cell identity");
checked_number!(Nci, u64, Nci::new, "a 36-bit NR cell identity");
checked_number!(
GnbIdLength,
u8,
GnbIdLength::new,
"a gNB-ID length of 22 to 32 bits"
);
macro_rules! plain_number {
($t:ty, $raw:ty, $ctor:expr) => {
impl Serialize for $t {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
self.get().serialize(s)
}
}
impl<'de> Deserialize<'de> for $t {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
#[allow(clippy::redundant_closure_call)]
Ok(($ctor)(<$raw>::deserialize(d)?))
}
}
};
}
plain_number!(CellId, u16, CellId::new);
plain_number!(ServiceAreaCode, u16, ServiceAreaCode::new);
plain_number!(RoutingAreaCode, u8, RoutingAreaCode::new);
#[derive(Serialize, Deserialize)]
#[serde(rename = "TrackingAreaCode")]
struct TacRepr {
value: u32,
width: TacWidth,
}
impl Serialize for TrackingAreaCode {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
TacRepr {
value: self.get(),
width: self.width(),
}
.serialize(s)
}
}
impl<'de> Deserialize<'de> for TrackingAreaCode {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let r = TacRepr::deserialize(d)?;
let built = match r.width {
TacWidth::Eps => u16::try_from(r.value).ok().and_then(TrackingAreaCode::eps),
TacWidth::FiveGs => TrackingAreaCode::five_gs(r.value),
};
built.ok_or_else(|| {
de::Error::custom(format!(
"{} is not a valid {} tracking area code",
r.value, r.width
))
})
}
}
macro_rules! composite {
($t:ty, $name:literal, { $($field:ident : $ty:ty),+ $(,)? }) => {
#[derive(Serialize, Deserialize)]
#[serde(rename = $name)]
struct Repr {
$($field: $ty),+
}
impl Serialize for $t {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
Repr { $($field: self.$field()),+ }.serialize(s)
}
}
impl<'de> Deserialize<'de> for $t {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let r = Repr::deserialize(d)?;
Ok(<$t>::new($(r.$field),+))
}
}
};
}
mod cgi {
use super::*;
composite!(Cgi, "Cgi", { plmn: PlmnId, lac: Lac, cell: CellId });
}
mod sai {
use super::*;
composite!(Sai, "Sai", { plmn: PlmnId, lac: Lac, sac: ServiceAreaCode });
}
mod ecgi {
use super::*;
composite!(Ecgi, "Ecgi", { plmn: PlmnId, eci: Eci });
}
mod ncgi {
use super::*;
composite!(Ncgi, "Ncgi", { plmn: PlmnId, nci: Nci });
}
mod tai {
use super::*;
composite!(Tai, "Tai", { plmn: PlmnId, tac: TrackingAreaCode });
}
mod lai {
use super::*;
composite!(Lai, "Lai", { plmn: PlmnId, lac: Lac });
}
mod rai {
use super::*;
composite!(Rai, "Rai", { plmn: PlmnId, lac: Lac, rac: RoutingAreaCode });
}
mod macro_enb {
use super::*;
#[derive(Serialize, Deserialize)]
#[serde(rename = "MacroEnbId")]
struct Repr {
plmn: PlmnId,
id: u32,
}
impl Serialize for MacroEnbId {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
Repr {
plmn: self.plmn(),
id: self.get(),
}
.serialize(s)
}
}
impl<'de> Deserialize<'de> for MacroEnbId {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let r = Repr::deserialize(d)?;
MacroEnbId::new(r.plmn, r.id).ok_or_else(|| {
de::Error::custom(format!("{} is not a 20-bit macro eNodeB id", r.id))
})
}
}
}
mod ext_macro_enb {
use super::*;
#[derive(Serialize, Deserialize)]
#[serde(rename = "ExtendedMacroEnbId")]
struct Repr {
plmn: PlmnId,
kind: ExtendedEnbKind,
id: u32,
}
impl Serialize for ExtendedMacroEnbId {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
Repr {
plmn: self.plmn(),
kind: self.kind(),
id: self.get(),
}
.serialize(s)
}
}
impl<'de> Deserialize<'de> for ExtendedMacroEnbId {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let r = Repr::deserialize(d)?;
ExtendedMacroEnbId::new(r.plmn, r.kind, r.id).ok_or_else(|| {
de::Error::custom(format!("{} does not fit a {} identifier", r.id, r.kind))
})
}
}
}
mod uli {
use super::*;
#[derive(Serialize, Deserialize, Default)]
#[serde(rename = "Uli", default)]
struct Repr {
cgi: Option<Cgi>,
sai: Option<Sai>,
rai: Option<Rai>,
tai: Option<Tai>,
ecgi: Option<Ecgi>,
lai: Option<Lai>,
macro_enb: Option<MacroEnbId>,
extended_macro_enb: Option<ExtendedMacroEnbId>,
}
impl Serialize for Uli {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
Repr {
cgi: self.cgi,
sai: self.sai,
rai: self.rai,
tai: self.tai,
ecgi: self.ecgi,
lai: self.lai,
macro_enb: self.macro_enb,
extended_macro_enb: self.extended_macro_enb,
}
.serialize(s)
}
}
impl<'de> Deserialize<'de> for Uli {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let r = Repr::deserialize(d)?;
Ok(Uli {
cgi: r.cgi,
sai: r.sai,
rai: r.rai,
tai: r.tai,
ecgi: r.ecgi,
lai: r.lai,
macro_enb: r.macro_enb,
extended_macro_enb: r.extended_macro_enb,
})
}
}
}
string_enum!(ExtendedEnbKind, "LONG or SHORT");
#[derive(Serialize, Deserialize)]
#[serde(tag = "kind", rename = "UserLocation")]
enum LocationRepr {
#[serde(rename = "CGI")]
Cgi(Cgi),
#[serde(rename = "SAI")]
Sai(Sai),
#[serde(rename = "ECGI")]
Ecgi(Ecgi),
#[serde(rename = "NCGI")]
Ncgi(Ncgi),
#[serde(rename = "TAI")]
Tai(Tai),
#[serde(rename = "RAI")]
Rai(Rai),
#[serde(rename = "LAI")]
Lai(Lai),
}
impl Serialize for UserLocation {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
match *self {
UserLocation::Cgi(v) => LocationRepr::Cgi(v),
UserLocation::Sai(v) => LocationRepr::Sai(v),
UserLocation::Ecgi(v) => LocationRepr::Ecgi(v),
UserLocation::Ncgi(v) => LocationRepr::Ncgi(v),
UserLocation::Tai(v) => LocationRepr::Tai(v),
UserLocation::Rai(v) => LocationRepr::Rai(v),
UserLocation::Lai(v) => LocationRepr::Lai(v),
}
.serialize(s)
}
}
impl<'de> Deserialize<'de> for UserLocation {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
Ok(match LocationRepr::deserialize(d)? {
LocationRepr::Cgi(v) => UserLocation::Cgi(v),
LocationRepr::Sai(v) => UserLocation::Sai(v),
LocationRepr::Ecgi(v) => UserLocation::Ecgi(v),
LocationRepr::Ncgi(v) => UserLocation::Ncgi(v),
LocationRepr::Tai(v) => UserLocation::Tai(v),
LocationRepr::Rai(v) => UserLocation::Rai(v),
LocationRepr::Lai(v) => UserLocation::Lai(v),
})
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn plmn() -> PlmnId {
"262-02".parse().expect("a valid network")
}
#[test]
fn the_two_reserved_location_areas_are_rejected() {
assert!(Lac::new(0x0000).is_none());
assert!(Lac::new(0xFFFE).is_none());
assert!(Lac::new(0x0001).is_some());
assert!(Lac::new(0xFFFF).is_some(), "only the two are reserved");
assert!(Lac::is_reserved(0xFFFE));
assert!(!Lac::is_reserved(0xFFFF));
assert_eq!(
(0u32..=0xFFFF)
.filter(|v| super::is_reserved_area(*v, 16))
.count(),
2
);
assert!(super::is_reserved_area(0x00FF_FFFE, 24));
assert!(!super::is_reserved_area(0x0000_FFFE, 24));
assert_eq!(Lac::new(0x00AB).unwrap().to_string(), "00AB");
}
#[test]
fn the_same_two_values_are_reserved_for_tracking_areas() {
assert!(TrackingAreaCode::eps(0x0000).is_none());
assert!(TrackingAreaCode::eps(0xFFFE).is_none());
assert!(TrackingAreaCode::five_gs(0x00_0000).is_none());
assert!(TrackingAreaCode::five_gs(0xFF_FFFE).is_none());
assert!(TrackingAreaCode::five_gs(0x01_0000).is_some());
assert!(
TrackingAreaCode::five_gs(0x0100_0000).is_none(),
"more than 24 bits"
);
}
#[test]
fn a_cell_identity_splits_differently_for_a_home_enodeb() {
let eci = Eci::new(0x00A1_B2C3).unwrap();
assert_eq!(eci.enb_id(EnbKind::Macro), 0x0000_A1B2);
assert_eq!(eci.cell_id(EnbKind::Macro), Some(0xC3));
assert_eq!(eci.enb_id(EnbKind::Home), 0x00A1_B2C3);
assert_eq!(
eci.cell_id(EnbKind::Home),
None,
"a 28-bit home identifier leaves no cell part"
);
assert_eq!(EnbKind::Macro.id_bits() + 8, EnbKind::Home.id_bits());
}
#[test]
fn an_nr_cell_identity_needs_the_configured_length() {
let nci = Nci::new(0x0_1234_5678).unwrap();
let short = GnbIdLength::new(22).unwrap();
let long = GnbIdLength::new(32).unwrap();
assert_eq!(short.cell_bits(), 14);
assert_eq!(long.cell_bits(), 4);
assert_ne!(nci.gnb_id(short), nci.gnb_id(long));
for bits in GnbIdLength::MIN..=GnbIdLength::MAX {
let length = GnbIdLength::new(bits).unwrap();
let rebuilt = (nci.gnb_id(length) << length.cell_bits()) | nci.cell_id(length);
assert_eq!(rebuilt, nci.get(), "at {bits} bits");
}
}
#[test]
fn identities_are_bounded_by_their_bit_widths() {
assert!(Eci::new((1 << 28) - 1).is_some());
assert!(Eci::new(1 << 28).is_none());
assert!(Nci::new((1 << 36) - 1).is_some());
assert!(Nci::new(1 << 36).is_none());
assert!(GnbIdLength::new(21).is_none());
assert!(GnbIdLength::new(33).is_none());
assert_eq!(GnbIdLength::new(22).unwrap().get(), 22);
}
#[test]
fn a_tracking_area_carries_the_width_it_was_written_at() {
let eps = TrackingAreaCode::eps(0x1234).unwrap();
let five_gs = TrackingAreaCode::five_gs(0x00_1234).unwrap();
assert_ne!(eps, five_gs, "different widths are different values");
assert_eq!(eps.widened(), five_gs, "and this is the way across");
assert!(eps.is_same_area(five_gs));
assert_eq!(eps.to_string(), "1234");
assert_eq!(five_gs.to_string(), "001234");
assert_eq!(eps.width(), TacWidth::Eps);
assert_eq!(TacWidth::Eps.bits() + 8, TacWidth::FiveGs.bits());
}
#[test]
fn every_location_form_yields_a_country() {
let lac = Lac::new(0x1234).unwrap();
let forms = [
UserLocation::Cgi(Cgi::new(plmn(), lac, CellId::new(0xABCD))),
UserLocation::Sai(Sai::new(plmn(), lac, ServiceAreaCode::new(0xABCD))),
UserLocation::Ecgi(Ecgi::new(plmn(), Eci::new(0x0012_3456).unwrap())),
UserLocation::Ncgi(Ncgi::new(plmn(), Nci::new(0x0_1234_5678).unwrap())),
UserLocation::Tai(Tai::new(
plmn(),
TrackingAreaCode::five_gs(0x00_1234).unwrap(),
)),
];
for form in forms {
assert_eq!(form.mcc(), plmn().mcc());
assert_eq!(form.plmn(), plmn());
}
assert!(forms[0].is_cell());
assert!(!forms[4].is_cell());
}
#[test]
fn the_forms_are_distinguishable_as_strings() {
let lac = Lac::new(0x1234).unwrap();
let cgi = UserLocation::Cgi(Cgi::new(plmn(), lac, CellId::new(0xABCD)));
let sai = UserLocation::Sai(Sai::new(plmn(), lac, ServiceAreaCode::new(0xABCD)));
assert_ne!(cgi.to_string(), sai.to_string());
assert_eq!(cgi.to_string(), "cgi:262-02-1234-ABCD");
assert_eq!(sai.to_string(), "sai:262-02-1234-ABCD");
assert_eq!(cgi.kind(), "CGI");
}
#[test]
fn identities_render_at_their_full_width() {
assert_eq!(Eci::new(0x1).unwrap().to_string(), "0000001");
assert_eq!(Nci::new(0x1).unwrap().to_string(), "000000001");
assert_eq!(CellId::new(0x1).to_string(), "0001");
assert_eq!(ServiceAreaCode::new(0x1).to_string(), "0001");
}
#[test]
fn vocabulary_codes_round_trip() {
for (kind, code) in EnbKind::ALL.iter().zip(EnbKind::CODES) {
assert_eq!(kind.as_str(), *code);
assert_eq!(code.parse::<EnbKind>().unwrap(), *kind);
}
for (width, code) in TacWidth::ALL.iter().zip(TacWidth::CODES) {
assert_eq!(width.as_str(), *code);
assert_eq!(code.parse::<TacWidth>().unwrap(), *width);
}
assert_eq!("24".parse::<GnbIdLength>().unwrap().get(), 24);
assert!("21".parse::<GnbIdLength>().is_err());
assert!("LTE".parse::<TacWidth>().is_err());
}
}