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

Add attribute iterator #14

Merged
merged 2 commits into from
Feb 7, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 1 addition & 18 deletions examples/get_accounts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,6 @@ use std::{
str::FromStr
};

fn get_attr_str<'a,T>( ite: & mut T ) -> String
where T : Iterator<Item=& 'a u8>
{
let mut len = *ite.next().unwrap() as usize;
let mut val = String::with_capacity( len );
while len > 0 {
val.push( *ite.next().unwrap() as char );
len -= 1;
}
return val
}

fn get_price_type( ptype: &PriceType ) -> &'static str
{
match ptype {
Expand Down Expand Up @@ -78,13 +66,8 @@ fn main() {

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

// print all Prices that correspond to this Product
Expand Down
34 changes: 34 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,12 @@ pub struct Product
pub attr : [u8;PROD_ATTR_SIZE]
}

impl Product {
pub fn iter(&self) -> AttributeIter {
AttributeIter { attrs: &self.attr }
}
}

#[cfg(target_endian = "little")]
unsafe impl Zeroable for Product {}

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

return Ok(pyth_price);
}

struct AttributeIter<'a> {
attrs: &'a [u8],
}

impl<'a> Iterator for AttributeIter<'a> {
type Item = (&'a str, &'a str);

fn next(&mut self) -> Option<Self::Item> {
if self.attrs.is_empty() {
return None;
}
let (key, data) = get_attr_str(self.attrs);
let (val, data) = get_attr_str(data);
self.attrs = data;
return Some((key, val));
}
}

fn get_attr_str(buf: &[u8]) -> (&str, &[u8]) {
if buf.is_empty() {
return ("", &[]);
}
let len = buf[0] as usize;
let str = std::str::from_utf8(&buf[1..len + 1]).expect("attr should be ascii or utf-8");
let remaining_buf = &buf[len + 1..];
(str, remaining_buf)
}