How do I compile the raw-cpuid crate in rust? - rust

I am using raw-cpuid crate for a project. It uses raw::Slice structure in processor_brand_string() function of ExtendedFunctionInfo structure.
let slice = raw::Slice { data: brand_string_start, len: 3*4*4 };
The above statement doesn't compile. It aborts with this error
cannot find struct, variant or union type `Slice` in module `raw`
--> /home/ubuntu/.cargo/registry/src/github.com-1ecc6299db9ec823/raw-cpuid-2.0.0/src/lib.rs:435:25
|
435 | let slice = raw::Slice { data: brand_string_start, len: 3*4 };
| ^^^^^^^^^^ not found in `raw`
The crate uses no_std attribute. The Rust book says
When weโ€™re using the standard library, Rust automatically brings std
into scope, allowing you to use its features without an explicit
import. By the same token, when using #![no_std], Rust will bring core
into scope for you, as well as its prelude. This means that a lot of
code will Just Work.
I checked the core crate and it has Slice structure in the raw module. I have searched for any resolution of this error but I couldn't find one and me being new to Rust am unable to figure out what to do. I don't think many have used this crate but any help is appreciated. Thanks

Related

Code and feature conditional on Rust version or specific compiler feature

Rust 1.63 stabilized const std::sync::Mutex::new(). Till date to have global flag preventing parallel execution would look like (example):
use once_cell::sync::Lazy;
static GLOBAL_FLAG: Lazy<Mutex<()>> = Lazy::new(Default::default);
while in since 1.63 it can look like this and the dependency isn't required anymore in Cargo.toml:
static GLOBAL_FLAG: Mutex<()> = Mutex::new(());
Now, the question is how to make use of both conditionally, depending on either:
which version of the compiler is used to build the crate
or
whether the feature is stable (I struggle to find it's correct name at the moment)?
I was looking at cfg_rust_features crate, but the part where dependency isn't required by Cargo.toml remains mystery. Any hints welcome.
This is typically accomplished by:
Detecting the Rust version (using rustversion/rustc_version) or the required feature (using autocfg),
Making the fallback dependency (once_cell) optional, and
Emitting an error if the required Rust feature is missing and the fallback dependency is also missing.
For example, using rustversion:
#[rustversion::since(1.63)]
mod private {
use std::sync::Mutex;
pub static GLOBAL_FLAG: Mutex<()> = Mutex::new(());
}
#[rustversion::before(1.63)]
#[cfg(feature = "once_cell")]
mod private {
use once_cell::sync::Lazy;
use std::sync::Mutex;
pub static GLOBAL_FLAG: Lazy<Mutex<()>> = Lazy::new(Default::default);
}
#[rustversion::before(1.63)]
#[cfg(not(feature = "once_cell"))]
compile_error!(
"The \"once_cell\" feature must be enabled for Rust compiler versions prior to 1.63."
);
When compiling on 1.62 without once_cell, this emits
error: The "once_cell" feature must be enabled for Rust compiler versions prior to 1.63.
--> src/main.rs:18:1
|
18 | / compile_error!(
19 | | "The \"once_cell\" feature must be enabled for Rust compiler versions prior to 1.63."
20 | | );
| |_^
Note: the use of mod private seen above is not strictly necessary, but it reduces the number of attributes and ensures that the relevant compile error is the only error emitted. You can pub use private::GLOBAL_FLAG to put it back in scope.

What is the built-in `#[main]` attribute?

I have been using the #[tokio::main] macro in one of my programs. After importing main and using it unqualified, I encountered an unexpected error.
use tokio::main;
#[main]
async fn main() {}
error[E0659]: `main` is ambiguous
--> src/main.rs:3:3
|
3 | #[main]
| ^^^^ ambiguous name
|
= note: ambiguous because of a name conflict with a builtin attribute
= note: `main` could refer to a built-in attribute
I've been scouring the documentation but I haven't been able to find this built-in #[main] attribute described anywhere. The Rust Reference contains an index of built-in attributes. The index doesn't include #[main], though it does include an attribute named #[no_main].
I did a search of the rustlang/rust repository, and found some code that seems related, but it seems to use a pair of macros named #[start] and #[rustc_main], with no mention of #[main] itself. (Neither of those macros appears to be usable on stable, with #[start] emitting an error that it's unstable, and #[rustc_main] emitting an error that it's only meant for internal use by the compiler.)
My guess from the name would have been that it's meant to mark a different function as an entry-point instead of main, but it also doesn't seem to do that:
#[main]
fn something_else() {
println!("this does not run");
}
fn main() {
println!("this runs");
}
Rust Analyzer didn't have much to offer:
What does the built-in #[main] attribute do, aside from conflicting with my imports? ๐Ÿ˜‰
#[main] is an old, unstable attribute that was mostly removed from the language in 1.53.0. However, the removal missed one line, with the result you see: the attribute had no effect, but it could be used on stable Rust without an error, and conflicted with imported attributes named main. This was a bug, not intended behaviour. It has been fixed as of nightly-2022-02-10 and 1.59.0-beta.8. Your example with use tokio::main; and #[main] can now run without error.
Before it was removed, the unstable #[main] was used to specify the entry point of a program. Alex Crichton described the behaviour of it and related attributes in a 2016 comment on GitHub:
Ah yes, we've got three entry points. I.. think this is how they work:
First, #[start], the receiver of int argc and char **argv. This is literally the symbol main (or what is called by that symbol generated in the compiler).
Next, there's #[lang = "start"]. If no #[start] exists in the crate graph then the compiler generates a main function that calls this. This functions receives argc/argv along with a third argument that is a function pointer to the #[main] function (defined below). Importantly, #[lang = "start"] can be located in a library. For example it's located in the standard library (libstd).
Finally, #[main], the main function for an executable. This is passed no arguments and is called by #[lang = "start"] (if it decides to). The standard library uses this to initialize itself and then call the Rust program. This, if not specified, defaults to fn main at the top.
So to answer your question, this isn't the same as #[start]. To answer your other (possibly not yet asked) question, yes we have too many entry points.

What do `use raw` and `raw: raw::git_buf` from the git2-rs wrapper mean?

I'm trying to build a safe wrapper over some native Rust-C bindings. I'm referencing the git2-rs codebase and I ran into the following usage:
use raw;
use util::Binding;
pub struct Buf {
raw: raw::git_buf,
}
What are use raw and raw: raw::git_buf doing? I think this has to do with std::raw.
raw is the identifier that git2-rs chooses to give to the libgit2_sys crate:
extern crate libgit2_sys as raw;
use raw is thus equivalent to use libgit2_sys and conceptually the same as use regex or use itertools โ€” it simply brings the crate into scope in this module.
Please re-read Bringing Paths into Scope with the use Keyword from The Rust Programming Language for a refresher on the use statement.
raw: raw::git_buf defines the field raw of the struct Buf to be of the type raw::git_buf. This is equivalent to raw: libgit2_sys::git_buf and conceptually the same as raw: String or raw: i32.
Please re-read Defining and Instantiating Structs for a refresher on how structs are defined.

How to link to other fns/structs/enums/traits in rustdoc?

I'm building a Rust library and want to give it some polish. In the rustdoc, I'd sometimes like to link to other parts of the library within the docs, e.g. fns, traits or structs. What is the official syntax for this?
As of Rust 1.48, you can now rely on RFC 1946. This adds the concept of intra-documentation links. This allows using Rust paths as the URL of a link:
[Iterator](std::iter::Iterator)
[Iterator][iter], and somewhere else in the document: [iter]: std::iter::Iterator
[Iterator], and somewhere else in the document: [Iterator]: std::iter::Iterator
The RFC also introduces "Implied Shortcut Reference Links". This allows leaving out the link reference, which is then inferred automatically.
[std::iter::Iterator], without having a link reference definition for Iterator anywhere else in the document
[`std::iter::Iterator`], without having a link reference definition for Iterator anywhere else in the document (same as previous style but with back ticks to format link as inline code)
As a concrete example, this source code:
//! Check out [ExampleStruct], especially [this
//! method](ExampleStruct::foo), but [the trait method][trait] is also
//! cool. There is also [an enum variant you can
//! use](nested::ExampleEnum::Beta).
//!
//! [trait]: ExampleTrait::bar
pub struct ExampleStruct;
impl ExampleStruct {
pub fn foo(&self) {}
}
pub trait ExampleTrait {
fn bar();
}
pub mod nested {
pub enum ExampleEnum {
Alpha,
Beta,
}
}
Produces this documentation:
Specifically, this HTML is generated:
<p>Check out ExampleStruct, especially this method, but the trait method is also cool. There is also an enum variant you can use.</p>
As of Rust 1.48, Rustdoc now supports direct intra-doc links.
Pre Rust 1.48:
Rustdoc seems to generate mostly deterministic filenames for constituent elements of a crate. Therefore if you have an enum named Complex you can generally link to it using:
[Complex](enum.Complex.html)
Similarly a struct called Point would look like:
[Point](struct.Point.html)
This should carry over to most definitions (fn, trait, and so on).
For referencing elements of a crate at different nesting levels, you can use relative paths (where each module is its own folder):
[Point](../model/struct.Point.html)
or use absolute paths:
[Point](/crate_name/model/struct.Point.html)
More of these "conventions", including anchors for specific fields, etc., can be deduced if one builds docs (cargo doc --no-deps --open) and navigates to the field or item they want and takes note of the URL. Remember that only pub items are published to docs.
If one wants to link some specific part of a struct e.g., a method named foo in the same struct (using stable rust, not nightly)
[foo](#method.foo)
or if it is in another struct
[foo](struct.OtherStruct.html#method.foo)
In Rust 1.49 nightly it works (1.48 stable not released yet):
[super::structs::WebApiResponse]
[mycrate::structs::WebApiResponse]
etc.
Read here
Since the documentation is written in Markdown, just use the Markdown syntax for Hyperlinks; i.e.
[anchor text](URL)
Also, take a look at this: https://doc.rust-lang.org/book/documentation.html

Unresolved import from_str

How do I use from_str ? I have the snippet
let base: u32 = from_str::<u32>(&var)
and get the error
Error: unresolved name from_str
So I googled this error and found this, so I tried adding the following
use std::u32;
use std::from_str::FromStr
But now I get
Error: unresolved import `std::from_str::FromStr` could not from `from_str` in `std`
According to this github issue, I need to include this yet rust can't find it. What's going on? Here's a super simple program which gives me those errors
use std::u32;
use std::from_str::FromStr;
fn main() {
let my_str = "String".to_string();
let base: u32 = from_str(&my_str);
}
This is such a trivial issue and yet these resources are only showing me how to get more errors.
Use the docs to search for from_str. They show that the FromStr trait is in std::str now, not std::from_str. (April 2014 is a long time ago in Rust terms, being well before Rust 1.0.0.)
FromStr should not be used directly in general anyway; you should use str.parse method instead: my_str.parse::<u32>(). Remember that it returns a Result, because the string might just not contain a number.

Resources