ic_wasm/
metadata.rs

1use walrus::{IdsToIndices, Module, RawCustomSection};
2
3#[derive(Clone, Copy)]
4pub enum Kind {
5    Public,
6    Private,
7}
8
9/// Add or overwrite a metadata section
10pub fn add_metadata(m: &mut Module, visibility: Kind, name: &str, data: Vec<u8>) {
11    let name = match visibility {
12        Kind::Public => "icp:public ".to_owned(),
13        Kind::Private => "icp:private ".to_owned(),
14    } + name;
15    drop(m.customs.remove_raw(&name));
16    let custom_section = RawCustomSection { name, data };
17    m.customs.add(custom_section);
18}
19
20/// Remove a metadata section
21pub fn remove_metadata(m: &mut Module, name: &str) {
22    let public = "icp:public ".to_owned() + name;
23    let private = "icp:private ".to_owned() + name;
24    m.customs.remove_raw(&public);
25    m.customs.remove_raw(&private);
26}
27
28/// List current metadata sections
29pub fn list_metadata(m: &Module) -> Vec<&str> {
30    m.customs
31        .iter()
32        .map(|section| section.1.name())
33        .filter(|name| name.starts_with("icp:"))
34        .collect()
35}
36
37/// Get the content of metadata
38pub fn get_metadata<'a>(m: &'a Module, name: &'a str) -> Option<std::borrow::Cow<'a, [u8]>> {
39    let public = "icp:public ".to_owned() + name;
40    let private = "icp:private ".to_owned() + name;
41    m.customs
42        .iter()
43        .find(|(_, section)| section.name() == public || section.name() == private)
44        .map(|(_, section)| section.data(&IdsToIndices::default()))
45}