Elegant Algorithm for Parsing Data Stream Into Record

Posted by Matt Long on Stack Overflow See other posts from Stack Overflow or by Matt Long
Published on 2010-03-16T23:36:23Z Indexed on 2010/03/17 3:21 UTC
Read the original article Hit count: 344

Filed under:
|
|

I am interfacing with a hardware device that streams data to my app over Wifi. The data is streaming in just fine. The data contains a character header (DATA:) that indicates a new record has begun. The issues is that the data I receive doesn't necessarily fall on the header boundary, so I have to capture the data until what I've captured contains the header. Then, everything that precedes the header goes into the previous record and everything that comes after it goes into a new record. I have this working, but wondered if anyone has done this before and has a good computer-sciencey way to solve the problem.

Here's what I do:

  1. Convert the NSData of the current read to an NSString

  2. Append the NSString to a placeholder string

  3. Check placeholder string for the header (DATA:). If the header is not there, just wait for the next read.

  4. If the header exists, append whatever precedes it to a previous record placeholder and hand that placeholder off to an array as a complete record that I can further parse into fields.

  5. Take whatever shows up after the header and place it in the record placeholder so that it can be appended to in the next read. Repeat steps 3 - 5.

Let me know if you see any flaws with this or have a suggestion for a better way.

Seems there should be some design pattern for this, but I can't think of one.

Thanks.

© Stack Overflow or respective owner

Related posts about algorithm

Related posts about objective-c