quick-xml icon indicating copy to clipboard operation
quick-xml copied to clipboard

Easy way to implement a LineCounter

Open TG-97 opened this issue 11 months ago • 3 comments

Hello, i am trying to deserialize an XML file using the Event:: functionality. I am looking to implement a linecounter for better error messages. Is there any smooth way to achieve this? All the apporaches i came across yet didn't really work for me. I am trying to avoid having to read the file "line-by-line" and simply counting the lines. My current apporach handles the file by jumping from Event to Event. My attempts to just count the "\n,\r,\r\n"-text events did not really result in a number close to how my file actually looked. Any ideas are appreciated!

TG-97 avatar Jan 13 '25 10:01 TG-97

Yes, you can find an example in the documentation of the Reader::into_inner method. The same approach should be possible to implement using get_ref or get_mut methods.

Mingun avatar Jan 13 '25 18:01 Mingun

Do you think a mechanism could be exposed to count the lines, such as when using an async buf reader? From what I can see, this isn't possible to do currently, since you don't know how when in the buffer the current event comes from (so you can exclude newlines after it in the reader buffer).

etylermoss avatar Dec 05 '25 22:12 etylermoss

since you don't know how when in the buffer the current event comes from

I think, you may to calculate this. You control when you clear buf into which you read events. You may know its size before and after read_event_into[_async]. So you may count newlines in each chunk.

Another way, is to create impl AsyncBufRead + Unpin struct which will count newlines when data is requested from it and keep track of those. Then build Reader around this struct.

Mingun avatar Dec 07 '25 10:12 Mingun