use std::sync::LazyLock;
use crate::core::store::ReadAdvice;
use crate::core::store::flush_info::FlushInfo;
use crate::core::store::merge_info::MergeInfo;
use crate::core::util::error::lucene_error::{LuceneError, Result};
pub static IO_CONTEXT_DEFAULT: LazyLock<Result<IOContext>> =
LazyLock::new(|| IOContext::with_read_advice(ReadAdvice::default_read_advice()?));
pub static IO_CONTEXT_READ_ONCE: LazyLock<IOContext> = LazyLock::new(|| {
expect_invariant!(
IOContext::read_once_io_context(),
"a default context with fixed sequential read advice is valid",
)
});
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct IOContext {
context: Context,
read_advice: ReadAdvice,
merge_info: Option<MergeInfo>,
flush_info: Option<FlushInfo>,
}
impl IOContext {
pub fn new(
context: Option<Context>,
read_advice: Option<ReadAdvice>,
merge_info: Option<MergeInfo>,
flush_info: Option<FlushInfo>,
) -> Result<IOContext> {
let context = context
.ok_or_else(|| LuceneError::illegal_argument("context must not be None".to_string()))?;
let read_advice = read_advice
.ok_or_else(|| LuceneError::illegal_argument("read_advice must not be None".to_string()))?;
if matches!(context, Context::Merge) && merge_info.is_none() {
return Err(LuceneError::illegal_argument(
"merge_info must not be None if context is MERGE".to_string(),
));
}
if matches!(context, Context::Flush) && flush_info.is_none() {
return Err(LuceneError::illegal_argument(
"flush_info must not be None if context is FLUSH".to_string(),
));
}
if (matches!(context, Context::Flush) || matches!(context, Context::Merge))
&& !matches!(read_advice, ReadAdvice::Sequential)
{
return Err(LuceneError::illegal_argument(
"The FLUSH and MERGE contexts must use the SEQUENTIAL read access advice".to_string(),
));
}
Ok(Self {
context,
read_advice,
merge_info,
flush_info,
})
}
pub fn get_context(&self) -> &Context {
&self.context
}
pub fn get_read_advice(&self) -> &ReadAdvice {
&self.read_advice
}
pub fn get_merge_info(&self) -> &Option<MergeInfo> {
&self.merge_info
}
pub fn get_flush_info(&self) -> &Option<FlushInfo> {
&self.flush_info
}
pub fn with_read_advice(read_advice: ReadAdvice) -> Result<IOContext> {
Self::new(Some(Context::Default), Some(read_advice), None, None)
}
pub fn with_flush(flush_info: FlushInfo) -> Result<IOContext> {
Self::new(
Some(Context::Flush),
Some(ReadAdvice::Sequential),
None,
Some(flush_info),
)
}
pub fn with_merge(merge_info: MergeInfo) -> Result<IOContext> {
Self::new(
Some(Context::Merge),
Some(ReadAdvice::Sequential),
Some(merge_info),
None,
)
}
pub fn with_read_advice_self(&self, read_advice: ReadAdvice) -> Result<IOContext> {
if matches!(self.context, Context::Default) {
Self::with_read_advice(read_advice)
} else {
Ok(self.clone())
}
}
pub fn read_once_io_context() -> Result<IOContext> {
Self::with_read_advice(ReadAdvice::Sequential)
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Context {
Merge,
Flush,
Default,
}