Use slice.chunks

This commit is contained in:
arkpar 2016-03-14 00:41:25 +01:00
parent 45c3600d5a
commit 615e03542e

View File

@ -18,7 +18,6 @@ use bytes::Bytes;
use std::net::SocketAddr; use std::net::SocketAddr;
use std::collections::{HashSet, HashMap, BTreeMap, VecDeque}; use std::collections::{HashSet, HashMap, BTreeMap, VecDeque};
use std::mem; use std::mem;
use std::cmp;
use std::default::Default; use std::default::Default;
use mio::*; use mio::*;
use mio::udp::*; use mio::udp::*;
@ -420,24 +419,19 @@ impl Discovery {
} }
fn prepare_neighbours_packets(nearest: &[NodeEntry]) -> Vec<Bytes> { fn prepare_neighbours_packets(nearest: &[NodeEntry]) -> Vec<Bytes> {
let mut packets = Vec::new();
let mut rlp = RlpStream::new_list(1);
let limit = (MAX_DATAGRAM_SIZE - 109) / 90; let limit = (MAX_DATAGRAM_SIZE - 109) / 90;
let mut count = cmp::min(limit, nearest.len()); let chunks = nearest.chunks(limit);
rlp.begin_list(count); let packets = chunks.map(|c| {
for n in 0 .. nearest.len() { let mut rlp = RlpStream::new_list(1);
rlp.begin_list(4); rlp.begin_list(c.len());
nearest[n].endpoint.to_rlp(&mut rlp); for n in 0 .. c.len() {
rlp.append(&nearest[n].id); rlp.begin_list(4);
count -= 1; c[n].endpoint.to_rlp(&mut rlp);
if count == 0 { rlp.append(&c[n].id);
packets.push(rlp.out());
rlp = RlpStream::new_list(1);
count = cmp::min(limit, nearest.len() - n);
rlp.begin_list(count);
} }
} rlp.out()
packets });
packets.collect()
} }
fn on_neighbours(&mut self, rlp: &UntrustedRlp, _node: &NodeId, from: &SocketAddr) -> Result<Option<TableUpdates>, NetworkError> { fn on_neighbours(&mut self, rlp: &UntrustedRlp, _node: &NodeId, from: &SocketAddr) -> Result<Option<TableUpdates>, NetworkError> {
@ -529,11 +523,12 @@ mod tests {
} }
let packets = Discovery::prepare_neighbours_packets(&nearest); let packets = Discovery::prepare_neighbours_packets(&nearest);
assert_eq!(packets.len(), 76); assert_eq!(packets.len(), 77);
for p in &packets { for p in &packets[0..76] {
assert!(p.len() > 1280/2); assert!(p.len() > 1280/2);
assert!(p.len() <= 1280); assert!(p.len() <= 1280);
} }
assert!(packets.last().unwrap().len() > 0);
} }
#[test] #[test]