marine_core/
memory_statistic.rs

1/*
2 * Copyright 2022 Fluence Labs Limited
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17use marine_wasm_backend_traits::MemoryAllocationStats;
18
19use serde::Serialize;
20use serde::Deserialize;
21
22use std::fmt;
23
24/// Contains module name and a size of its linear memory in bytes.
25/// Please note that linear memory contains not only heap, but globals, shadow stack and so on.
26/// Although it doesn't contain operand stack, additional runtime (Wasmer) structures,
27/// and some other stuff, that should be count separately.
28#[derive(Clone, Default, Debug, Serialize, Deserialize)]
29pub struct ModuleMemoryStat<'module_name> {
30    pub name: &'module_name str,
31    pub memory_size: usize,
32}
33
34pub struct MemoryStats<'module_name> {
35    pub modules: Vec<ModuleMemoryStat<'module_name>>,
36    pub allocation_stats: Option<MemoryAllocationStats>,
37}
38
39impl<'module_name> MemoryStats<'module_name> {
40    pub fn new(
41        modules: Vec<ModuleMemoryStat<'module_name>>,
42        allocation_stats: Option<MemoryAllocationStats>,
43    ) -> Self {
44        Self {
45            modules,
46            allocation_stats,
47        }
48    }
49}
50
51impl<'module_name> ModuleMemoryStat<'module_name> {
52    pub fn new(module_name: &'module_name str, memory_size: usize) -> Self {
53        ModuleMemoryStat {
54            name: module_name,
55            memory_size,
56        }
57    }
58}
59
60impl fmt::Display for MemoryStats<'_> {
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        for module in self.modules.iter() {
63            let memory_size = bytesize::ByteSize::b(module.memory_size as u64);
64            writeln!(f, "{} - {}", module.name, memory_size)?;
65        }
66
67        match &self.allocation_stats {
68            None => writeln!(
69                f,
70                "Allocation rejects - value is not recorded by current wasm backend"
71            )?,
72            Some(stats) => writeln!(f, "Allocation rejects - {}", stats.allocation_rejects)?,
73        }
74
75        Ok(())
76    }
77}