Stdweb js! reading out an i32


#1
  1. I am using js! from stdweb.

  2. I have a snippet like:

    let v : Value = (js!{ return (window.devicePixelRatio || 1) });
    let dpc: i32 = v.into();
  1. I get a compile error of:
19 |     let dpc: i32 = v.into();
   |                      ^^^^ the trait `std::convert::From<stdweb::Value>` is not implemented for `i32`
   |
   = help: the following implementations were found:
             <i32 as std::convert::From<bool>>
             <i32 as std::convert::From<i16>>
             <i32 as std::convert::From<i8>>
             <i32 as std::convert::From<u16>>
             <i32 as std::convert::From<u8>>
   = note: required because of the requirements on the impl of `std::convert::Into<i32>` for `stdweb::Value`
  1. Now I am confused – why does it not support i32? Well, let me try i16 anyway to see what happens, so I try:
    let v : Value = (js!{ return (window.devicePixelRatio || 1) });
    let dpc: i16 = v.into();
  1. This now gives me error:
19 |     let dpc: i16 = v.into();
   |                      ^^^^ the trait `std::convert::From<stdweb::Value>` is not implemented for `i16`
   |
   = help: the following implementations were found:
             <i16 as std::convert::From<bool>>
             <i16 as std::convert::From<i8>>
             <i16 as std::convert::From<u8>>
   = note: required because of the requirements on the impl of `std::convert::Into<i16>` for `stdweb::Value`
  1. So this does not work either.

  2. Questions:

7a. WTF is going on?
7b. How do I read out i32 from js! ?


#2

You can use try_into to convert into an integer. From<stdweb::Value> is not implemented because it is a fallible conversion, and From<stdweb::Value> is for infallible conversions.

https://docs.rs/stdweb/*/stdweb/enum.Value.html#impl-TryFrom<i32>


#3

I’m a bit confused with the high level terminology here. Are the following right.

  1. impl U From<V> == impl V Into<U> == we can go from V to U always, without failing.

  2. try_into is for situations where failure can happen.

  3. Value -> i32 is try_into, because Value could be a string, or a DOM element, and not a number.


#4

Yes