use parking_lot::RwLock;
use std::sync::LazyLock;
use std::{fmt, sync::Arc};
use crate::core::util::close::CloseableRef;
use crate::core::util::error::lucene_error::Result;
pub trait InfoStream: Send + Sync + CloseableRef {
fn message(&self, component: &str, message: &str) -> Result<()>;
fn is_enabled(&self, component: &str) -> bool;
}
impl<T> InfoStream for Arc<T>
where
T: InfoStream + ?Sized,
{
fn message(&self, component: &str, message: &str) -> Result<()> {
self.as_ref().message(component, message)
}
fn is_enabled(&self, component: &str) -> bool {
self.as_ref().is_enabled(component)
}
}
pub(crate) static NO_OUTPUT_INFO_STREAM: LazyLock<InfoStreamMT> =
LazyLock::new(|| Arc::new(InfoStreamEnum::NoOutput(NoOutput)));
static DEFAULT_INFO_STREAM: LazyLock<RwLock<InfoStreamMT>> =
LazyLock::new(|| RwLock::new(Arc::clone(&NO_OUTPUT_INFO_STREAM)));
#[derive(Clone, Debug, Default)]
pub struct NoOutput;
impl CloseableRef for NoOutput {
fn close(&self) -> Result<()> {
Ok(())
}
}
impl InfoStream for NoOutput {
fn message(&self, _component: &str, _message: &str) -> Result<()> {
debug_assert!(
false,
"this method should never be called when is_enabled returns false"
);
Ok(())
}
fn is_enabled(&self, _component: &str) -> bool {
false
}
}
pub fn get_default_info_stream() -> Arc<InfoStreamEnum> {
DEFAULT_INFO_STREAM.read().clone()
}
pub fn set_default<T>(info_stream: T)
where
T: Into<InfoStreamMT>,
{
let info_stream = info_stream.into();
let previous = std::mem::replace(&mut *DEFAULT_INFO_STREAM.write(), info_stream);
drop(previous);
}
pub enum InfoStreamEnum {
NoOutput(NoOutput),
Custom(Box<dyn InfoStream>),
}
impl fmt::Debug for InfoStreamEnum {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
InfoStreamEnum::NoOutput(output) => f.debug_tuple("NoOutput").field(output).finish(),
InfoStreamEnum::Custom(_) => f.write_str("CustomInfoStream"),
}
}
}
impl Default for InfoStreamEnum {
fn default() -> Self {
InfoStreamEnum::NoOutput(NoOutput)
}
}
impl CloseableRef for InfoStreamEnum {
fn close(&self) -> Result<()> {
match self {
InfoStreamEnum::NoOutput(output) => output.close(),
InfoStreamEnum::Custom(output) => CloseableRef::close(output.as_ref()),
}
}
}
impl InfoStream for InfoStreamEnum {
fn message(&self, component: &str, message: &str) -> Result<()> {
match self {
InfoStreamEnum::NoOutput(output) => output.message(component, message),
InfoStreamEnum::Custom(output) => output.message(component, message),
}
}
fn is_enabled(&self, component: &str) -> bool {
match self {
InfoStreamEnum::NoOutput(output) => output.is_enabled(component),
InfoStreamEnum::Custom(output) => output.is_enabled(component),
}
}
}
pub type InfoStreamMT = Arc<InfoStreamEnum>;