Convert filename to URI in Rust - rust

In Python, we have:
pathlib.Path("~/hello/world").expanduser().as_uri()
# or
pathlib.Path("/hello/world").as_uri()
In C, we have:
char* uri = g_filename_to_uri("/hello/world", NULL, NULL)
// ...
g_free(uri)
What is the Rust's equivalent?

The from_file_path method from the url crate seems to provide the functionality you're after:
let url = Url::from_file_path("/hello/world").unwrap();
println!("{}", url); // prints file:///hello/world
Playground

Related

separate GET request path from query variables

I have the url: http://www.localhost:8080/api/numbers/prime?amount=13
via GET request
I want to get api/numbers/prime
is there any way to do that in node.js vanilla?
You can use JavaScript split and slice methods on Strings.
let url = "http://www.localhost:8080/api/numbers/prime?amount=13";
let urlWithoutQuery = url.split("?")[0];
let path = urlWithoutQuery.slice(25); // To get the value after http://www.localhost:8080
You can use URL:
const url = new URL('http://www.localhost:8080/api/numbers/prime?amount=13')
then:
console.log(url.pathname);
// outputs:
// /api/numbers/prime
console.log(url.searchParams);
// outputs:
// URLSearchParams { 'amount' => '13' }
console.log(url.search);
// outputs:
// ?amount=13

Is it possible to access current file name?

Is it possible to access current file name in Rust by
// main.rs
fn main() {
println!("filename: {}", FILE_NAME);
}
?
(This program should print filename: main.rs)
You can use the std::file macro to get the current source filename at the compile time.
let this_file = file!();
If you want to remove the path from the returned filename, you can construct a Path with it and call the file_name method.
let filename_only = Path::new(this_file).file_name().and_then(|s| s.to_str()).unwrap();
Playground

How to get path.join in Rust?

How do I write the path.join in Rust. I tried multiple examples but couldn't get it.
const exeDirectory = path.join(__dirname, '..', 'bin', 'openvpn.exe');
const processFile = path.join(__dirname, '..', '1');
I want to convert these lines of JS into Rust.
Use Path which has the .join method
Path::new("..").join("bin").join("openvpn.exe");
I may be missing something but have you looked at Path::join, and PathBuf::push linked from it?
let exe_directory = Path::new(dirname).join("..").join("bin").join("openvpn.exe");
println!("{:?}", exe_directory);
let mut exe_directory = PathBuf::new();
exe_directory.push(dirname);
exe_directory.push("..");
exe_directory.push("bin");
exe_directory.push("openvpn.exe");
println!("{:?}", exe_directory);
Playground link
Another option is collecting an iterator of string into a PathBuf:
let path: PathBuf = ["..", "bin", "openvpn.exe"].iter().collect();
This is equivalent to creating a new PathBuf and calling .push() for each string in the iterator. To add multiple new components to an existing PathBuf, you can use the extend() method:
let mut path = PathBuf::from(dir_name);
path.extend(&["..", "bin", "openvpn.exe"]);

Require() from string into object

Assuming I have the content of a js file in a string. Furthermore, assume it has an exports['default'] = function() {...} and/or other exported properties or functions. Is there any way to "require" it (compile it) from that string into an object, such that I can use it? (Also, I don't want to cache it like require() does.)
Here's a very simple example using vm.runInThisContext():
const vm = require('vm');
let code = `
exports['default'] = function() {
console.log('hello world');
}
`
global.exports = {}; // this is what `exports` in the code will refer to
vm.runInThisContext(code);
global.exports.default(); // "hello world"
Or, if you don't want to use globals, you can achieve something similar using eval:
let sandbox = {};
let wrappedCode = `void function(exports) { ${ code } }(sandbox)`;
eval(wrappedCode);
sandbox.default(); // "hello world"
Both methods assume that the code you're feeding to it is "safe", because they will both allow running arbitrary code.

Improper base64url

The JWT guide here - https://scotch.io/tutorials/the-anatomy-of-a-json-web-token#header - says they run base64url on this:
{
"typ": "JWT",
"alg": "HS256"
}
And they end up with this:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
I try this code:
var b64u = require("base64url")
var rez = b64u(JSON.stringify({
"typ": "JWT",
"alg": "HS256"
}));
var shouldbe = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9';
console.log(rez);
console.log(shouldbe);
console.log(rez == shouldbe);
as seen here in online test:
https://tonicdev.com/56c5484d7a4ea10d0002c623/5733af59234d9d1200d8c818
however they are not matching.
Does anyone see any simple issue?
The Base64 output is dependent on which order of keys you receive in the string from the JSON.stringify call.
For reference, here is a working example using pre-built JSON strings.
let expected = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9';
let str1 = '{"alg":"HS256","typ":"JWT"}';
let str2 = '{"typ":"JWT","alg":"HS256"}';
// note that you don't need a library to Base64 encode strings in node
let base64str1 = new Buffer(str1).toString('base64');
let base64str2 = new Buffer(str2).toString('base64');
console.log(base64str1); // 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9'
console.log(base64str2); // 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9'
console.log('base64str1 equals expected?', base64str1 === expected); // true
console.log('base64str2 equals expected?', base64str2 === expected); // false

Resources