1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
//! Registry of problem and solver factories.
use crate::json::JsonRecipe;
use crate::problem::{BoxProblemFactory, ProblemRecipe};
use crate::solver::{BoxSolverFactory, SolverRecipe};
use crate::{Error, Result};
use serde_json;
use std::collections::HashMap;
use std::fmt;
use std::sync::{Arc, Mutex, Weak};

/// Factory registry.
#[derive(Debug)]
pub struct FactoryRegistry {
    problem: ProblemFactoryRegistry,
    solver: SolverFactoryRegistry,
}
impl FactoryRegistry {
    /// Makes a new `FactoryRegistry` instance.
    pub fn new<P, S>() -> Self
    where
        P: 'static + ProblemRecipe,
        S: 'static + SolverRecipe,
    {
        Self {
            problem: ProblemFactoryRegistry::new::<P>(),
            solver: SolverFactoryRegistry::new::<S>(),
        }
    }

    /// Gets or creates a problem factory associated with the given recipe JSON.
    pub fn get_or_create_problem_factory(
        &self,
        recipe: &JsonRecipe,
    ) -> Result<Arc<Mutex<BoxProblemFactory>>> {
        self.problem.get_or_create(recipe, self)
    }

    /// Gets or creates a solver factory associated with the given recipe JSON.
    pub fn get_or_create_solver_factory(
        &self,
        recipe: &JsonRecipe,
    ) -> Result<Arc<Mutex<BoxSolverFactory>>> {
        self.solver.get_or_create(recipe, self)
    }
}

struct ProblemFactoryRegistry {
    normalize_json: Box<dyn Fn(&JsonRecipe) -> Result<String>>,
    create_factory: Box<dyn Fn(&str, &FactoryRegistry) -> Result<BoxProblemFactory>>,
    factories: Mutex<HashMap<String, Weak<Mutex<BoxProblemFactory>>>>,
}
impl ProblemFactoryRegistry {
    fn new<T>() -> Self
    where
        T: 'static + ProblemRecipe,
    {
        let normalize_json = Box::new(|json: &JsonRecipe| {
            let recipe: T = track!(serde_json::from_value(json.clone()).map_err(Error::from))?;
            track!(serde_json::to_string(&recipe).map_err(Error::from))
        });
        let create_factory = Box::new(|json: &str, registry: &FactoryRegistry| {
            let recipe: T = track!(serde_json::from_str(json).map_err(Error::from))?;
            let factory = track!(recipe.create_factory(registry)).map(BoxProblemFactory::new)?;
            Ok(factory)
        });
        Self {
            normalize_json,
            create_factory,
            factories: Mutex::new(HashMap::new()),
        }
    }

    fn get_or_create(
        &self,
        recipe: &JsonRecipe,
        registry: &FactoryRegistry,
    ) -> Result<Arc<Mutex<BoxProblemFactory>>> {
        let json = track!((self.normalize_json)(recipe))?;
        let factory = track!(self.factories.lock().map_err(Error::from))?
            .get(&json)
            .and_then(|s| s.upgrade());
        if let Some(factory) = factory {
            Ok(factory)
        } else {
            let factory = track!((self.create_factory)(&json, registry); json)?;
            let factory = Arc::new(Mutex::new(factory));
            track!(self.factories.lock().map_err(Error::from))?
                .insert(json, Arc::downgrade(&factory));
            Ok(factory)
        }
    }
}
impl fmt::Debug for ProblemFactoryRegistry {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "ProblemFactoryRegistry {{ .. }}")
    }
}

struct SolverFactoryRegistry {
    normalize_json: Box<dyn Fn(&JsonRecipe) -> Result<String>>,
    create_factory: Box<dyn Fn(&str, &FactoryRegistry) -> Result<BoxSolverFactory>>,
    factories: Mutex<HashMap<String, Weak<Mutex<BoxSolverFactory>>>>,
}
impl SolverFactoryRegistry {
    fn new<T>() -> Self
    where
        T: 'static + SolverRecipe,
    {
        let normalize_json = Box::new(|json: &JsonRecipe| {
            let recipe: T = track!(serde_json::from_value(json.clone()).map_err(Error::from))?;
            track!(serde_json::to_string(&recipe).map_err(Error::from))
        });
        let create_factory = Box::new(|json: &str, registry: &FactoryRegistry| {
            let recipe: T = track!(serde_json::from_str(json).map_err(Error::from))?;
            let factory = track!(recipe.create_factory(registry)).map(BoxSolverFactory::new)?;
            Ok(factory)
        });
        Self {
            normalize_json,
            create_factory,
            factories: Mutex::new(HashMap::new()),
        }
    }

    fn get_or_create(
        &self,
        recipe: &JsonRecipe,
        registry: &FactoryRegistry,
    ) -> Result<Arc<Mutex<BoxSolverFactory>>> {
        let json = track!((self.normalize_json)(recipe))?;
        let factory = track!(self.factories.lock().map_err(Error::from))?
            .get(&json)
            .and_then(|s| s.upgrade());
        if let Some(factory) = factory {
            Ok(factory)
        } else {
            let factory = track!((self.create_factory)(&json, registry); json)?;
            let factory = Arc::new(Mutex::new(factory));
            track!(self.factories.lock().map_err(Error::from))?
                .insert(json, Arc::downgrade(&factory));
            Ok(factory)
        }
    }
}
impl fmt::Debug for SolverFactoryRegistry {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "SolverFactoryRegistry {{ .. }}")
    }
}