cypheron-core 0.1.2

Post-quantum cryptography library with NIST-standardized quantum-resistant algorithms
Documentation
// Copyright 2025 Cypheron Labs, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use super::{CpuCapabilities, OptimizationLevel, OptimizationProvider};
use std::error::Error as StdError;
use std::fmt::Debug;

pub trait AlgorithmFactory<T> {
    type Error: StdError + Debug + Send + Sync + 'static;

    fn create_with_optimization(
        &self,
        level: OptimizationLevel,
        capabilities: &CpuCapabilities,
    ) -> Result<T, Self::Error>;

    fn create_reference(&self) -> Result<T, Self::Error>;
    fn create_optimized(&self, capabilities: &CpuCapabilities) -> Result<T, Self::Error>;
}

pub struct DefaultAlgorithmFactory<P> {
    provider: P,
}

impl<P> DefaultAlgorithmFactory<P> {
    pub fn new(provider: P) -> Self {
        Self { provider }
    }
}

impl<P, T> AlgorithmFactory<T> for DefaultAlgorithmFactory<P>
where
    P: OptimizationProvider<Output = T>,
    P::Error: StdError + Debug + Send + Sync + 'static,
{
    type Error = P::Error;

    fn create_with_optimization(
        &self,
        level: OptimizationLevel,
        capabilities: &CpuCapabilities,
    ) -> Result<T, Self::Error> {
        match level {
            OptimizationLevel::Reference => self.create_reference(),
            OptimizationLevel::Optimized | OptimizationLevel::Aggressive => {
                self.create_optimized(capabilities)
            }
        }
    }

    fn create_reference(&self) -> Result<T, Self::Error> {
        self.provider.create_reference()
    }

    fn create_optimized(&self, capabilities: &CpuCapabilities) -> Result<T, Self::Error> {
        self.provider.create_optimized(capabilities)
    }
}