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

Is it possible to return a container from a loop when the container is used by an iterator?
How to conditionally compile code on target word size in Rust? [duplicate]
the type closure does not fulfill the required lifetime [duplicate]
Return a reference from a callback [duplicate]
Return struct with lifetime for FFI
Why am I getting a “value must be known” error on tuple in a for-loop?
Waiting for a result mapped future
Use different impl when type parameters are the same
Weird characters when using cursive SelectView
How to return a instance of a struct that uses a locally declared variable [duplicate]
Cannot infer an appropriate lifetime when calling a mutable method with references passed as closure arguments
How to access the element at variable index of a tuple?
Iron::new()::http() intercepts stdin
Join futures with limited concurrency
How to get Racer working with Atom?
How do I compile the raw-cpuid crate in rust?

Categories

HOME
artificial-intelligence
firebase
apache-nifi
facebook-messenger
eclipse-plugin
bots
mousemove
code-formatting
plpgsql
websocket
web2py
qooxdoo
moodle-api
navigation
linker
video-streaming
stored-procedures
angular-meteor
minecraft
smartgwt
orange-api
google-cloud-logging
uima
l20n
maven-plugin
cpu-usage
raml
multi-upload
quantitative-finance
ava
vuforia
data-collection
sfml
javax.persistence
es6-modules
location-services
infopath2010
vcenter
progid
advanced-filter
subclassing
code-push
react-intl
audio-converter
bit-shift
non-linear-regression
lightning-workbench
freshdesk
glimpse
google-shopping-api
cefpython
tablespace
dcount
conan
cdo.message
android-4.2-jelly-bean
dojo-build
perforce-integrate
android-syncadapter
fdt
mercurial-extension
accessibilityservice
as3-api
jsr363
perceptron
nette
blank-line
pythonxy
apple
com0com
tree-structure
quercus
azure-xplat-cli
maven-central
neo4jphp
meteorite
armv6
smips
pbkdf2
compiler-flags
vlab
apache-shindig
xsd2code
django-facebook
.net-remoting
unicoins
android-authenticator
arrow
word-frequency
mvcrecaptcha
drawimage
delphi-prism
data-dump
pyjamas
mygeneration
gtktextview

Resources

Database Users
RDBMS discuss
Database Dev&Adm
javascript
java
csharp
php
android
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App