use std::fmt::Write as _;
use std::ops::Deref;
use rustorb_core::giop::{Corbaloc, ObjAddr};
use rustorb_core::name::{self, Name, NameComponent};
use rustorb_core::{ObjectRef, SystemException};
use crate::NamingError;
use crate::idl::cos_naming as idl;
use crate::repository_id::{NAMING_CONTEXT, NAMING_CONTEXT_EXT};
pub(crate) fn to_idl_name(n: &[NameComponent]) -> idl::Name {
n.iter()
.map(|c| idl::NameComponent {
id: c.id.clone(),
kind: c.kind.clone(),
})
.collect()
}
pub(crate) fn from_idl_name(n: idl::Name) -> Name {
n.into_iter()
.map(|c| NameComponent {
id: c.id,
kind: c.kind,
})
.collect()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BindingType {
Object,
Context,
}
impl BindingType {
pub fn name(self) -> &'static str {
match self {
BindingType::Object => "nobject",
BindingType::Context => "ncontext",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Binding {
pub binding_name: Name,
pub binding_type: BindingType,
}
impl From<idl::Binding> for Binding {
fn from(b: idl::Binding) -> Binding {
Binding {
binding_name: from_idl_name(b.binding_name),
binding_type: match b.binding_type {
idl::BindingType::Nobject => BindingType::Object,
idl::BindingType::Ncontext => BindingType::Context,
},
}
}
}
impl From<&Binding> for idl::Binding {
fn from(b: &Binding) -> idl::Binding {
idl::Binding {
binding_name: to_idl_name(&b.binding_name),
binding_type: match b.binding_type {
BindingType::Object => idl::BindingType::Nobject,
BindingType::Context => idl::BindingType::Ncontext,
},
}
}
}
fn bindings(list: idl::BindingList) -> Vec<Binding> {
list.into_iter().map(Binding::from).collect()
}
fn supports(obj: &ObjectRef, repository_id: &str, also: &[&str]) -> Result<bool, SystemException> {
if also.contains(&obj.type_id()) {
return Ok(true);
}
rustorb_core::idl::is_a(obj, repository_id)
}
fn context(nc: Option<idl::NamingContext>) -> Result<NamingContext, NamingError> {
let nc = nc.ok_or_else(|| {
SystemException::new(
rustorb_core::SystemExceptionKind::MARSHAL,
0,
rustorb_core::CompletionStatus::Yes,
)
})?;
Ok(NamingContext::unchecked_narrow(nc.into_object()))
}
#[derive(Debug, Clone)]
pub struct NamingContext {
stub: idl::NamingContext,
}
impl NamingContext {
pub fn narrow(obj: ObjectRef) -> Result<Option<NamingContext>, SystemException> {
Ok(supports(&obj, NAMING_CONTEXT, &[NAMING_CONTEXT_EXT])?
.then(|| NamingContext::unchecked_narrow(obj)))
}
pub fn unchecked_narrow(obj: ObjectRef) -> NamingContext {
NamingContext {
stub: idl::NamingContext::unchecked_narrow(obj),
}
}
pub fn object(&self) -> &ObjectRef {
self.stub.object()
}
pub fn into_object(self) -> ObjectRef {
self.stub.into_object()
}
pub fn stub(&self) -> &idl::NamingContext {
&self.stub
}
pub fn bind(&self, n: &[NameComponent], obj: &ObjectRef) -> Result<(), NamingError> {
Ok(self.stub.bind(&to_idl_name(n), Some(obj))?)
}
pub fn rebind(&self, n: &[NameComponent], obj: &ObjectRef) -> Result<(), NamingError> {
Ok(self.stub.rebind(&to_idl_name(n), Some(obj))?)
}
pub fn bind_context(&self, n: &[NameComponent], nc: &NamingContext) -> Result<(), NamingError> {
Ok(self.stub.bind_context(&to_idl_name(n), Some(&nc.stub))?)
}
pub fn rebind_context(
&self,
n: &[NameComponent],
nc: &NamingContext,
) -> Result<(), NamingError> {
Ok(self.stub.rebind_context(&to_idl_name(n), Some(&nc.stub))?)
}
pub fn resolve(&self, n: &[NameComponent]) -> Result<Option<ObjectRef>, NamingError> {
Ok(self.stub.resolve(&to_idl_name(n))?)
}
pub fn unbind(&self, n: &[NameComponent]) -> Result<(), NamingError> {
Ok(self.stub.unbind(&to_idl_name(n))?)
}
pub fn new_context(&self) -> Result<NamingContext, NamingError> {
context(self.stub.new_context()?)
}
pub fn bind_new_context(&self, n: &[NameComponent]) -> Result<NamingContext, NamingError> {
context(self.stub.bind_new_context(&to_idl_name(n))?)
}
pub fn destroy(&self) -> Result<(), NamingError> {
Ok(self.stub.destroy()?)
}
pub fn list(
&self,
how_many: u32,
) -> Result<(Vec<Binding>, Option<BindingIterator>), NamingError> {
let (list, iterator) = self.stub.list(how_many)?;
Ok((
bindings(list),
iterator.map(|stub| BindingIterator { stub }),
))
}
}
#[derive(Debug, Clone)]
pub struct NamingContextExt {
ctx: NamingContext,
stub: idl::NamingContextExt,
}
impl NamingContextExt {
pub fn narrow(obj: ObjectRef) -> Result<Option<NamingContextExt>, SystemException> {
Ok(supports(&obj, NAMING_CONTEXT_EXT, &[])?
.then(|| NamingContextExt::unchecked_narrow(obj)))
}
pub fn unchecked_narrow(obj: ObjectRef) -> NamingContextExt {
NamingContextExt {
ctx: NamingContext::unchecked_narrow(obj.clone()),
stub: idl::NamingContextExt::unchecked_narrow(obj),
}
}
pub fn context(&self) -> &NamingContext {
&self.ctx
}
pub fn stub(&self) -> &idl::NamingContextExt {
&self.stub
}
pub fn to_string(&self, n: &[NameComponent]) -> Result<String, NamingError> {
Ok(self.stub.to_string(&to_idl_name(n))?)
}
pub fn to_name(&self, sn: &str) -> Result<Name, NamingError> {
Ok(from_idl_name(self.stub.to_name(sn)?))
}
pub fn to_url(&self, addr: &str, sn: &str) -> Result<String, NamingError> {
Ok(self.stub.to_url(addr, sn)?)
}
pub fn resolve_str(&self, sn: &str) -> Result<Option<ObjectRef>, NamingError> {
Ok(self.stub.resolve_str(sn)?)
}
}
impl Deref for NamingContextExt {
type Target = NamingContext;
fn deref(&self) -> &NamingContext {
&self.ctx
}
}
impl From<NamingContextExt> for NamingContext {
fn from(ext: NamingContextExt) -> NamingContext {
ext.ctx
}
}
#[derive(Debug, Clone)]
pub struct BindingIterator {
stub: idl::BindingIterator,
}
impl BindingIterator {
pub fn narrow(obj: ObjectRef) -> Result<Option<BindingIterator>, SystemException> {
Ok(idl::BindingIterator::narrow(&obj)?.map(|stub| BindingIterator { stub }))
}
pub fn object(&self) -> &ObjectRef {
self.stub.object()
}
pub fn next_one(&self) -> Result<Option<Binding>, NamingError> {
let (more, binding) = self.stub.next_one()?;
Ok(more.then(|| binding.into()))
}
pub fn next_n(&self, how_many: u32) -> Result<(bool, Vec<Binding>), NamingError> {
let (more, list) = self.stub.next_n(how_many)?;
Ok((more, bindings(list)))
}
pub fn destroy(&self) -> Result<(), NamingError> {
Ok(self.stub.destroy()?)
}
}
pub fn to_url(addr: &str, sn: &str) -> Result<String, NamingError> {
let valid = !addr.contains(['/', '#'])
&& Corbaloc::parse(&format!("corbaloc:{addr}/x")).is_ok_and(|loc| {
loc.addresses
.iter()
.all(|a| !matches!(a, ObjAddr::Other { .. }))
});
if !valid {
return Err(NamingError::InvalidAddress);
}
if sn.is_empty() {
return Ok(format!("corbaname:{addr}"));
}
name::to_name(sn)?;
let mut url = format!("corbaname:{addr}#");
for b in sn.bytes() {
if b.is_ascii_alphanumeric() || b";/:?@&=+$,-_.!~*'()".contains(&b) {
url.push(b as char);
} else {
let _ = write!(url, "%{b:02X}");
}
}
Ok(url)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn to_url_escapes_the_name() {
assert_eq!(
to_url(":host:2809", "a/b c").unwrap(),
"corbaname::host:2809#a/b%20c"
);
assert_eq!(
to_url("iiop:1.2@host,:other", "x.y/z\\/w").unwrap(),
"corbaname:iiop:1.2@host,:other#x.y/z%5C/w"
);
assert_eq!(to_url("rir:", "a").unwrap(), "corbaname:rir:#a");
assert_eq!(to_url(":host", "").unwrap(), "corbaname::host");
}
#[test]
fn to_url_checks_address_and_name() {
for addr in ["host:2809", "", "iiop:host/x", ":host#a"] {
assert!(
matches!(to_url(addr, "a"), Err(NamingError::InvalidAddress)),
"{addr:?}"
);
}
assert!(matches!(
to_url(":host", "a//b"),
Err(NamingError::InvalidName)
));
}
}