简体   繁体   中英

Guidelines for designing a robust file format writer?

Suppose you want to write a.WAV file format writer like so:

using var stream = File.OpenRead("test.wav");
using var writer = new WavWriter(stream, ... /* .WAV format parameters */);

// write the file

// writer.Dispose() does a few things:
// - writes user-added chunks
// - updates the file header (chunk size) so the file is valid

There is a concpetual problem in doing so:

  • the user can change the stream position and therefore screw the writing process

You may suggest the following:

  • the writer should own the stream, this would work if writing to a file, but not to a stream
  • own its own memory stream so it can write to streams too, okay but memory concerns

I guess you get the point...

To me, the only viable thing would be to document that aspect but I may have missed something, hence the question.

Question:

How to make a file format writer be able to write to a stream yet defend yourself about possible changes to its position?

My suggestion would be to keep an internal position field in the WavWriter . Each time you do some operation you can check that this matches the position in the backing stream and throw an exception if it does not. Update this value at the end of each write operation.

Ideally you should also handle streams that does not support seeking, but it does not sound like your design would permit that anyway. It might be a good idea to check CanSeek in the constructor and throw if seek is not supported. It is in general a good idea to validate any arguments before usage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM