sedregex 0.2.5

Sed-like regex library
Documentation
use crate::ErrorKind;
use regex::RegexBuilder;
use std::{collections::BTreeSet, str::FromStr};

/// A single regex flag.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum RegexFlag {
    /// Regex should be case insensitive. Corresponds to `i`.
    CaseInsensitive,
    /// Regex is run for every match in a string. Corresponds to `g`.
    Global,
    /// "Greedy swap" flag. Corresponds to `U`.
    GreedySwap,
    /// Ignore whitespaces. Corresponds to `x`.
    IgnoreWhitespaces,
}

/// A set of regex flags.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct RegexFlags(BTreeSet<RegexFlag>);

impl RegexFlags {
    /// Applies stored flags on a regex builder.
    pub fn apply(&self, builder: &mut RegexBuilder) {
        builder.case_insensitive(self.0.contains(&RegexFlag::CaseInsensitive));
        builder.swap_greed(self.0.contains(&RegexFlag::GreedySwap));
        builder.ignore_whitespace(self.0.contains(&RegexFlag::IgnoreWhitespaces));
    }

    /// If the regex should be run for all the matches or just for the first one.
    pub fn is_global(&self) -> bool {
        self.0.contains(&RegexFlag::Global)
    }
}

impl<I: IntoIterator<Item = RegexFlag>> From<I> for RegexFlags {
    fn from(i: I) -> Self {
        RegexFlags(i.into_iter().collect())
    }
}

impl FromStr for RegexFlags {
    type Err = ErrorKind;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        s.chars()
            .map(|c| match c {
                'i' => Ok(RegexFlag::CaseInsensitive),
                'g' => Ok(RegexFlag::Global),
                'U' => Ok(RegexFlag::GreedySwap),
                'x' => Ok(RegexFlag::IgnoreWhitespaces),
                c => Err(ErrorKind::UnknownFlag(c)),
            })
            .collect::<Result<_, _>>()
            .map(RegexFlags)
    }
}