github.com/muhammedhassanm/blockchain@v0.0.0-20200120143007-697261defd4d/sawtooth-core-master/perf/sawtooth_perf/src/source.rs (about) 1 /* 2 * Copyright 2017 Intel Corporation 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 * ------------------------------------------------------------------------------ 16 */ 17 18 //! Tools for generating signed batches from a stream of transactions 19 20 extern crate protobuf; 21 22 use std::io::Read; 23 use std::marker::PhantomData; 24 25 use self::protobuf::Message; 26 27 /// Decodes Protocol Buffer messages from a length-delimited input reader. 28 pub struct LengthDelimitedMessageSource<'a, T: 'a> { 29 source: protobuf::CodedInputStream<'a>, 30 phantom: PhantomData<&'a T>, 31 } 32 33 impl<'a, T> LengthDelimitedMessageSource<'a, T> 34 where 35 T: Message, 36 { 37 /// Creates a new `LengthDelimitedMessageSource` from a given reader. 38 pub fn new(source: &'a mut Read) -> Self { 39 let source = protobuf::CodedInputStream::new(source); 40 LengthDelimitedMessageSource { 41 source, 42 phantom: PhantomData, 43 } 44 } 45 46 /// Returns the next set of messages. 47 /// The vector of messages will contain up to `max_msgs` number of 48 /// messages. An empty vector indicates that the source has been consumed. 49 pub fn next(&mut self, max_msgs: usize) -> Result<Vec<T>, protobuf::ProtobufError> { 50 let mut results = Vec::with_capacity(max_msgs); 51 for _ in 0..max_msgs { 52 if self.source.eof()? { 53 break; 54 } 55 56 // read the delimited length 57 let next_len = try!(self.source.read_raw_varint32()); 58 let buf = try!(self.source.read_raw_bytes(next_len)); 59 60 let msg = try!(protobuf::parse_from_bytes(&buf)); 61 results.push(msg); 62 } 63 Ok(results) 64 } 65 }