Skip to content

Commit 060041c

Browse files
committed
refactor: Generalize usize config validation
Signed-off-by: subhramit <[email protected]>
1 parent f6314d1 commit 060041c

1 file changed

Lines changed: 106 additions & 13 deletions

File tree

‎datafusion/common/src/config.rs‎

Lines changed: 106 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ use arrow_ipc::CompressionType;
2121

2222
#[cfg(feature = "parquet_encryption")]
2323
use crate::encryption::{FileDecryptionProperties, FileEncryptionProperties};
24-
use crate::error::{_config_datafusion_err, _config_err};
24+
use crate::error::_config_err;
2525
use crate::format::{ExplainAnalyzeCategories, ExplainFormat, MetricType};
2626
use crate::parquet_config::DFParquetWriterVersion;
2727
use crate::parsers::{CompressionTypeVariant, CsvQuoteStyle};
@@ -33,7 +33,6 @@ use std::any::Any;
3333
use std::collections::{BTreeMap, HashMap};
3434
use std::error::Error;
3535
use std::fmt::{self, Display};
36-
use std::num::NonZeroUsize;
3736
use std::str::FromStr;
3837
#[cfg(feature = "parquet_encryption")]
3938
use std::sync::Arc;
@@ -583,29 +582,123 @@ impl Display for SpillCompression {
583582
}
584583
}
585584

585+
/// A reusable bounded `usize` configuration value.
586+
///
587+
/// This stores the configured value together with its inclusive lower bound and
588+
/// optional inclusive upper bound so wrapper types such as
589+
/// [`ConfigNonZeroUsize`] and [`ConfigMinTwoUsize`] can share the same range
590+
/// validation logic.
591+
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
592+
pub struct ConfigRangeUsize {
593+
value: usize,
594+
inclusive_min: usize,
595+
/// `None` if there is no maximum limit.
596+
inclusive_max: Option<usize>,
597+
}
598+
599+
impl ConfigRangeUsize {
600+
const fn in_range(
601+
value: usize,
602+
inclusive_min: usize,
603+
inclusive_max: Option<usize>,
604+
) -> bool {
605+
if value < inclusive_min {
606+
return false;
607+
}
608+
609+
match inclusive_max {
610+
Some(inclusive_max) => value <= inclusive_max,
611+
None => true,
612+
}
613+
}
614+
615+
const fn new_for_default(
616+
value: usize,
617+
inclusive_min: usize,
618+
inclusive_max: Option<usize>,
619+
) -> Self {
620+
if Self::in_range(value, inclusive_min, inclusive_max) {
621+
Self {
622+
value,
623+
inclusive_min,
624+
inclusive_max,
625+
}
626+
} else {
627+
panic!("value out of allowed range")
628+
}
629+
}
630+
631+
/// Creates a [`ConfigRangeUsize`], returning a configuration error if the
632+
/// value falls outside the provided inclusive bounds.
633+
pub fn try_new(
634+
value: usize,
635+
inclusive_min: usize,
636+
inclusive_max: Option<usize>,
637+
) -> Result<Self> {
638+
if Self::in_range(value, inclusive_min, inclusive_max) {
639+
Ok(Self {
640+
value,
641+
inclusive_min,
642+
inclusive_max,
643+
})
644+
} else {
645+
match inclusive_max {
646+
Some(inclusive_max) => _config_err!(
647+
"value must be between {inclusive_min} and {inclusive_max}, got {value}"
648+
),
649+
None => _config_err!("value must be at least {inclusive_min}"),
650+
}
651+
}
652+
}
653+
654+
/// Returns the configured value.
655+
pub const fn get(self) -> usize {
656+
self.value
657+
}
658+
659+
/// Returns the inclusive minimum bound.
660+
pub const fn inclusive_min(self) -> usize {
661+
self.inclusive_min
662+
}
663+
664+
/// Returns the inclusive maximum bound, if any.
665+
pub const fn inclusive_max(self) -> Option<usize> {
666+
self.inclusive_max
667+
}
668+
}
669+
670+
impl Display for ConfigRangeUsize {
671+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
672+
write!(f, "{}", self.get())
673+
}
674+
}
675+
586676
/// A `usize` configuration value that rejects zero when set from strings.
587677
///
588678
/// Use this for options where zero is never a meaningful runtime value.
589679
/// Invalid values return a configuration error through [`ConfigField`].
590680
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
591-
pub struct ConfigNonZeroUsize(NonZeroUsize);
681+
pub struct ConfigNonZeroUsize(ConfigRangeUsize);
592682

593683
/// Private helper for hard-coded defaults in `config_namespace!`, which cannot
594684
/// use `?`. All external construction should use [`ConfigNonZeroUsize::try_new`].
595685
const fn non_zero_usize_default(value: usize) -> ConfigNonZeroUsize {
596-
match NonZeroUsize::new(value) {
597-
Some(value) => ConfigNonZeroUsize(value),
598-
None => panic!("value must be greater than 0"),
686+
if value > 0 {
687+
ConfigNonZeroUsize(ConfigRangeUsize::new_for_default(value, 1, None))
688+
} else {
689+
panic!("value must be greater than 0")
599690
}
600691
}
601692

602693
impl ConfigNonZeroUsize {
603694
/// Creates a [`ConfigNonZeroUsize`], returning a configuration error if
604695
/// `value` is zero.
605696
pub fn try_new(value: usize) -> Result<Self> {
606-
NonZeroUsize::new(value)
607-
.map(Self)
608-
.ok_or_else(|| _config_datafusion_err!("value must be greater than 0"))
697+
if value > 0 {
698+
Ok(Self(ConfigRangeUsize::new_for_default(value, 1, None)))
699+
} else {
700+
_config_err!("value must be greater than 0")
701+
}
609702
}
610703

611704
/// Returns the wrapped `usize`.
@@ -670,13 +763,13 @@ impl Display for ConfigNonZeroUsize {
670763
/// round down to a zero-capacity buffer and panic. Invalid values return a
671764
/// configuration error through [`ConfigField`] instead.
672765
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
673-
pub struct ConfigMinTwoUsize(usize);
766+
pub struct ConfigMinTwoUsize(ConfigRangeUsize);
674767

675768
/// Private helper for hard-coded defaults in `config_namespace!`, which cannot
676769
/// use `?`. All external construction should use [`ConfigMinTwoUsize::try_new`].
677770
const fn min_two_usize_default(value: usize) -> ConfigMinTwoUsize {
678771
if value >= 2 {
679-
ConfigMinTwoUsize(value)
772+
ConfigMinTwoUsize(ConfigRangeUsize::new_for_default(value, 2, None))
680773
} else {
681774
panic!("value must be at least 2")
682775
}
@@ -687,15 +780,15 @@ impl ConfigMinTwoUsize {
687780
/// `value` is less than 2.
688781
pub fn try_new(value: usize) -> Result<Self> {
689782
if value >= 2 {
690-
Ok(Self(value))
783+
Ok(Self(ConfigRangeUsize::new_for_default(value, 2, None)))
691784
} else {
692785
_config_err!("value must be at least 2")
693786
}
694787
}
695788

696789
/// Returns the wrapped `usize`.
697790
pub const fn get(self) -> usize {
698-
self.0
791+
self.0.get()
699792
}
700793
}
701794

0 commit comments

Comments
 (0)