rive_rs/importers/
import_stack.rs

1// Copyright 2021 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use std::any::TypeId;
6use std::collections::HashMap;
7use std::fmt;
8
9use crate::core::AsAny;
10use crate::status_code::StatusCode;
11
12pub trait ImportStackObject: AsAny + fmt::Debug {
13    fn resolve(&self) -> StatusCode {
14        StatusCode::Ok
15    }
16}
17
18#[derive(Debug, Default)]
19pub struct ImportStack {
20    latests: HashMap<TypeId, Box<dyn ImportStackObject>>,
21}
22
23impl ImportStack {
24    pub fn latest<T: ImportStackObject>(&self, id: TypeId) -> Option<&T> {
25        self.latests.get(&id).and_then(|object| (&**object).as_any().downcast_ref())
26    }
27
28    pub fn make_latest(
29        &mut self,
30        id: TypeId,
31        object: Option<Box<dyn ImportStackObject>>,
32    ) -> StatusCode {
33        if let Some(removed) = self.latests.remove(&id) {
34            let code = removed.resolve();
35            if code != StatusCode::Ok {
36                return code;
37            }
38        }
39
40        if let Some(object) = object {
41            self.latests.insert(id, object);
42        }
43
44        StatusCode::Ok
45    }
46
47    pub fn resolve(&self) -> StatusCode {
48        self.latests
49            .values()
50            .map(|object| object.resolve())
51            .find(|&code| code != StatusCode::Ok)
52            .unwrap_or(StatusCode::Ok)
53    }
54}