rust


How to call count on an iterator and still use the iterator's items?


parts.count() leads to ownership transfer, so parts can't be used any more.
fn split(slice: &[u8], splitter: &[u8]) -> Option<Vec<u8>> {
let mut parts = slice.split(|b| splitter.contains(b));
let len = parts.count(); //ownership transfer
if len >= 2 {
Some(parts.nth(1).unwrap().to_vec())
} else if len >= 1 {
Some(parts.nth(0).unwrap().to_vec())
} else {
None
}
}
fn main() {
split(&[1u8, 2u8, 3u8], &[2u8]);
}
It is also possible to avoid unnecessary allocations of Vec if you only need to use the first or the second part:
fn split<'a>(slice: &'a [u8], splitter: &[u8]) -> Option<&'a [u8]> {
let mut parts = slice.split(|b| splitter.contains(b)).fuse();
let first = parts.next();
let second = parts.next();
second.or(first)
}
Then if you actually need a Vec you can map on the result:
split(&[1u8, 2u8, 3u8], &[2u8]).map(|s| s.to_vec())
Of course, if you want, you can move to_vec() conversion to the function:
second.or(first).map(|s| s.to_vec())
I'm calling fuse() on the iterator in order to guarantee that it will always return None after the first None is returned (which is not guaranteed by the general iterator protocol).
The other answers are good suggestions to answer your problem, but I'd like to point out another general solution: create multiple iterators:
fn split(slice: &[u8], splitter: &[u8]) -> Option<Vec<u8>> {
let mut parts = slice.split(|b| splitter.contains(b));
let parts2 = slice.split(|b| splitter.contains(b));
let len = parts2.count();
if len >= 2 {
Some(parts.nth(1).unwrap().to_vec())
} else if len >= 1 {
Some(parts.nth(0).unwrap().to_vec())
} else {
None
}
}
fn main() {
split(&[1u8, 2u8, 3u8], &[2u8]);
}
You can usually create multiple read-only iterators. Some iterators even implement Clone, so you could just say iter.clone().count(). Unfortunately, Split isn't one of them because it owns the passed-in closure.
One thing you can do is collect the results of the split in a new owned Vec, like this:
fn split(slice: &[u8], splitter: &[u8]) -> Option<Vec<u8>> {
let parts: Vec<&[u8]> = slice.split(|b| splitter.contains(b)).collect();
let len = parts.len();
if len >= 2 {
Some(parts.iter().nth(1).unwrap().to_vec())
} else if len >= 1 {
Some(parts.iter().nth(0).unwrap().to_vec())
} else {
None
}
}

Related Links

Why is this trait/implementation incompatible - bound lifetime vs concrete lifetime
Cannot move out of `req` because it is borrowed
remove duplicates from vector of custom struct
error with % operator inside closure
How can I open a file with the standard text editor?
How to use multiple variables in routes with Nickel?
sdl2-sys won't compile - could not exec the linker: No such file or directory
Cannot borrow as mutable more than once at a time in one code - but can in another very similar
Forcing a move for an implemented `Copy` type
When do I need to specify explicit lifetimes in Rust?
cannot borrow `self.x` as immutable because `*self` is also borrowed as mutable
Getting sequence of bytes (u8) from a char
How does the lifetime work on constant strings?
Conditionally compile only one module at a time
“macro undefined” error in the macro's own doc test
How to get mutable struct from HashMap?

Categories

HOME
visual-studio
flask
libgdx
android-studio
mpdf
selenium-builder
key
mousemove
greasemonkey
navigation
static-analysis
siesta
nexus3
orc
angular4
ex
squirrel-sql
distributed-computing
twisted
temperature
cocos2d-android
word2vec
xsl-fo
opam
anova
altium-designer
fluent-migrator
candlestick-chart
jstree
tortoisehg
ibm-connections
unmarshalling
jsonresult
actframework
cucumber-junit
sql-execution-plan
devtools
payeezy
polyml
char-pointer
love2d
iscroll
newtons-method
oauth2-playground
ejml
coverage.py
git-tfs
sendinput
common-table-expression
music21
roracle
subforms
watir-webdriver
dtd
emacs25
openerp-6
bpms
yargs
jsonix
data-management
nvda
zynq
traversable
rails-engines
timestamping
jemdoc
persistent-object-store
vim-plugin
textpattern
msgpack
bjam
postal-code
web-api
clarion
nssortdescriptor
window-resize
storing-data
relationships
category-theory
nachos
screwturn
cpu-time
pre
strdup
armv6
particle-swarm
sensormanager
compiler-flags
codahale-metrics
void-pointers
xmlwriter
thejit
pageheap
quartz-core
haiku
data-dump
representation
sql-parametrized-query
libxslt
ninject-interception
tabbarcontroller
oracle-pro-c
rational-unified-process
.net-client-profile
jvm-bytecode

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