"macro undefined" when reading u8 using scan!() - input

I read about reading integer input in How to read an integer input from the user in Rust 1.0?, but I noticed that all the solutions first take a string as input and then convert it to integer. I wonder if there's a way to read an integer directly.
This page mentions scan!() macro but for some reason it doesn't seem to run when I compile the following program using rustc main.rc.
extern crate text_io;
fn main() {
let mut a: u8;
let mut b: u8;
scan!("{},{}", a, b);
print!("{} {}", a, b);
}
This produces the error:
error: macro undefined: 'scan!'
scan!("{},{}",a,b);

You have to explicitly say that you want to import macros from this crate:
#[macro_use] extern crate text_io;
This is written at the very top of the readme, you must have missed it.
To use crates from crates.io, you need to add them to your Cargo.toml, for example by adding the following lines to that file:
[dependencies]
text_io = "0.1"

Related

Deserializing an enum using a combination of #[serde(untagged)] and #[serde(with)]

I'm trying to use an actix-web server as a gateway to a small stack to guarantee a strict data format inside of the stack while allowing some freedoms for the user.
To do that, I want to deserialize a JSON string to the struct, then validate it, serialize it again and publish it on a message broker. The main part of the data is an array of arrays that contain integers, floats and datetimes. I'm using serde for deserialization and chrono to deal with datetimes.
I tried using a struct combined with an enum to allow the different types:
#[derive(Serialize, Deserialize)]
pub struct Data {
pub column_names: Option<Vec<String>>,
pub values: Vec<Vec<ValueType>>,
}
#[derive(Serialize, Deserialize)]
#[serde(untagged)]
pub enum ValueType {
I32(i32),
F64(f64),
#[serde(with = "datetime_handler")]
Dt(DateTime<Utc>),
}
Since chrono::DateTime<T> does not implement Serialize, I added a custom module for that similar to how it is described in the serde docs.
mod datetime_handler {
use chrono::{DateTime, TimeZone, Utc};
use serde::{self, Deserialize, Deserializer, Serializer};
pub fn serialize<S>(dt: &DateTime<Utc>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let s = dt.to_rfc3339();
serializer.serialize_str(&s)
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<DateTime<Utc>, D::Error>
where
D: Deserializer<'de>,
{
println!("Checkpoint 1");
let s = String::deserialize(deserializer)?;
println!("{}", s);
println!("Checkpoint 2");
let err1 = match DateTime::parse_from_rfc3339(&s) {
Ok(dt) => return Ok(dt.with_timezone(&Utc)),
Err(e) => Err(e),
};
println!("Checkpoint 3");
const FORMAT1: &'static str = "%Y-%m-%d %H:%M:%S";
match Utc.datetime_from_str(&s, FORMAT1) {
Ok(dt) => return Ok(dt.with_timezone(&Utc)),
Err(e) => println!("{}", e), // return first error not second if both fail
};
println!("Checkpoint 4");
return err1.map_err(serde::de::Error::custom);
}
}
This tries 2 different time formats one after the other and works for DateTime strings.
The Problem
It seems like the combination of `#[derive(Serialize, Deserialize)]`, `#[serde(untagged)]` and `#[serde(with)]` does something unexpected. `serde:from_str(...)` tries to deserialize every entry in the array with my custom `deserialize` function.
I would expect it to either try to deserialize into `ValueType::I32` first, succeed and continue with the next entry, as [the docs](https://serde.rs/enum-representations.html) say:
Serde will try to match the data against each variant in order and the first one that deserializes successfully is the one returned.
What happens is that the custom deserializeis applied to e.g. "0" fails and the deserialization stops.
What's going on? How do I solve it?
My ideas are that I either fail to deserialize in the wrong way or that I somehow "overwrite" the derived deserialize with my own.
#jonasbb helped me realize the code works when using [0,16.9,"2020-12-23 00:23:14"] but it does not when trying to deserialize ["0","16.9","2020-12-23 00:23:14"]. Serde does not serialize numbers from strings by default, the attempts for I32 and F64 just fail silently. This is discussed in this serde-issue and can be solved using the inofficial serde-aux crate.
Many crates will implement serde and other common utility crates, but will leave them as optional features. This can help save time when compiling. You can check a crate by viewing the Cargo.toml file to see if there is a feature for it or the dependency is included but marked as optional.
In your case, I can go to chrono on crates.io and select the Repository link to view the source code for the crate. In the Cargo.toml file, I can see that serde is used, but is not enabled by default.
[features]
default = ["clock", "std", "oldtime"]
alloc = []
std = []
clock = ["libc", "std", "winapi"]
oldtime = ["time"]
wasmbind = ["wasm-bindgen", "js-sys"]
unstable-locales = ["pure-rust-locales", "alloc"]
__internal_bench = []
__doctest = []
[depenencies]
...
serde = { version = "1.0.99", default-features = false, optional = true }
To enable it you can go into the Cargo.toml for your project and add it as a feature to chrono.
[depenencies]
chrono = { version: "0.4.19", features = ["serde"] }
Alternatively, chrono lists some (but not all?) of their optional features in their documentation. However, not all crates do this and docs can sometimes be out of date so I usually prefer the manual method.
As for the issue between the interaction of deserialize_with and untagged on enums, I don't see any issue with your code. It may be a bug in serde so I suggest you create an issue on the serde Repository so they can further look into why this error occurs.

How to dynamically call a function in a shared library?

I have a Rust project, set as an executable. I am trying to call an external shared library, also written in Rust, dynamically. I have the external library compiled on release, and I have tried both crate types cdylib and dylib.
I am using the crate libloading, which claims to be able to dynamically load shared library functions, as long as they only use primitive arguments. I keep getting this error when I try to run my code using this crate.
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: GetProcAddress { source: Os { code: 127, kind: Other, message: "The specified procedure could not be found." } }', src\main.rs:14:68
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
main.rs/main():
let now = Instant::now();
unsafe {
let lib = libloading::Library::new(
"externtest.dll").unwrap();
let foo3: Symbol<extern fn(i32) -> i32> = lib.get(b"foo").unwrap();
println!("{}", foo(1));
}
let elapsed = now.elapsed();
println!("Elapsed: {:?}", elapsed);
lib.rs:
pub extern "C" fn foo3(i:i32) -> i32{
i
}
First, your library function is called "foo3", but you're trying to load the symbol "foo".
Second, the library function's symbol may not match it's name due to mangling. You need to tell the compiler not to do that with the #[no_mangle] attribute:
#[no_mangle]
pub extern "C" fn foo(i: i32) -> i32 {
i
}
Third, this is mostly a stylistic choice, but I'd specify the ABI extern "C" when defining your symbol. Even though extern with no epecified ABI uses the "C" ABI, I've found it better to be explicit.
use libloading::{Library, Symbol};
fn main() {
unsafe {
let lib = Library::new("externtest.dll").unwrap();
let foo = lib
.get::<Symbol<extern "C" fn(i32) -> i32>>(b"foo")
.unwrap();
println!("{}", foo(1));
}
}
The above should work without issue.

What is the correct error part of the Result type of a function propagating different error types?

I tried to write a function, that shall propagate different error types. Only for example see the following code:
use std::fs::File;
use std::io;
use std::io::Read;
fn main() {
let number = read_number_from_file().unwrap();
println!("Read number {}!", number);
}
// So what is the correct error part of the Result<i32, ...>?
fn read_number_from_file() -> Result<i32, io::Error> {
let mut f = File::open("hello.txt")?;
let mut s = String::new();
f.read_to_string(&mut s)?;
let number = s.parse()?;
Ok(number)
}
Compiling it results in the following error unsurprisingly:
error[E0277]: `?` couldn't convert the error to `std::io::Error`
--> src\main.rs:16:27
|
16 | let number = s.parse()?;
| ^ the trait `std::convert::From<std::num::ParseIntError>` is not implemented for `std::io::Error`
|
= note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait
= help: the following implementations were found:
<std::io::Error as std::convert::From<std::ffi::NulError>>
<std::io::Error as std::convert::From<std::io::ErrorKind>>
<std::io::Error as std::convert::From<std::io::IntoInnerError<W>>>
= note: required by `std::convert::From::from`
So what is the correct Error type of the Result type? Is there an answer not only for this specific case: I have a function with several calls to other functions returning Result<T, E> which in the error case shall be propagated out of the function to the caller but have different Types E?
You should define your own error type, which includes all possible errors that could happen:
#[derive(Debug)]
enum Error {
Io(io::Error),
ParseInt(num::ParseIntError)
}
impl From<io::Error> for Error {
fn from(other: io::Error) -> Error {
Error::Io(other)
}
}
impl From<num::ParseIntError> for Error {
fn from(other: num::ParseIntError) -> Error {
Error::ParseInt(other)
}
}
The From conversions allow the ? operator to work as expected.
You can save a lot of typing by using one of the several crates that will generate the boilerplate for you. Some popular ones are thiserror and snafu.
I prefer thiserror because it only adds the implementations that you would otherwise write yourself and, if you are writing a library, it is transparent to your library's users. snafu is arguably more powerful - it generates a lot more code, but is opinionated in what it generates, so you will need to get used to its paradigm in order to take full advantage of it, and the snafu concepts will become part of your library's API.
Using thiserror, the code above is reduced to:
use thiserror::Error;
#[derive(Debug, Error)]
enum Error {
#[error("IO Error: {0})]
Io(#[from] io::Error),
#[error("ParseInt Error: {0})]
ParseInt(#[from] num::ParseIntError)
}
Note that this is also generating Display implementations, which I didn't include above.

How can I get user input without receiving an "Unsed Variable" warning?

I'm taking a look at Rust and decided to build a small program that takes a user's input and prints it, but also want to do some math stuff with it for practice. Currently, this is how I am taking user input:
let mut number = String::new();
let input = io::stdin().read_line(&mut number)
.ok()
.expect("Failed to read line");
println!("You entered {}", number);
However, although I do get the correct input this way, Cargo gives me the following warning:
src/main.rs:10:9: 10:14 warning: unused variable: input, #[warn(unused_variables)] on by default
src/main.rs:10 let input = reader.read_line(&mut number)
If I were to just use the input variable, no matter what number I enter I would get a "2" in return when I print the number.
How can I avoid the warning? Is there another way for me to take input without creating 2 variable bindings?
You can simply not write the value to a variable. As long as the type of the value is not marked must_use, you can ignore the value.
let mut number = String::new();
io::stdin().read_line(&mut number)
.ok()
.expect("Failed to read line");
println!("You entered {}", number);
[commercial]
You can use the text_io crate for super short and readable input like
let i: i32 = read!()
let tup: (i32, String) = read!("{}, {}");
[/commercial]
It creates a warning because you are allocating space for a variable that is never used.
When faced with such warning you can either replace offending variable with _
let _ = io::stdin().read_line(&mut number) ...
or as ker noted just remove the variable altogether
io::stdin().read_line(&mut number)...
The _ will also work in other situation like parameters or in match clauses.
One additional option is to add #[allow(unused_variables)] in the module or crate and disable unused variable warnings. Although, I don't recommend it.

How do I use a macro across module files?

I have two modules in separate files within the same crate, where the crate has macro_rules enabled. I want to use the macros defined in one module in another module.
// macros.rs
#[macro_export] // or not? is ineffectual for this, afaik
macro_rules! my_macro(...)
// something.rs
use macros;
// use macros::my_macro; <-- unresolved import (for obvious reasons)
my_macro!() // <-- how?
I currently hit the compiler error "macro undefined: 'my_macro'"... which makes sense; the macro system runs before the module system. How do I work around that?
Macros within the same crate
New method (since Rust 1.32, 2019-01-17)
foo::bar!(); // works
mod foo {
macro_rules! bar {
() => ()
}
pub(crate) use bar; // <-- the trick
}
foo::bar!(); // works
With the pub use, the macro can be used and imported like any other item. And unlike the older method, this does not rely on source code order, so you can use the macro before (source code order) it has been defined.
Old method
bar!(); // Does not work! Relies on source code order!
#[macro_use]
mod foo {
macro_rules! bar {
() => ()
}
}
bar!(); // works
If you want to use the macro in the same crate, the module your macro is defined in needs the attribute #[macro_use]. Note that macros can only be used after they have been defined!
Macros across crates
Crate util
#[macro_export]
macro_rules! foo {
() => ()
}
Crate user
use util::foo;
foo!();
Note that with this method, macros always live at the top-level of a crate! So even if foo would be inside a mod bar {}, the user crate would still have to write use util::foo; and not use util::bar::foo;. By using pub use, you can export a macro from a module of your crate (in addition to it being exported at the root).
Before Rust 2018, you had to import macro from other crates by adding the attribute #[macro_use] to the extern crate util; statement. That would import all macros from util. This syntax should not be necessary anymore.
Alternative approach as of 1.32.0 (2018 edition)
Note that while the instructions from #lukas-kalbertodt are still up to date and work well, the idea of having to remember special namespacing rules for macros can be annoying for some people.
EDIT: it turns out their answer has been updated to include my suggestion, with no credit mention whatsoever ๐Ÿ˜•
On the 2018 edition and onwards, since the version 1.32.0 of Rust, there is another approach which works as well, and which has the benefit, imho, of making it easier to teach (e.g., it renders #[macro_use] obsolete). The key idea is the following:
A re-exported macro behaves as any other item (function, type, constant, etc.): it is namespaced within the module where the re-export occurs.
It can then be referred to with a fully qualified path.
It can also be locally used / brought into scope so as to refer to it in an unqualified fashion.
Example
macro_rules! macro_name { ... }
pub(crate) use macro_name; // Now classic paths Just Workโ„ข
And that's it. Quite simple, huh?
Feel free to keep reading, but only if you are not scared of information overload ;) I'll try to detail why, how and when exactly does this work.
More detailed explanation
In order to re-export (pub(...) use ...) a macro, we need to refer to it! That's where the rules from the original answer are useful: a macro can always be named within the very module where the macro definition occurs, but only after that definition.
macro_rules! my_macro { ... }
my_macro!(...); // OK
// Not OK
my_macro!(...); /* Error, no `my_macro` in scope! */
macro_rules! my_macro { ... }
Based on that, we can re-export a macro after the definition; the re-exported name, then, in and of itself, is location agnostic, as all the other global items in Rust ๐Ÿ™‚
In the same fashion that we can do:
struct Foo {}
fn main() {
let _: Foo;
}
We can also do:
fn main() {
let _: A;
}
struct Foo {}
use Foo as A;
The same applies to other items, such as functions, but also to macros!
fn main() {
a!();
}
macro_rules! foo { ... } // foo is only nameable *from now on*
use foo as a; // but `a` is now visible all around the module scope!
And it turns out that we can write use foo as foo;, or the common use foo; shorthand, and it still works.
The only question remaining is: pub(crate) or pub?
For #[macro_export]-ed macros, you can use whatever privacy you want; usually pub.
For the other macro_rules! macros, you cannot go above pub(crate).
Detailed examples
For a non-#[macro_export]ed macro
mod foo {
use super::example::my_macro;
my_macro!(...); // OK
}
mod example {
macro_rules! my_macro { ... }
pub(crate) use my_macro;
}
example::my_macro!(...); // OK
For a #[macro_export]-ed macro
Applying #[macro_export] on a macro definition makes it visible after the very module where it is defined (so as to be consistent with the behavior of non-#[macro_export]ed macros), but it also puts the macro at the root of the crate (where the macro is defined), in an absolute path fashion.
This means that a pub use macro_name; right after the macro definition, or a pub use crate::macro_name; in any module of that crate will work.
Note: in order for the re-export not to collide with the "exported at the root of the crate" mechanic, it cannot be done at the root of the crate itself.
pub mod example {
#[macro_export] // macro nameable at `crate::my_macro`
macro_rules! my_macro { ... }
pub use my_macro; // macro nameable at `crate::example::my_macro`
}
pub mod foo {
pub use crate::my_macro; // macro nameable at `crate::foo::my_macro`
}
When using the pub / pub(crate) use macro_name;, be aware that given how namespaces work in Rust, you may also be re-exporting constants / functions or types / modules. This also causes problems with globally available macros such as #[test], #[allow(...)], #[warn(...)], etc.
In order to solve these issues, remember you can rename an item when re-exporting it:
macro_rules! __test__ { ... }
pub(crate) use __test__ as test; // OK
macro_rules! __warn__ { ... }
pub(crate) use __warn__ as warn; // OK
Also, some false positive lints may fire:
from the trigger-happy clippy tool, when this trick is done in any fashion;
from rustc itself, when this is done on a macro_rules! definition that happens inside a function's body: https://github.com/rust-lang/rust/issues/78894
This answer is outdated as of Rust 1.1.0-stable.
You need to add #![macro_escape] at the top of macros.rs and include it using mod macros; as mentioned in the Macros Guide.
$ cat macros.rs
#![macro_escape]
#[macro_export]
macro_rules! my_macro {
() => { println!("hi"); }
}
$ cat something.rs
#![feature(macro_rules)]
mod macros;
fn main() {
my_macro!();
}
$ rustc something.rs
$ ./something
hi
For future reference,
$ rustc -v
rustc 0.13.0-dev (2790505c1 2014-11-03 14:17:26 +0000)
Adding #![macro_use] to the top of your file containing macros will cause all macros to be pulled into main.rs.
For example, let's assume this file is called node.rs:
#![macro_use]
macro_rules! test {
() => { println!("Nuts"); }
}
macro_rules! best {
() => { println!("Run"); }
}
pub fn fun_times() {
println!("Is it really?");
}
Your main.rs would look sometime like the following:
mod node; //We're using node.rs
mod toad; //Also using toad.rs
fn main() {
test!();
best!();
toad::a_thing();
}
Finally let's say you have a file called toad.rs that also requires these macros:
use node; //Notice this is 'use' not 'mod'
pub fn a_thing() {
test!();
node::fun_times();
}
Notice that once files are pulled into main.rs with mod, the rest of your files have access to them through the use keyword.
I have came across the same problem in Rust 1.44.1, and this solution works for later versions (known working for Rust 1.7).
Say you have a new project as:
src/
main.rs
memory.rs
chunk.rs
In main.rs, you need to annotate that you are importing macros from the source, otherwise, it will not do for you.
#[macro_use]
mod memory;
mod chunk;
fn main() {
println!("Hello, world!");
}
So in memory.rs you can define the macros, and you don't need annotations:
macro_rules! grow_capacity {
( $x:expr ) => {
{
if $x < 8 { 8 } else { $x * 2 }
}
};
}
Finally you can use it in chunk.rs, and you don't need to include the macro here, because it's done in main.rs:
grow_capacity!(8);
The upvoted answer caused confusion for me, with this doc by example, it would be helpful too.
Note: This solution does work, but do note as #ineiti highlighted in the comments, the order u declare the mods in the main.rs/lib.rs matters, all mods declared after the macros mod declaration try to invoke the macro will fail.