screeps/objects/impls/
store.rs

1use js_sys::Object;
2use wasm_bindgen::prelude::*;
3
4use crate::constants::ResourceType;
5
6//TODO: wiarchbe: Need types for general purpose store and specific store.
7// (Specific store can return undefined for missing types.)
8#[wasm_bindgen]
9extern "C" {
10    /// An object that represents the cargo within an entity in the game world.
11    ///
12    /// [Screeps documentation](https://docs.screeps.com/api/#Store)
13    #[wasm_bindgen]
14    pub type Store;
15
16    #[wasm_bindgen(method, structural, indexing_getter)]
17    pub fn get(this: &Store, ty: ResourceType) -> Option<u32>;
18
19    /// Get the capacity of the [`Store`] for the specified resource. If the
20    /// [`Store`] can contain any resource, passing `None` as the type will get
21    /// the general store capacity.
22    ///
23    /// [Screeps documentation](https://docs.screeps.com/api/#Store.getCapacity)
24    #[wasm_bindgen(method, js_name = getCapacity)]
25    fn get_capacity_internal(this: &Store, ty: Option<ResourceType>) -> Option<u32>;
26
27    /// Return the free capacity of the [`Store`] for the specified resource.
28    ///
29    /// [Screeps documentation](https://docs.screeps.com/api/#Store.getFreeCapacity)
30    #[wasm_bindgen(method, js_name = getFreeCapacity)]
31    fn get_free_capacity_internal(this: &Store, ty: Option<ResourceType>) -> Option<i32>;
32
33    /// Return the used capacity of the [`Store`] for the specified resource. If
34    /// the [`Store`] can contain any resource, passing `None` as the type will
35    /// get the total used capacity.
36    ///
37    /// [Screeps documentation](https://docs.screeps.com/api/#Store.getUsedCapacity)
38    #[wasm_bindgen(method, js_name = getUsedCapacity)]
39    fn get_used_capacity_internal(this: &Store, ty: Option<ResourceType>) -> Option<u32>;
40}
41
42impl Store {
43    pub fn store_types(&self) -> Vec<ResourceType> {
44        Object::keys(self.unchecked_ref())
45            .iter()
46            .filter_map(|v| ResourceType::from_js_value(&v))
47            .collect()
48    }
49
50    pub fn get_capacity(&self, ty: Option<ResourceType>) -> u32 {
51        self.get_capacity_internal(ty).unwrap_or(0)
52    }
53
54    pub fn get_free_capacity(&self, ty: Option<ResourceType>) -> i32 {
55        self.get_free_capacity_internal(ty).unwrap_or(0)
56    }
57
58    pub fn get_used_capacity(&self, ty: Option<ResourceType>) -> u32 {
59        self.get_used_capacity_internal(ty).unwrap_or(0)
60    }
61}