readTps<T> function

T readTps<T>(
  1. String path,
  2. T read(
    1. TpsReader reader
    ), {
  3. String? password,
  4. Encoding encoding = windows1252,
  5. int cachePages = 64,
  6. int attempts = 3,
})

Opens path, runs read and closes the file again, returning what read returns. Safe on a file a Clarion program is writing to.

read must collect what it needs (for example with toList()), since the reader is closed afterwards. When the file changed while read ran, the result may mix old and new data, so it is thrown away and read runs again on a fresh reader, up to attempts times in all. No lock is taken: a lock could make the Clarion program fail.

Throws TpsException when the file kept changing on every attempt, or is not a readable TopSpeed file.

Implementation

T readTps<T>(String path, T Function(TpsReader reader) read,
    {String? password,
    Encoding encoding = windows1252,
    int cachePages = 64,
    int attempts = 3}) {
  for (var attempt = 1;; attempt++) {
    final reader = openTps(path,
        password: password, encoding: encoding, cachePages: cachePages);
    try {
      final T result;
      try {
        result = read(reader);
      } on TpsException {
        // A page caught in the middle of a write can fail to decode.
        if (!reader.changedOnDisk || attempt >= attempts) rethrow;
        continue;
      }
      if (!reader.changedOnDisk) return result;
      if (attempt >= attempts) {
        throw TpsException(
            '$path changed during each of $attempts reads; try again later');
      }
    } finally {
      reader.close();
    }
  }
}