Skip to content

any - [mainnet]

use 0x1::bcs;
use 0x1::error;
use 0x1::from_bcs;
use 0x1::string;
use 0x1::type_info;

Constants

The type provided for unpack is not the same as was given for pack.

const ETYPE_MISMATCH: u64 = 1;

Structs

Any

A type which can represent a value of any type. This allows for representation of ‘unknown’ future values. For example, to define a resource such that it can be later be extended without breaking changes one can do

struct Resource {
field: Type,
...
extension: Option<Any>
}
struct Any has drop, store
Fields
type_name: string::String
data: vector<u8>

Functions

pack

Pack a value into the Any representation. Because Any can be stored and dropped, this is also required from T.

public fun pack<T: drop, store>(x: T): any::Any
Implementation
public fun pack<T: drop + store>(x: T): Any {
Any {
type_name: type_info::type_name<T>(),
data: to_bytes(&x)
}
}

unpack

Unpack a value from the Any representation. This aborts if the value has not the expected type T.

public fun unpack<T>(self: any::Any): T
Implementation
public fun unpack<T>(self: Any): T {
assert!(type_info::type_name<T>() == self.type_name, error::invalid_argument(ETYPE_MISMATCH));
from_bytes<T>(self.data)
}

type_name

Returns the type name of this Any

public fun type_name(self: &any::Any): &string::String
Implementation
public fun type_name(self: &Any): &String {
&self.type_name
}

Specification

pack

public fun pack<T: drop, store>(x: T): any::Any
aborts_if false;
ensures result == Any {
type_name: type_info::type_name<T>(),
data: bcs::serialize<T>(x)
};
ensures [abstract] from_bcs::deserializable<T>(result.data);

unpack

public fun unpack<T>(self: any::Any): T
include UnpackAbortsIf<T>;
ensures result == from_bcs::deserialize<T>(self.data);
schema UnpackAbortsIf<T> {
self: Any;
aborts_if type_info::type_name<T>() != self.type_name;
aborts_if !from_bcs::deserializable<T>(self.data);
}
schema UnpackRequirement<T> {
self: Any;
requires type_info::type_name<T>() == self.type_name;
requires from_bcs::deserializable<T>(self.data);
}

type_name

public fun type_name(self: &any::Any): &string::String
aborts_if false;
ensures result == self.type_name;