Why is the document object unknown. In fact, everything, even the window.document call is not linted. Linting is quite important for me to lean a new programming language/library.
lib.rs
use wasm_bindgen::prelude::*;
#[wasm_bindgen(start)]
pub fn run() -> Result<(), JsValue> {
let window = web_sys::window().expect("could not get window handle");
let document = window.document().expect("could not get document handle");
let body = document.body().expect("could not get body handle");
let val = document.create_element("p")?;
val.set_text_content(Some("Hello from rust"));
body.append_child(&val)?;
Ok(())
}
cargo.toml
[lib]
crate-type = ["cdylib"]
[dependencies]
serde = { version = "1.0", features = ["derive"] }
wasm-bindgen = { version = "0.2", features = ["serde-serialize"] }
[dependencies.web-sys]
version = "0.3.53"
features = [
"Document",
"Element",
"HtmlElement",
"Node",
"Window",
]
Related
I want to use the crate rocket_cors for Rocket v0.5.0-rc.2 but it does not compile because "the trait bound 'Cors: Fairing' is not satisfied".
Here is my Cargo.toml:
# --snip--
[dependencies]
rocket = { version = "0.5.0-rc.2", features = [ "json" ] }
rocket_cors = { version = "0.5.2", default-features = false }
# --snip--
And here is my rocket() function:
fn rocket() -> _ {
let cors = rocket_cors::CorsOptions {
allowed_origins: AllowedOrigins::all(),
allowed_headers: AllowedHeaders::some(&["Authorization", "Accept"]),
allow_credentials: true,
..Default::default()
}
.to_cors()
.unwrap();
rocket::build()
.attach(DbConnection::fairing())
.attach(cors) // <- Here's the error: "the trait `Fairing` is not implemented for `Cors`"
.mount("/", routes![get_tasks])
}
I won't have a problem if the solution is using another CORS crate either.
I'm trying to use the criterion crate to benchmark a function in my binary crate.
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use rand::Rng;
use enigma::enigma::Enigma; // failed to resolve: use of undeclared crate or module `enigma` use of undeclared crate or module `enigma`rustcE0433
fn gen_rand_string(n: usize) -> String {
const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let mut rng = rand::thread_rng();
(0..n)
.map(|_| {
let idx = rng.gen_range(0..CHARSET.len());
CHARSET[idx] as char
})
.collect()
}
// Lots of red squigglies because of imports
fn construct_enigma() -> Enigma {
let rotors: RotorConfig =
RotorConfig::try_from([(Rotors::I, 'A'), (Rotors::II, 'X'), (Rotors::IV, 'N')])
.unwrap();
let plugs = Plugs::try_from(vec![]).unwrap();
let plugboard: Plugboard = Plugboard::try_from(plugs).unwrap();
let reflector: Reflectors = Reflectors::B;
Enigma::new(rotors, plugboard, reflector)
}
fn criterion_benchmark(c:&mut Criterion){
let e = construct_enigma();
let s1000 = gen_rand_string(1000);
c.bench_function("ENC 1000", |b|b.iter(||))
}
Here's my cargo.toml
[package]
name = "enigma"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
anyhow = "1.0.65"
bimap = "0.6.2"
bruh_moment = "0.1.1"
itertools = "0.10.3"
log = "0.4.17"
rand = "0.8.5"
strum = "0.24.1"
strum_macros = "0.24.3"
thiserror = "1.0.37"
[dev-dependencies]
criterion = "0.4.0"
[[bench]]
name = "encode_string"
harness = false
by my understanding i should be importing my function using %mycratename%::foo::bar instead of crate::foo::bar but i'm getting an error saying that my crate can't be found. How do I get rust to recognize my local unpublished crate for criterion benchmarks?
How do you convert an IInspectable reference to a RenderingEventArgs in the following taken from the full xaml_app code below?
CompositionTarget::Rendering(EventHandler::new(move |_, args: &Option<IInspectable>| {
let args: &IInspectable = args.as_ref().unwrap();
//let render_args = RenderingEventArgs::from(&args);
//let render_args: RenderingEventArgs = args.try_into()?;
Ok(())
}))?;
Full code listing follows for context:
#![windows_subsystem = "windows"]
#![allow(non_snake_case)]
use windows::{
core::{
IInspectable,
Result,
HSTRING,
implement,
},
ApplicationModel::Activation::LaunchActivatedEventArgs,
Win32::System::Com::{
CoInitializeEx,
COINIT_MULTITHREADED,
},
Foundation::EventHandler,
//Foundation::TypedEventHandler,
UI::{
Colors,
Xaml::{
Controls::{
TextBlock,
},
Application,
ApplicationInitializationCallback,
Window,
Media::{
FontFamily,
SolidColorBrush,
CompositionTarget,
RenderingEventArgs,
},
HorizontalAlignment,
VerticalAlignment,
FrameworkElement,
IApplicationOverrides,
IApplicationOverrides_Impl,
},
},
};
//use std::convert::TryInto;
#[implement(IApplicationOverrides)]
struct App();
impl IApplicationOverrides_Impl for App {
fn OnLaunched(&self, _: &Option<LaunchActivatedEventArgs>) -> Result<()> {
let block = TextBlock::new()?;
block.SetFontFamily(FontFamily::CreateInstanceWithName(HSTRING::from("Segoe UI Semibold"))?)?;
block.SetFontSize(72.0)?;
block.SetForeground(SolidColorBrush::CreateInstanceWithColor(Colors::Orange()?)?)?;
let fe = FrameworkElement::from(&block);
fe.SetHorizontalAlignment(HorizontalAlignment::Center)?;
fe.SetVerticalAlignment(VerticalAlignment::Center)?;
let window = Window::Current()?;
window.SetContent(&block)?;
window.Activate()?;
CompositionTarget::Rendering(EventHandler::new(move |_, args: &Option<IInspectable>| {
let args: &IInspectable = args.as_ref().unwrap();
//let render_args = RenderingEventArgs::from(&args);
//let render_args: RenderingEventArgs = args.try_into()?;
Ok(())
}))?;
Ok(())
}
}
fn main() -> Result<()> {
unsafe {
CoInitializeEx(std::ptr::null(), COINIT_MULTITHREADED)?;
}
Application::Start(ApplicationInitializationCallback::new(|_| {
Application::compose(App())?;
Ok(())
}))
}
[package]
name = "expanding_text"
version = "0.0.0"
edition = "2018"
[dependencies]
futures = "0.3"
[dependencies.windows]
version = "0.36"
features = [
"implement",
"ApplicationModel_Activation",
"Win32_System_Com",
"UI_Xaml_Controls",
"UI_Xaml",
"UI_Xaml_Media",
"UI",
"Storage_Pickers",
"Foundation_Collections",
"Storage",
"Foundation",
"Storage_Streams",
"Graphics_Imaging",
"Media_Ocr",
"ApplicationModel_Core",
"UI_Core",
]
The following line appears to make the conversion and builds:
let render_args: RenderingEventArgs = args.cast()?;
I'm trying to use the setup as outlined in the serde_with docs here to deserialize nested json into my struct: https://docs.rs/serde_with/1.4.0/serde_with/json/nested/index.html
After a few tries Cargo.toml file looks like:
[dependencies]
serde = { version = "1.0", features = ["derive"] }
//serde_with = { version = "1.4.0", features = ["..."] } // this doesn't work even though that's what the serde_with README calls for
serde_with = { version = "1.4.0", optional = true }
serde_json = "1.0"
Trying the above I get an error such as:
#[serde(default, rename(deserialize = "Plan"), with="serde_with::json::nested")]
^^^^^^^^^^^^^^^^^^^^^^^^^^ use of undeclared type or module `serde_with`
What am I doing wrong?
In your example the module serde_with is not optional and must provide the feature json.
Replace
serde_with = { version = "1.4.0", optional = true}
with
serde_with = { version = "1.4.0", features = ["json"]}
Full example:
Cargo.toml
[dependencies]
serde = { version = "1.0" }
serde_json = "1.0"
serde_derive = "1.0"
serde_with = { version = "1.4.0", features = ["json"]}
main.rs
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
#[derive(Deserialize, Serialize)]
struct A {
#[serde(with = "serde_with::json::nested")]
other_struct: B,
}
#[derive(Deserialize, Serialize)]
struct B {
value: usize,
}
fn main() {
let v: A = serde_json::from_str(r#"{"other_struct":"{\"value\":5}"}"#).unwrap();
assert_eq!(5, v.other_struct.value);
let x = A {
other_struct: B { value: 10 },
};
assert_eq!(r#"{"other_struct":"{\"value\":10}"}"#, serde_json::to_string(&x).unwrap());
}
reqwest v0.9 has serde v1.0 as a dependency and as a result implements converting serde_json errors into reqwest error.
In my code, I am doing some deserialization using serde_json instead of using .json() method that comes with reqwest.
// reqwest = "0.9"
// serde = { version = "1.0", features = ["derive"] }
// serde_json = "1.0"
pub fn get_meta(client: &reqwest::Client) -> Result<Meta, reqwest::Error> {
let mut resp = client
.get("http://localhost:8080/requests/playlist.json")
.send()?;
let data: Value = serde_json::from_str(&resp.text()?).unwrap();
let data = data["children"][0]["children"].clone();
let metas: Vec<Meta> = serde_json::from_value(data).unwrap();
let meta: Meta = metas.last().expect("nothing is playing").clone();
Ok(meta)
}
Currently, I am trying to return serde_json errors as reqwest errors. Changing let metas: Vec<Meta> = serde_json::from_value(data).unwrap(); to let metas: Vec<Meta> = serde_json::from_value(data)?; fails with the following error:
the trait `std::convert::From<serde_json::error::Error>` is not implemented for `reqwest::error::Error`
Is it possible to convert serde_json::error::Error to reqwest::error::Error by wrapping it inside Kind::Json error enum of reqwest, or do I have to make a custom error enum that encompasses both as mentioned in this article?
No, you can't construct reqwest::Error value yourself because it:
has non-public fields
does not expose public constructors
does not have From implementations for public types
Fortunately both reqwest::Error and serde_json::error::Error implement std::error::Error trait. Following the recommendation from the blog post you linked, the anyhow crate is very helpful here:
// reqwest = "0.9"
// serde = { version = "1.0", features = ["derive"] }
// serde_json = "1.0"
// anyhow = "1.0"
pub fn get_meta(client: &reqwest::Client) -> Result<Meta, anyhow::Error> {
let mut resp = client
.get("http://localhost:8080/requests/playlist.json")
.send()?;
let data: Value = serde_json::from_str(&resp.text()?).unwrap();
let data = data["children"][0]["children"].clone();
let metas: Vec<Meta> = serde_json::from_value(data).unwrap();
let meta: Meta = metas.last().expect("nothing is playing").clone();
Ok(meta)
}