graph_process_manager_core 0.4.0

Utilities to explore parts of a tree-like or graph-like structure that is not known in advance
Documentation
/*
Copyright 2020 Erwan Mahe (github.com/erwanM974)

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 std::collections::HashMap;
use std::sync::Arc;

use super::config::AbstractProcessConfiguration;



pub(crate) enum NodeMemoizer<Conf : AbstractProcessConfiguration> {
    // Arc<Node> as key: Hash/Eq delegate to Node, and Arc<T>: Borrow<T> lets
    // check_memo look up by &Node without constructing a temporary Arc.
    Memoizing(HashMap<Arc<Conf::DomainSpecificNode>, u32>),
    NotMemoizing
}

impl<Conf : AbstractProcessConfiguration> NodeMemoizer<Conf> {

    pub fn new(is_memoized : bool) -> Self {
        if is_memoized {
            Self::Memoizing(HashMap::new())
        } else {
            Self::NotMemoizing
        }
    }

    pub fn is_memoized(&self) -> bool {
        match &self {
            NodeMemoizer::Memoizing(_) => true,
            NodeMemoizer::NotMemoizing => false
        }
    }

    // Takes &Node — Arc<T>: Borrow<T> makes the HashMap lookup work without an Arc allocation.
    pub fn check_memo(&self, to_look_up : &Conf::DomainSpecificNode) -> Option<u32> {
        match &self {
            NodeMemoizer::Memoizing(memo) => memo.get(to_look_up).copied(),
            NodeMemoizer::NotMemoizing => None,
        }
    }

    // Takes the Arc directly so the caller's Arc is stored as the key with no extra clone.
    pub fn memoize_new_node(&mut self, arc_node : Arc<Conf::DomainSpecificNode>, new_node_id : u32) {
        match self {
            NodeMemoizer::Memoizing(memo) => {
                memo.insert(arc_node, new_node_id);
            },
            NodeMemoizer::NotMemoizing => {}
        }
    }

}