How to print a Vec without brackets - vector

How can I print a Vec without brackets?
let v = vec![1,2,3];
I want to print it like this:
1 2 3
not like this:
[1,2,3]
What I tried:
let mut v = vec![s; k];
println!("{}", format!("{:?}", v)[1..]);
but I got error:
error[E0277]: the size for values of type `str` cannot be known at compilation time
--> src/main.rs:16:9
|
16 | println!("{}", format!("{:?}", v)[1..]);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time

If you literally just want to print the values, you could do something like this:
fn main() {
let v = vec![1, 2, 3];
v.iter().for_each(|val| print!("{} ", val));
}
If you want to concatenate them into a String, you could do this:
fn main() {
let v = vec![1, 2, 3];
let str = v.iter().map(|val| format!("{}", val)).collect::<Vec<String>>().join(" ");
println!("{}", str);
}

Not quite sure what youre asking... bit if all you need to do is print just like that... you could to this...
fn main() {
let v = [1,2,3];
for x in v {
print!("{} ", x);
}
println!()
}

Related

Why can't this struct method add an element to a vector through a mutable reference?

I have been trying to implement SHA256 as a practice, but I stumbled upon a behavior that I do not fully understand.
I start with a Vec<u8>, where I place the data to be hashed. Then, I pass a mutable reference to the hash function, where it adds the SHA2 padding. The problem is that when the push function is reached within the hash function, it does not add a thing.
I determined this behavior using the debugger, since the program does not crashes, just hangs in the while.
use std::fmt;
struct Sha256 {
state: [u32; 8],
k: [u32; 64]
}
impl fmt::Display for Sha256 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:x?}{:x?}{:x?}{:x?}{:x?}{:x?}{:x?}{:x?}",
self.state[0],self.state[1],self.state[2],self.state[3],
self.state[4],self.state[5],self.state[6],self.state[7]
)
}
}
impl Sha256 {
pub fn new() -> Sha256 {
Sha256 {
state: [
0x6a09e667,
0xbb67ae85,
0x3c6ef372,
0xa54ff53a,
0x510e527f,
0x9b05688c,
0x1f83d9ab,
0x5be0cd19
],
k: [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
]
}
}
pub fn process_block(&mut self, data: &[u8]) {
let mut w = [0u32; 64];
for (i, &d) in data.iter().enumerate() {
let byte = i % 4;
let word = i / 4;
w[word] |= (d as u32) << ((8*(3-byte)) as u32);
}
println!("{:?}", w);
for i in 16..64 {
let s0 = w[i-15].rotate_right(7) ^ w[i-15].rotate_right(18) ^ w[i-15].rotate_right(3);
let s1 = w[i-2].rotate_right(17) ^ w[i-2].rotate_right(19) ^ w[i-2].rotate_right(10);
w[i] = w[i-16].wrapping_add(s0).wrapping_add(w[i-7]).wrapping_add(s1);
}
let mut a = self.state[0];
let mut b = self.state[1];
let mut c = self.state[2];
let mut d = self.state[3];
let mut e = self.state[4];
let mut f = self.state[5];
let mut g = self.state[6];
let mut h = self.state[7];
for i in 0..64 {
let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
let ch = (e & f) ^((!e) & g);
let t1 = h.wrapping_add(s1).wrapping_add(ch).wrapping_add(self.k[i]).wrapping_add(w[i]);
let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
let maj = (a & b)^(a & c)^(b & c);
let t2 = s0.wrapping_add(maj);
h = g;
g = f;
f = e;
e = d.wrapping_add(t1);
d = c;
c = b;
b = a;
a = t1.wrapping_add(t2);
}
self.state[0] = self.state[0].wrapping_add(a);
self.state[1] = self.state[1].wrapping_add(b);
self.state[2] = self.state[2].wrapping_add(c);
self.state[3] = self.state[3].wrapping_add(d);
self.state[4] = self.state[4].wrapping_add(e);
self.state[5] = self.state[5].wrapping_add(f);
self.state[6] = self.state[6].wrapping_add(g);
self.state[7] = self.state[7].wrapping_add(h);
}
pub fn hash(&mut self, v: &mut Vec<u8>) {
v.push(0x80);
while (v.len()%64) < 56 {
v.push(0x00);
}
let size = v.len() as u64;
let mut s_idx = 0;
while s_idx < 8 {
let byte = ((size >> (8*(7-s_idx))) & 0xffu64 ) as u8;
s_idx += 1;
v.push(byte);
}
println!("{:?}", v);
for i in 0..(v.len()/64) {
self.process_block(&v[i*64..(i+1)*64]);
}
}
}
fn main() {
let mut th = Sha256::new();
let mut v = Vec::<u8>::new();
// Sha256::hash(&mut th, &mut v); // This not work
th.hash(&mut v); // Neither do this
println!("{}", th);
}
If I create another function I am able to push data within the function, like this:
fn add_elem(v: &mut Vec<u8>) {
v.push(10);
}
fn main() {
let mut th = Sha256::new();
let mut v = Vec::<u8>::new();
add_elem(&mut v);
th.hash(&mut v);
println!("{}", th);
}
I don't know what I am missing here, because the reference is the same, but it works sometimes and others not.
I am using the Rust 1.59 stable version for Linux and Windows (tested in both systems).
It seems to be a debugger error in this function, since the vector does in fact grow, but it cannot be seen by calling p v in the GDB console.

How do I calculate a multiple factorial using num_bigint in Rust?

I am trying to calculate a factorial of a factorial in Rust using the Num-BigInt library. I've gotten to the point where I can calculate a factorial:
use num_bigint::BigUint;
use num_traits::{One, Zero, FromPrimitive};
fn factorial(n: usize) -> BigUint {
let mut f: BigUint = One::one();
for i in 1..(n+1) {
let bu: BigUint = FromPrimitive::from_usize(i).unwrap();
f = f * bu;
}
f
}
pub fn main() {
println!("Starting calculation...");
println!("{}", factorial(5));
}
I want to do a double factorial, like:
pub fn main() {
println!("Starting calculation...");
println!("{}", factorial(factorial(5)));
}
However, this throws the following error because the data types are different:
error[E0308]: mismatched types
--> src/main.rs:16:30
|
16 | println!("{}", factorial(factorial(5)));
| ^^^^^^^^^^^^ expected `usize`, found struct `BigUint`
How can I repeat this function using BigUint instead of usize?
The problem is that you first want to use a usize and then a BigUint as your function parameter, while your parameter is set to be a usize.
To fix this you should make your factorial function generic and then only allow those types that make sense for your particular method.
I took your example and extended it to allow for all unsigned integer types:
use num_bigint::BigUint;
use num_traits::{One, FromPrimitive, Unsigned};
use num::{Integer, NumCast, ToPrimitive};
fn factorial<N: Unsigned + Integer + ToPrimitive>(n: N) -> BigUint {
let mut f: BigUint = One::one();
let end: usize = NumCast::from(n).unwrap();
for i in 1..(end + 1) {
let bu: BigUint = FromPrimitive::from_usize(i).unwrap();
f = f * bu;
}
f
}
pub fn main() {
println!("Starting calculation...");
println!("{}", factorial(factorial(5 as u32)));
}
This will however lead to not allowing factorial(5), because 5 is treated as an i32 by default, which can be signed. If you wish to allow for signed types and instead fail at runtime you can do something like that:
use num_bigint::BigUint;
use num_traits::{One, FromPrimitive};
use num::{Integer, NumCast, ToPrimitive};
fn factorial<N: Integer + ToPrimitive>(n: N) -> BigUint {
let mut f: BigUint = One::one();
let end: usize = NumCast::from(n).expect("Number too big or negative number used.");
for i in 1..(end + 1) {
let bu: BigUint = FromPrimitive::from_usize(i).unwrap();
f = f * bu;
}
f
}
pub fn main() {
println!("Starting calculation...");
println!("{}", factorial(factorial(5)));
}

Flatten a Map<Vec<u8>, Vec<u8>> into a Vec<u8> and then return it to a Map<Vec<u8>, Vec<u8>>

I've have data in a HashMap<Vec<u8>, Vec<u8>> and I want to write that data to a file as a byte buffer (a single Vec<u8>) and then read it back from the file and reconstruct the HashMap structure.
Is there an established algorithm for flattening and recovering maps like this? I could write metadata into the file to distinguish where the data partitions etc. I can't use structured serialization because of the nature of this project — I am encrypting the data and the file.
You may store this with the following format:
value1_len | value1_bytes | key1_len | key1_bytes | value2_len | value2_bytes | key2_len | key2_bytes | ...
what can be fairly easily done with the standard library (playground):
use std::collections::HashMap;
use std::convert::TryInto;
fn serialize(map: &HashMap<Vec<u8>, Vec<u8>>) -> Vec<u8> {
map.iter().fold(Vec::new(), |mut acc, (k, v)| {
acc.extend(&k.len().to_le_bytes());
acc.extend(k.as_slice());
acc.extend(&v.len().to_le_bytes());
acc.extend(v.as_slice());
acc
})
}
fn read_vec(input: &mut &[u8]) -> Vec<u8> {
let (len, rest) = input.split_at(std::mem::size_of::<usize>());
let len = usize::from_le_bytes(len.try_into().unwrap());
let (v, rest) = rest.split_at(len);
*input = rest;
v.to_vec()
}
fn deserialize(bytes: &Vec<u8>) -> HashMap<Vec<u8>, Vec<u8>> {
let mut map = HashMap::new();
let mut left = &bytes[..];
while left.len() > 0 {
let k = read_vec(&mut left);
let v = read_vec(&mut left);
map.insert(k, v);
}
map
}
fn main() {
let mut map = HashMap::new();
map.insert(vec![1, 2, 3], vec![4, 5, 6]);
map.insert(vec![4, 5, 6], vec![1, 2, 3]);
map.insert(vec![1, 5, 3], vec![4, 2, 6]);
let array = serialize(&map);
let recovered_map = deserialize(&array);
assert_eq!(map, recovered_map);
}

How do I concatenate a vector of integers into a single integer?

I'm trying to concatenate all of the contents of a vector into a single number. This would be like [1, 2, 4] -> 124. Here's what I have right now:
fn sumVector(vec: &Vec<u32>) -> u32 {
return vec.to_owned().concat();
}
This is failing with error
error[E0599]: no method named `concat` found for type `std::vec::Vec<u32>` in the current scope
--> src/lib.rs:2:27
|
2 | return vec.to_owned().concat();
| ^^^^^^ method not found in `std::vec::Vec<u32>`
As said in the comments by Stargateur, you can do:
fn concat(vec: &[u32]) -> u32 {
vec.iter().fold(0, |acc, elem| acc * 10 + elem)
}
You can also write the same function in imperative style:
fn concat(vec: &[u32]) -> u32 {
let mut acc = 0;
for elem in vec {
acc *= 10;
acc += elem;
}
acc
}
You can follow Ortomala Lokni's procedure if your input vector contains single digit integers.
If the vector contains multi-digit integers, the function may not return the intended value. The following concat_new function handles this case.
fn main() {
let a = vec![10_i32, 20, 300];
println!("{:?}", concat_new(&a));
println!("{:?}", concat(&a));
}
fn concat_new(vec: &[i32]) -> i32 {
let t = vec.iter().fold("".to_string(), |acc, x| acc + &x.to_string());
t.parse::<i32>().unwrap()
}
fn concat(vec: &[i32]) -> i32 {
vec.iter().fold(0, |acc, elem| acc * 10 + elem)
}

How to increment every number in a vector without the error "cannot borrow as mutable more than once at a time"?

This code is supposed to increment each value in a vector by 1:
fn main() {
let mut v = vec![2, 3, 1, 4, 2, 5];
let i = v.iter_mut();
for j in i {
*j += 1;
println!("{}", j);
}
println!("{:?}", &mut v);
}
It doesn't work because of the borrowing rules of Rust:
error[E0499]: cannot borrow `v` as mutable more than once at a time
--> src/main.rs:8:27
|
3 | let i = v.iter_mut();
| - first mutable borrow occurs here
...
8 | println!("{:?}", &mut v);
| ^ second mutable borrow occurs here
9 | }
| - first borrow ends here
How can I accomplish this task?
Don't store the mutable iterator; use it directly in the loop instead:
fn main() {
let mut v = vec![2, 3, 1, 4, 2, 5];
for j in v.iter_mut() { // or for j in &mut v
*j += 1;
println!("{}", j);
}
println!("{:?}", &v); // note that I dropped mut here; it's not needed
}
Your code will work as-is in a future version of Rust thanks to non-lexical lifetimes:
#![feature(nll)]
fn main() {
let mut v = vec![2, 3, 1, 4, 2, 5];
let i = v.iter_mut();
for j in i {
*j += 1;
println!("{}", j);
}
println!("{:?}", &mut v);
}
playground
You call also just use map and collect like,
>> let mut v = vec![5,1,4,2,3];
>> v.iter_mut().map(|x| *x += 1).collect::<Vec<_>>();
>> v
[6, 2, 5, 3, 4]
In my opinion the simplest and most readable solution:
#![feature(nll)]
fn main() {
let mut v = vec![2, 3, 1, 4, 2, 5];
for i in 0..v.len() {
v[i] += 1;
println!("{}", j);
}
println!("{:?}", v);
}

Resources