This repository was archived by the owner on Jun 30, 2022. It is now read-only.
File tree Expand file tree Collapse file tree 2 files changed +35
-18
lines changed Expand file tree Collapse file tree 2 files changed +35
-18
lines changed Original file line number Diff line number Diff line change @@ -20,18 +20,6 @@ use std::{
20
20
str:: FromStr
21
21
} ;
22
22
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
-
35
23
fn get_price_type ( ptype : & PriceType ) -> & ' static str
36
24
{
37
25
match ptype {
@@ -78,13 +66,8 @@ fn main() {
78
66
79
67
// print key and reference data for this Product
80
68
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 ( ) {
86
70
println ! ( " {:.<16} {}" , key, val ) ;
87
- psz -= 2 + key. len ( ) + val. len ( ) ;
88
71
}
89
72
90
73
// print all Prices that correspond to this Product
Original file line number Diff line number Diff line change @@ -128,6 +128,12 @@ pub struct Product
128
128
pub attr : [ u8 ; PROD_ATTR_SIZE ]
129
129
}
130
130
131
+ impl Product {
132
+ pub fn iter ( & self ) -> AttributeIter {
133
+ AttributeIter { attrs : & self . attr }
134
+ }
135
+ }
136
+
131
137
#[ cfg( target_endian = "little" ) ]
132
138
unsafe impl Zeroable for Product { }
133
139
@@ -387,3 +393,31 @@ pub fn load_price(data: &[u8]) -> Result<&Price, PythError> {
387
393
388
394
return Ok ( pyth_price) ;
389
395
}
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
+ }
You can’t perform that action at this time.
0 commit comments