Skip to content
This repository was archived by the owner on Jun 30, 2022. It is now read-only.

Commit c7f4e24

Browse files
authored
Add attribute iterator (#14)
* Add attribute iterator * remove copy-pasta comment
1 parent 1c1c283 commit c7f4e24

File tree

2 files changed

+35
-18
lines changed

2 files changed

+35
-18
lines changed

examples/get_accounts.rs

Lines changed: 1 addition & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -20,18 +20,6 @@ use std::{
2020
str::FromStr
2121
};
2222

23-
fn get_attr_str<'a,T>( ite: & mut T ) -> String
24-
where T : Iterator<Item=& 'a u8>
25-
{
26-
let mut len = *ite.next().unwrap() as usize;
27-
let mut val = String::with_capacity( len );
28-
while len > 0 {
29-
val.push( *ite.next().unwrap() as char );
30-
len -= 1;
31-
}
32-
return val
33-
}
34-
3523
fn get_price_type( ptype: &PriceType ) -> &'static str
3624
{
3725
match ptype {
@@ -78,13 +66,8 @@ fn main() {
7866

7967
// print key and reference data for this Product
8068
println!( "product_account .. {:?}", prod_pkey );
81-
let mut psz = prod_acct.size as usize - PROD_HDR_SIZE;
82-
let mut pit = (&prod_acct.attr[..]).iter();
83-
while psz > 0 {
84-
let key = get_attr_str( &mut pit );
85-
let val = get_attr_str( &mut pit );
69+
for (key, val) in prod_acct.iter() {
8670
println!( " {:.<16} {}", key, val );
87-
psz -= 2 + key.len() + val.len();
8871
}
8972

9073
// print all Prices that correspond to this Product

src/lib.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,12 @@ pub struct Product
128128
pub attr : [u8;PROD_ATTR_SIZE]
129129
}
130130

131+
impl Product {
132+
pub fn iter(&self) -> AttributeIter {
133+
AttributeIter { attrs: &self.attr }
134+
}
135+
}
136+
131137
#[cfg(target_endian = "little")]
132138
unsafe impl Zeroable for Product {}
133139

@@ -387,3 +393,31 @@ pub fn load_price(data: &[u8]) -> Result<&Price, PythError> {
387393

388394
return Ok(pyth_price);
389395
}
396+
397+
struct AttributeIter<'a> {
398+
attrs: &'a [u8],
399+
}
400+
401+
impl<'a> Iterator for AttributeIter<'a> {
402+
type Item = (&'a str, &'a str);
403+
404+
fn next(&mut self) -> Option<Self::Item> {
405+
if self.attrs.is_empty() {
406+
return None;
407+
}
408+
let (key, data) = get_attr_str(self.attrs);
409+
let (val, data) = get_attr_str(data);
410+
self.attrs = data;
411+
return Some((key, val));
412+
}
413+
}
414+
415+
fn get_attr_str(buf: &[u8]) -> (&str, &[u8]) {
416+
if buf.is_empty() {
417+
return ("", &[]);
418+
}
419+
let len = buf[0] as usize;
420+
let str = std::str::from_utf8(&buf[1..len + 1]).expect("attr should be ascii or utf-8");
421+
let remaining_buf = &buf[len + 1..];
422+
(str, remaining_buf)
423+
}

0 commit comments

Comments
 (0)