| OLD | NEW |
| (Empty) |
| 1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file | |
| 2 // for details. All rights reserved. Use of this source code is governed by a | |
| 3 // BSD-style license that can be found in the LICENSE file. | |
| 4 | |
| 5 library pub.transcript; | |
| 6 | |
| 7 import 'dart:collection'; | |
| 8 | |
| 9 /// A rolling transcript of entries of type [T]. | |
| 10 /// | |
| 11 /// It has a maximum number of entries. If entries are added that exceed that | |
| 12 /// it discards entries from the *middle* of the transcript. Generally, in logs, | |
| 13 /// the first and last entries are the most important, so it maintains those. | |
| 14 class Transcript<T> { | |
| 15 /// The maximum number of transcript entries. | |
| 16 final int max; | |
| 17 | |
| 18 /// The number of entries that were discarded after reaching [max]. | |
| 19 int get discarded => _discarded; | |
| 20 int _discarded = 0; | |
| 21 | |
| 22 /// The earliest half of the entries. | |
| 23 /// | |
| 24 /// This will be empty until the maximum number of entries is hit at which | |
| 25 /// point the oldest half of the entries will be moved from [_newest] to | |
| 26 /// here. | |
| 27 final _oldest = new List<T>(); | |
| 28 | |
| 29 /// The most recent half of the entries. | |
| 30 final _newest = new Queue<T>(); | |
| 31 | |
| 32 /// Creates a new [Transcript] that can hold up to [max] entries. | |
| 33 Transcript(this.max); | |
| 34 | |
| 35 /// Adds [entry] to the transcript. | |
| 36 /// | |
| 37 /// If the transcript already has the maximum number of entries, discards one | |
| 38 /// from the middle. | |
| 39 void add(T entry) { | |
| 40 if (discarded > 0) { | |
| 41 // We're already in "rolling" mode. | |
| 42 _newest.removeFirst(); | |
| 43 _discarded++; | |
| 44 } else if (_newest.length == max) { | |
| 45 // We are crossing the threshold where we have to discard items. Copy | |
| 46 // the first half over to the oldest list. | |
| 47 while (_newest.length > max ~/ 2) { | |
| 48 _oldest.add(_newest.removeFirst()); | |
| 49 } | |
| 50 | |
| 51 // Discard the middle item. | |
| 52 _newest.removeFirst(); | |
| 53 _discarded++; | |
| 54 } | |
| 55 | |
| 56 _newest.add(entry); | |
| 57 } | |
| 58 | |
| 59 /// Traverses the entries in the transcript from oldest to newest. | |
| 60 /// | |
| 61 /// Invokes [onEntry] for each item. When it reaches the point in the middle | |
| 62 /// where excess entries where dropped, invokes [onGap] with the number of | |
| 63 /// dropped entries. If no more than [max] entries were added, does not | |
| 64 /// invoke [onGap]. | |
| 65 void forEach(void onEntry(T entry), [void onGap(int)]) { | |
| 66 if (_oldest.isNotEmpty) { | |
| 67 _oldest.forEach(onEntry); | |
| 68 if (onGap != null) onGap(discarded); | |
| 69 } | |
| 70 | |
| 71 _newest.forEach(onEntry); | |
| 72 } | |
| 73 } | |
| OLD | NEW |