Create web_sys::RtcPeerConnection with customized configuration - rust

I am trying to figure how to create a RtcPeerConnection with the web-sys crate. In JavaScript I can write the following:
const pc = new RTCPeerConnection({'iceServers': [{'urls': ['stun:stun.l.google.com:19302']}]});
How does this translate to rust? I have tried the following:
let mut rtc = RtcConfiguration::new();
let config = RtcConfiguration::ice_servers(&mut rtc, &JsValue::from_serde(&json!({"iceServers": [{"urls": ["stun:stun.l.google.com:19302"]}]})).unwrap());
let pc = RtcPeerConnection::new_with_configuration(&config).unwrap();
But it fails when creating pc. The json! macro is from serde_json::json.

For anyone with the same issue, the following works:
let mut rtc = RtcConfiguration::new();
let config = rtc.ice_servers(&JsValue::from_serde(&json!([{"urls": "stun:stun.l.google.com:19302"}])).unwrap());
let pc = RtcPeerConnection::new_with_configuration(&config).unwrap();

Related

Hitting upload limit on crates.io on a sys crate

I'm trying to publish a sys crate for libvmaf. Unfortunately I can not simply dynamically link to libvmaf because it's not distributed anywhere and I need to build it from source and include it in my library. Unfortunately libvmaf is absolutely huge and my .rlib file is ending up at 1.4 megabytes which is over the upload limit for crates.io. Am I boned here?
Here's my build.rs file
use meson_next;
use std::env;
use std::fs::canonicalize;
use std::path::PathBuf;
fn main() {
//env::set_var("RUST_BACKTRACE", "1");
let build_dir = PathBuf::from(env::var("OUT_DIR").unwrap()).join("build");
let lib_dir = build_dir.join("src");
let build_dir_str = build_dir.to_str().unwrap();
let lib_dir_str = lib_dir.to_str().unwrap();
meson_next::build("vmaf/libvmaf", build_dir_str);
println!("cargo:rustc-link-lib=static=vmaf");
println!("cargo:rustc-link-search=native={lib_dir_str}");
// Path to vendor header files
let headers_dir = PathBuf::from("vmaf/libvmaf/include");
let headers_dir_canonical = canonicalize(headers_dir).unwrap();
let include_path = headers_dir_canonical.to_str().unwrap();
// Generate bindings to libvmaf using rust-bindgen
let bindings = bindgen::Builder::default()
.header("vmaf/libvmaf/include/libvmaf/libvmaf.h")
.clang_arg(format!("-I{include_path}"))
.parse_callbacks(Box::new(bindgen::CargoCallbacks))
.generate()
.expect("Unable to generate bindings");
// Write bindings to build directory
let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
bindings
.write_to_file(out_path.join("bindings.rs"))
.expect("Couldn't write bindings!");
}
In general you should not be including compiled libraries in your package. Include the source code, and have your build script perform the build.
This will usually result in a smaller package, and also means that your package works on any target architecture (that is supported by the library).

How do I execute a Move script on Aptos using the Rust SDK?

I want to execute this Move script, e.g. at sources/top_up.move:
script {
use std::signer;
use aptos_framework::aptos_account;
use aptos_framework::aptos_coin;
use aptos_framework::coin;
fun main(src: &signer, dest: address, desired_balance: u64) {
let src_addr = signer::address_of(src);
let balance = coin::balance<aptos_coin::AptosCoin>(src_addr);
if (balance < desired_balance) {
aptos_account::transfer(src, dest, desired_balance - balance);
};
}
}
This is calling functions on the aptos_coin.move module, which is deployed on chain. What it does isn't so important for this question, but in short, it checks that the balance of the destination account is less than desired_balance, and if so, tops it up to desired_balance.
I can execute this Move script via the CLI easily like this:
aptos move compile
aptos move run-script --compiled-script-path build/MyModule/bytecode_scripts/main.mv
Or even just this:
aptos move run-script --script-path sources/top_up.move
What I want to know is whether I can do this using the Rust SDK?
First, you need to compile the script, as you did above. Imagine you have a project layout like this:
src/
main.rs
move/
Move.toml
sources/
top_up.mv
You would want to go in to move/ and run aptos move compile, like you said above. From there, you can depend on the compiled script in your code (see below).
With that complete, here is a minimal code example demonstrating how to execute a Move script using the Rust SDK.
Cargo.toml:
[package]
name = "my-example"
version = "0.1.0"
edition = "2021"
[dependencies]
anyhow = "1"
aptos-sdk = { git = "https://github.com/aptos-labs/aptos-core", branch = "mainnet" }
src/main.rs:
use aptos_sdk::crypto::ed25519::Ed25519PublicKey;
use aptos_sdk::types::transaction::authenticator::AuthenticationKey;
use aptos_sdk::{
rest_client::Client,
transaction_builder::TransactionFactory,
types::{
account_address::AccountAddress,
chain_id::ChainId,
transaction::{Script, SignedTransaction, TransactionArgument},
LocalAccount,
},
};
static SCRIPT: &[u8] =
include_bytes!("../../move/build/MyModule/bytecode_scripts/main.mv");
fn main() -> anyhow::Result<()> {
// Prior to the follow code we assume you've already acquired the necessary
// information such as chain_id, the private key of the account submitting
// the transaction, arguments for the Move script, etc.
// Build a transaction factory.
let txn_factory = TransactionFactory::new(chain_id);
// Build a local representation of an account.
let account = LocalAccount::new(
AuthenticationKey::ed25519(&Ed25519PublicKey::from(&private_key)).derived_address()
private_key,
0,
);
// Build an API client.
let client = Client::new("https://fullnode.mainnet.aptoslabs.com");
// Create a builder where the payload is the script.
let txn_builder = transaction_factory.script(Script::new(
SCRIPT.to_vec(),
// type args
vec![],
// args
vec![
TransactionArgument::Address(dest_address),
TransactionArgument::U64(desired_balance),
],
)));
// Build the transaction request and sign it.
let signed_txn = account.sign_with_transaction_builder(
txn_builder
);
// Submit the transaction.
client.submit_and_wait_bcs(&signed_transaction).await?;
}

Edit local yaml file in rust

I'm trying to edit yaml file using serde_yaml but using this i'm only able to edit in stdout but cannot write back to local file(/home/home/.kube/config)
let kubeconfig = "/home/home/.kube/config"
let contents = fs::read_to_string(kubeconfig)
.expect("Something went wrong reading the file");
let mut value: serde_yaml::Value = serde_yaml::from_str(&contents).unwrap();
*value.get_mut("current-context").unwrap() = "new_user".into();
// Below lines shows the edited file in stdout
serde_yaml::to_writer(std::io::stdout(), &value).unwrap();
I did tired as below an other method but had no luck.
let writer = serde_yaml::to_writer(std::io::stdout(), &value).unwrap();
println!("{:?}",writer); // shows ()
serde_yaml::to_writer(writer);
How do i write this edit back to /home/home/.kube/config ?
It seems that you are trying to use to_writer as to_string:
let writer = serde_yaml::to_string(&value).unwrap();
println!("{:?}", writer);
Then you can save the string how you usually would.
Or, alternatively, you could write directly to a file:
let mut file = File::create("/home/home/.kube/config").unwrap();
serde_yaml.to_writer(&mut file, &value);

Rust lightningcss minify

Trying to figure out how to use minify from lightningcss. Here's my code
let fs = FileProvider::new();
let mut bundler = Bundler::new(&fs, None, ParserOptions::default());
let stylesheet = bundler.bundle(Path::new("./assets/css/global.css")).unwrap();
stylesheet.minify(MinifyOptions::default());
println!("{}", stylesheet.to_css(PrinterOptions::default()).unwrap().code);
If I try to print the unwrapped version of the minified output that is empty.
taken more from here https://docs.rs/lightningcss/1.0.0-alpha.34/lightningcss/stylesheet/struct.StyleSheet.html
And the question: how do I use the minify output?

fltk: failed to resolve GlutWindow

I'm trying to follow example of fltk application which uses openGl, but the build is not functioning:
let app = app::App::default();
let mut win = window::GlutWindow::default().with_size(800, 600);
win.set_mode(enums::Mode::Opengl3);
win.end();
win.show();
unsafe {
let gl = glow::Context::from_loader_function(|s| {
win.get_proc_address(s) as *const _
});
I get: failed to resolve: could not find GlutWindow in window.
I'm using fltk version 1
Thank you
p.s. I'm using Rust
Check your imports which are missing from that snippet.
Also if you’re not enabling the enable-glwindow feature, you should, try changing your Cargo.toml to include the missing feature:
[dependencies]
fltk = { version = "1", features = ["enable-glwindow"] }

Resources