How to include a text file along with a crate installation [duplicate] - rust

This question already has answers here:
Is there a good way to include external resource data into Rust source code?
(1 answer)
How to embed resources in Rust executable?
(2 answers)
How do I access assets included in a Rust/Cargo project installed via `cargo install`?
(2 answers)
How to create an in-memory object that can be used as a Reader, Writer, or Seek in Rust?
(3 answers)
Closed 3 years ago.
My program works as expected with my local machine. It prints random lines from a text file in the vein of the Emacs "Spook" amusement (M-x spook). The text file is located in src/spook.lines.
C:\Users\datan>spooks
domestic Eiffel Tower Euzkadi Ta Askatasuna Euzkadi Ta Askatasuna minefield
C:\Users\datan>spooks
Uzi White House secret Sivi Vukovi divers
C:\Users\datan>spooks
Hizb-i-Islami smallpox US Airways SWAT plague
C:\Users\datan>
But if I publish it as a crate and install it, the text file is not found (because it is not in src/spook.lines if the program is installed from crates.io):
C:\Users\datan>docker run -it rust bash
Unable to find image 'rust:latest' locally
latest: Pulling from library/rust
16ea0e8c8879: Pull complete
50024b0106d5: Pull complete
ff95660c6937: Pull complete
9c7d0e5c0bc2: Pull complete
29c4fb388fdf: Pull complete
ee0ab7fd0ac4: Pull complete
Digest: sha256:d8e2b124d6f4fcdf977bf7e6cfbda87fa5061b0c1933742699ee5131444217c9
Status: Downloaded newer image for rust:latest
root#137111b4d94c:/# cargo install spooks
Updating crates.io index
Downloaded spooks v0.1.0
Downloaded 1 crate (19.0 KB) in 1.60s
Installing spooks v0.1.0
Downloaded getopts v0.2.21
Downloaded rand v0.7.2
Downloaded rand_chacha v0.2.1
Downloaded easy_reader v0.5.0
Downloaded getrandom v0.1.13
Downloaded rand_core v0.5.1
Downloaded unicode-width v0.1.7
Downloaded libc v0.2.66
Downloaded c2-chacha v0.2.3
Downloaded fnv v1.0.6
Downloaded cfg-if v0.1.10
Downloaded ppv-lite86 v0.2.6
Compiling libc v0.2.66
Compiling getrandom v0.1.13
Compiling cfg-if v0.1.10
Compiling ppv-lite86 v0.2.6
Compiling fnv v1.0.6
Compiling unicode-width v0.1.7
Compiling getopts v0.2.21
Compiling c2-chacha v0.2.3
Compiling rand_core v0.5.1
Compiling rand_chacha v0.2.1
Compiling rand v0.7.2
Compiling easy_reader v0.5.0
Compiling spooks v0.1.0
Finished release [optimized] target(s) in 22.15s
Installing /usr/local/cargo/bin/spooks
Installed package `spooks v0.1.0` (executable `spooks`)
root#137111b4d94c:/# spooks
(no output because src/spook.lines is not there)
The way I include the file is:
let file = File::open("src/spook.lines")?;
Why can I not just tell the cargo/crate packaging to include the text file? What is the preferred way? I mean even if I include the file in a certain directory then it would not be in the PATH of the execution because the program might be run from anywhere.

You can use the include_str! macro.
fn main() {
let my_str = include_str!("spanish.in");
assert_eq!(my_str, "adiĆ³s\n");
print!("{}", my_str);
}
https://doc.rust-lang.org/std/macro.include_str.html

Related

cargo run/build is stuck on last file

When running cargo build or cargo run on a specific rust project (base_names), it gets stuck on the last file. Output:
Compiling autocfg v1.1.0
Compiling proc-macro2 v1.0.47
Compiling quote v1.0.21
Compiling unicode-ident v1.0.5
Compiling proc-macro-hack v0.5.19
Compiling syn v1.0.102
Compiling radium v0.6.2
Compiling tap v1.0.1
Compiling funty v1.2.0
Compiling lazy_static v1.4.0
Compiling primes v0.3.0
Compiling wyz v0.4.0
Compiling num-traits v0.2.15
Compiling num-integer v0.1.45
Compiling num-bigint v0.4.3
Compiling num-rational v0.4.1
Compiling num-iter v0.1.43
Compiling bitvec v0.22.3
Compiling num-complex v0.4.2
Compiling num v0.4.0
Compiling fraction v0.12.0
Compiling arr_macro_impl v0.1.3
Compiling arr_macro v0.1.3
Compiling base_names v0.1.0 (/home/max/Documents/Projects/base_names)
Building [=========================> ] 43/44: base_names(bin)
I've tried:
cargo clean
rustup update
pkill cargo
pkill rls
running from vscode and terminal
trying existing rust projects (they work fine, so it's project-specific)
creating a new rust project and copying in Cargo.toml + the contents of src
Environment: Linux (Fedora Workstation 36)
Cargo.toml contents:
[package]
name = "base_names"
version = "0.1.0"
edition = "2021"
[dependencies]
primes = "0.3.0"
fraction = "0.12.0"
bitvec = "0.22.3"
arr_macro = "0.1.3"
Thanks to Locke for figuring it out. I used the arr_macro package to write
arr![Default::default(); 100_000]
which expands into 100 000 instances of Default::default(), making compilation take too long.
For cases where:
you need a list of structs
the generator needs access to the previous structs
the trait Copy can't be implemented on your struct
you should use a Vec instead.

Rust build error: unknown `--json` option `future-incompat`

I am trying to build a basic application for the Adafruit CLUE using Rust.
When using the peripheral access crate (PAC) everything works fine, but I would like to use the HAL crate from Nordic Semiconductors.
I set up a very basic project which uses their nrf52840-hal crate. When running cargo build, I get the following error (full build log with --verbose):
Updating crates.io index
Compiling semver-parser v0.7.0
Compiling cortex-m v0.7.4
Compiling proc-macro2 v1.0.37
Compiling nb v1.0.0
Compiling unicode-xid v0.2.3
Compiling syn v1.0.92
Compiling vcell v0.1.3
Compiling void v1.0.2
Compiling bitfield v0.13.2
Compiling cortex-m-rt v0.7.1
Compiling critical-section v0.2.7
Compiling typenum v1.15.0
info: syncing channel updates for 'nightly-2021-08-18-x86_64-unknown-linux-gnu'
Compiling az v1.2.0
Compiling nrf52840-pac v0.11.0
info: latest update on 2021-08-18, rust version 1.56.0-nightly (30a0a9b69 2021-08-17)
Compiling fixed v1.15.0
Compiling cfg-if v1.0.0
info: component 'rust-src' is up to date
info: component 'rust-std' for target 'riscv32imac-unknown-none-elf' is up to date
info: component 'rust-std' for target 'riscv32imc-unknown-none-elf' is up to date
info: component 'rust-std' for target 'thumbv6m-none-eabi' is up to date
info: component 'rust-std' for target 'thumbv7em-none-eabi' is up to date
info: component 'rustfmt' for target 'x86_64-unknown-linux-gnu' is up to date
warning: Force-skipping unavailable component 'rust-std-avr-specs/avr-atmpeg328p.json'
Compiling bare-metal v1.0.0
error: unknown `--json` option `future-incompat`
Compiling half v1.8.2
error: could not compile `critical-section`
warning: build failed, waiting for other jobs to finish...
error: build failed
I am using rustup with the stable toolchain on Ubuntu 20.04 (using nighly 2022-05-03 does not change anything to the error message). Rustup version output is:
rustup 1.24.3 (ce5817a94 2021-05-31)
info: This is the version for the rustup toolchain manager, not the rustc compiler.
info: The currently active `rustc` version is `rustc 1.60.0 (7737e0b5c 2022-04-04)`
The full project is available here.
My .cargo/config.toml file is:
[build]
target = "thumbv7em-none-eabihf"
rustflags = [
"-C", "link-arg=-Tlink.x",
]
The Cargo.toml is:
[package]
name = "hal-test"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
cortex-m-rt = "0.7.1"
nrf52840-hal = "0.15.0"
panic-halt = "0.2.0"
and the src/main.rs file is:
#![no_std]
#![no_main]
use panic_halt as _;
#[cortex_m_rt::entry]
fn main() -> ! {
loop {}
}
I tried to go through the dependency tree but I failed to find where this future-incompat option is added, given that it is passed plenty of times to rustc and it succeeds.
I would appreciate any pointers as to where to look further.
Update 2022-05-06: building the project with the exact same toolchain version on Ubuntu 21.04 works, I'll have to investigate further.
The issue was fixed by switching away from the rustup snap and using the recommended installation method of running the shell script (https://www.rust-lang.org/tools/install).

Cargo: "No such file or directory" error when compiling a Rust project

I'm trying to build a Rust project with cargo (on Ubuntu 20.04), and it seems I'm running into an error when compiling some of the dependencies.
I run cargo build --release, all of the external crates are downloaded, then it begins compiling some of them, but eventually runs into the error below:
> cargo build --release
Updating crates.io index
Downloaded ansi_term v0.12.1
Downloaded phf_generator v0.7.24
Downloaded cmake v0.1.48
...
Downloaded 95 crates (6.9 MB) in 2.51s (largest was `wabt-sys` at 2.6 MB)
Compiling libc v0.2.112
...
Compiling unicode-width v0.1.9
error: couldn't create a temp dir: No such file or directory (os error 2) at path "/home/user/.cargo/registry/src/github.com-1ecc6299db9ec823/cfg-if-1.0.0/home/user/rustcH0KskO"
...
And I get the exact same error for 15 other packages. It's obvious why the path wouldn't exist, but I'm not sure where to begin fixing this issue.
I've tried uninstalling and reinstalling Rust, but I'm new to the language and not sure what to do beyond that, so help is much appreciated. Thanks!
I linked it above, but the project in question is https://github.com/iden3/circom.

llvm-sys - Didn't find usable system-wide LLVM

I'm trying to learn LLVM to make a programming language using Rust. I am using the llvm-sys crate that wraps around the LLVM API.
I have installed LLVM : LLVM-8.0.0-win64
My dependencies in cargo.toml
[dependencies]
llvm-sys = "80.1.1"
When I run cargo run I get the following error,
Updating crates.io index
Compiling memchr v2.2.1
Compiling lazy_static v1.4.0
Compiling regex-syntax v0.6.12
Compiling semver-parser v0.7.0
Compiling libc v0.2.65
Compiling cc v1.0.47
Compiling thread_local v0.3.6
Compiling semver v0.9.0
Compiling aho-corasick v0.7.6
Compiling regex v1.3.1
Compiling llvm-sys v80.1.1
error: failed to run custom build command for `llvm-sys v80.1.1`
Caused by:
process didn't exit successfully: `C:\Users\Name\Desktop\Carbon\carbon-lang\target\debug\build\llvm-sys-ed5d351b1ae6a41b\build-script-build` (exit code: 101)
--- stdout
cargo:rerun-if-env-changed=LLVM_SYS_80_PREFIX
cargo:rerun-if-env-changed=LLVM_SYS_80_IGNORE_BLACKLIST
cargo:rerun-if-env-changed=LLVM_SYS_80_STRICT_VERSIONING
cargo:rerun-if-env-changed=LLVM_SYS_80_NO_CLEAN_CFLAGS
cargo:rerun-if-env-changed=LLVM_SYS_80_USE_DEBUG_MSVCRT
cargo:rerun-if-env-changed=LLVM_SYS_80_FFI_WORKAROUND
Didn't find usable system-wide LLVM.
--- stderr
thread 'main' panicked at 'Failed to execute "C:\\Program Files\\LLVM\\bin\\llvm-config": Os { code: 2, kind: NotFound, message: "The system cannot find the file specified." }', src\libcore\result.rs:1165:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace.
But I have set the LLVM_SYS_80_PREFIX as C:\Program Files\LLVM which is where the bin folder is.
Should the llvm-config file be separately installed? I could not find it anywhere.
FYI: I'm on Windows 10
Thanks for the help!
llvm-config is a developer-side tool, it is not shipped with binaries. You need to build LLVM from sources.
LLVM is not shipped with a component called llvm-config.exe, I am not sure how to bypass though.

According to xargo my code has built successfully, but there's no binary in target, why?

I'm brand new to Rust so forgive me if I don't know the lingo/tools yet. I'm trying to get an STM32F4 to blink an LED, and I think the code is right, but when I build it xargo doesn't generate a binary or any sort of error. My code is:
#![feature(proc_macro)] // <- IMPORTANT! Feature gate for procedural macros
#![no_std]
extern crate cortex_m;
extern crate cortex_m_rtfm as rtfm;
extern crate stm32f40x;
use cortex_m::peripheral::SystClkSource;
use rtfm::{app, Threshold};
app! {
device: stm32f40x,
resources: {},
tasks: {
SYS_TICK: {
path: toggle,
resources: [GPIOC],
},
},
}
fn init(p: init::Peripherals, _r: init::Resources) {
// TODO: initialize the GPIO
p.SYST.set_clock_source(SystClkSource::Core);
p.SYST.set_reload(8_000_000); // 1s?
p.SYST.enable_interrupt();
p.SYST.enable_counter();
}
fn idle() -> ! {
loop {
rtfm::wfi();
}
}
fn toggle(_t: &mut Threshold, r: SYS_TICK::Resources) {
**r.GPIOC.odr.modify(|r, w| w.odr13().bit(!r.odr13().bit()));
}
The Cargo.toml file is
[package]
name = "sign_firmware"
version = "0.0.1"
authors = ["teryret"]
categories = ["embedded", "no-std"]
description = "With any luck this will cause an STM32F4 based board to drive a few thousand LEDs."
keywords = ["arm", "cortex-m"]
license = "MIT OR Apache-2.0"
repository = "TODO"
[dependencies]
cortex-m = "*"
cortex-m-rt = "*"
cortex-m-rtfm = "*"
stm32f40x = "*"
[profile]
[profile.release]
debug = true
lto = true
[target.arm-none-linux-gnueabihf]
ar = "arm-linux-gnueabihf-gcc-ar"
linker = "arm-linux-gnueabihf-gcc"
And when I run xargo build --release in the docker image I set up to contain all the dependencies and whatnot it says:
teryret#bee ~/d/rtfm> ./build
Compiling core v0.0.0 (file:///usr/local/rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/src/libcore)
Finished release [optimized + debuginfo] target(s) in 12.82 secs
Updating git repository `https://github.com/rust-lang-nursery/compiler-builtins`
Compiling compiler_builtins v0.1.0 (https://github.com/rust-lang-nursery/compiler-builtins#f5532b22)
Finished release [optimized + debuginfo] target(s) in 2.12 secs
warning: unused manifest key: target.arm-none-linux-gnueabihf.ar
warning: unused manifest key: target.arm-none-linux-gnueabihf.linker
Downloading cortex-m-rtfm v0.2.1
Downloading stm32f40x v0.5.0
Downloading cortex-m-rt v0.3.6
Downloading cortex-m v0.3.1
Downloading rtfm-core v0.1.0
Downloading static-ref v0.2.1
Downloading cortex-m-rtfm-macros v0.2.0
Downloading error-chain v0.10.0
Downloading quote v0.3.15
Downloading rtfm-syntax v0.1.0
Downloading syn v0.11.11
Downloading unicode-xid v0.0.4
Downloading synom v0.11.3
Downloading volatile-register v0.2.0
Downloading bare-metal v0.1.1
Downloading aligned v0.1.1
Downloading vcell v0.1.0
Downloading r0 v0.2.2
Compiling r0 v0.2.2
Compiling libc v0.2.33
Compiling vcell v0.1.0
Compiling quote v0.3.15
Compiling cc v1.0.3
Compiling sign_firmware v0.0.1 (file:///usr/src/myapp)
Compiling cortex-m-rt v0.3.6
Compiling cortex-m-rtfm v0.2.1
Compiling cfg-if v0.1.2
Compiling rustc-demangle v0.1.5
Compiling bare-metal v0.1.1
Compiling unicode-xid v0.0.4
Compiling aligned v0.1.1
Compiling cortex-m v0.3.1
Compiling static-ref v0.2.1
Compiling volatile-register v0.2.0
Compiling synom v0.11.3
Compiling rtfm-core v0.1.0
Compiling syn v0.11.11
Compiling stm32f40x v0.5.0
Compiling backtrace-sys v0.1.16
Compiling backtrace v0.3.4
Compiling error-chain v0.10.0
Compiling rtfm-syntax v0.1.0
Compiling cortex-m-rtfm-macros v0.2.0
Finished release [optimized + debuginfo] target(s) in 47.2 secs
While lots of stuff is generated in target/ none of it is a binary I can flash onto the board. Any idea why? I mean, it's got to be something simple, but I don't have the experience to know where to look.
In the tutorial you were following, all of the examples are in an "examples" directory. You can build these using the --example argument, as shown in the tutorial:
xargo build --example hello
If this is your primary program, however, you will want to put your code in "src/main.rs", allowing just:
xargo build
If you have multiple executables, you can also specify that.

Resources