Skip to content

Commit

Permalink
add vec conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
chenyan-dfinity committed Feb 26, 2023
1 parent d0448b9 commit 58374a3
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ Type annotations in `ic-repl` is more permissible (not following the subtyping r
* `("text" : blob)` becomes `blob "text"` and vice versa. Converting `blob` to `text` can get an error if the blob is not utf8 compatible.
* `(service "aaaaa-aa" : principal)` becomes `principal "aaaaa-aa"`. You can convert among `service`, `principal` and `func`.
* `((((1.99 : nat8) : int) : float32) : nat32)` becomes `(1 : nat32)`. When converting from float to integer, we only return the integer part of the float.
* Type annotations for `vec`, `record`, `variant` is left unimplemented. With candid interface embedded in the canister metadata, annotating composite types is almost never needed.
* Type annotations for `record`, `variant` is left unimplemented. With candid interface embedded in the canister metadata, annotating composite types is almost never needed.

## Examples

Expand Down
10 changes: 9 additions & 1 deletion src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,14 @@ pub fn cast_type(v: IDLValue, ty: &Type) -> Result<IDLValue> {
(IDLValue::Null | IDLValue::Reserved | IDLValue::None, TypeInner::Opt(_)) => IDLValue::None,
// No fallback to None for option
(IDLValue::Opt(v), TypeInner::Opt(t)) => IDLValue::Opt(Box::new(cast_type(*v, t)?)),
(IDLValue::Vec(vec), TypeInner::Vec(t)) => {
let mut res = Vec::with_capacity(vec.len());
for e in vec.into_iter() {
let v = cast_type(e, t)?;
res.push(v);
}
IDLValue::Vec(res)
}
// text <--> blob
(IDLValue::Text(s), TypeInner::Text) => IDLValue::Text(s),
(IDLValue::Vec(vec), TypeInner::Text)
Expand Down Expand Up @@ -109,7 +117,7 @@ pub fn cast_type(v: IDLValue, ty: &Type) -> Result<IDLValue> {
(v, TypeInner::Float32) => IDLValue::Float32(num_cast_helper(v, false)?.parse::<f32>()?),
(v, TypeInner::Float64) => IDLValue::Float64(num_cast_helper(v, false)?.parse::<f64>()?),
// error
(_, TypeInner::Vec(_) | TypeInner::Record(_) | TypeInner::Variant(_)) => {
(_, TypeInner::Record(_) | TypeInner::Variant(_)) => {
return Err(anyhow!("{ty} annotation not implemented"))
}
(v, _) => return Err(anyhow!("Cannot cast {v} to type {ty}")),
Expand Down

0 comments on commit 58374a3

Please sign in to comment.