rust


How to slice a large Vec<i32> as &[u8]?


I don't know how to slice a Vec as a &[u8] slice?
fn main() {
let v: Vec<i32> = vec![1; 100_000_000];
let v_bytes: &[u8] = ...
}
I ask because I want to write a large Vec to a file so I can read it back at a future time.
You can try std::slice::from_raw_parts:
let v_bytes: &[u8] = unsafe {
std::slice::from_raw_parts(v.as_ptr() as *const u8,
v.len() * std::mem::size_of::<i32>())
};
update
(following answer comments)
You can also wrap this code in a function and have the return value borrow the input vec, so that you use the borrow checker as far as possible.
fn as_u8_slice(v: &[i32]) -> &[u8] {
unsafe {
std::slice::from_raw_parts(v.as_ptr() as *const u8,
v.len() * std::mem::size_of::<i32>())
}
}
I took #swizards answer and ran with it a bit to get the other side of the coin - reading the vector back in:
use std::{mem,slice};
use std::fs::File;
use std::io::{Read,Write};
fn as_u8_slice(v: &[i32]) -> &[u8] {
let element_size = mem::size_of::<i32>();
unsafe {
slice::from_raw_parts(v.as_ptr() as *const u8,
v.len() * element_size)
}
}
fn from_u8(v: Vec<u8>) -> Vec<i32> {
let data = v.as_ptr();
let len = v.len();
let capacity = v.capacity();
let element_size = mem::size_of::<i32>();
// Make sure we have a proper amount of capacity (may be overkill)
assert_eq!(capacity % element_size, 0);
// Make sure we are going to read a full chunk of stuff
assert_eq!(len % element_size, 0);
unsafe {
// Don't allow the current vector to be dropped
// (which would invalidate the memory)
mem::forget(v);
Vec::from_raw_parts(data as *mut i32,
len / element_size,
capacity / element_size)
}
}
fn do_write(filename: &str, v: &[i32]) {
let mut f = File::create(filename).unwrap();
f.write_all(as_u8_slice(&v)).unwrap();
}
fn do_read(filename: &str) -> Vec<i32> {
let mut f = File::open(filename).unwrap();
let mut bytes = Vec::new();
f.read_to_end(&mut bytes).unwrap();
from_u8(bytes)
}
fn main() {
let v = vec![42; 10];
do_write("vector.dump", &v);
let v2 = do_read("vector.dump");
assert_eq!(v, v2);
println!("{:?}", v2)
}

Related Links

A macro with quotes around a metavariable
How do I iterate over elements of a struct in Rust?
Do we need to manually create a destructor for a linked list?
Is it possible to create a macro to implement builder pattern methods?
Safely traversing a directed acyclic graph
Borrowing reference in structure
Is only using references the most idiomatic/efficient for “big” structures?
How to write a method that adds `self` as a mutable trait reference to a collection?
How do I modify a value after matching on it?
Drop a Rust void pointer stored in an FFI
Iterate two vectors and the rest of the larger one
How do I implement Clone/Copy for an enum that contains a String?
Modeling embedded hardware in Rust and how to have multiple mutable references cleanly?
Should I borrow or copy my small data types?
Using pointer casting to change the “type” of data in memory [duplicate]
Export function only to module test?

Categories

HOME
powerbi
tomcat
jms
android-fragments
activemq
message-queue
tabs
lvm
gentelella
azure-mobile-services
log4j2
migrate
getopenfilename
nsstring
cname
outlook-restapi
xbox360
asp.net-core-1.0
renderscript
raml
adminlte
libgit2
multi-upload
device
eclipse-emf
restier
ratio
opentext
nurbs
cellular-network
offline-caching
django-import-export
winsock
steam-web-api
opnet
fotorama
keyboard-layout
bluemixtools
ms-solver-foundation
cargo
game-center
spongycastle
xcglogger
webvtt
gawk
google-identity-toolkit
msg
ftp-client
groovyfx
maximize
seadragon
android-studio-import
cache-manifest
componentart
flow-js
mathematical-expressions
osascript
aho-corasick
webautomation
network-printers
screwturn
fileshare
ctp
saga
illuminate-container
mousemotionlistener
unrealscript
libxml-js
form-for
jacob
bcdedit
onconfigurationchanged
zend-pdf
zotonic
prefuse
opends
gwt-celltable
mvcrecaptcha
3des
libxslt
gaelyk
active-record-query
ninject-interception
fxruby
server-load

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App