OLD | NEW |
| (Empty) |
1 // Copyright (c) 2013, 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 library utils; | |
5 | |
6 | |
7 List<int> getLineOffsets(String text) { | |
8 var offsets = <int> [0]; | |
9 var wasSR = false; | |
10 text.codeUnits.asMap().forEach((int i, int codeUnit) { | |
11 if (codeUnit == 13) { | |
12 wasSR = true; | |
13 return; | |
14 } | |
15 if (codeUnit == 10) { | |
16 if (wasSR) { | |
17 offsets.add(i - 1); | |
18 } else { | |
19 offsets.add(i); | |
20 } | |
21 } | |
22 wasSR = false; | |
23 }); | |
24 return offsets; | |
25 } | |
26 | |
27 /// Find the first entry in a sorted [list] that matches a monotonic predicate. | |
28 /// Given a result `n`, that all items before `n` will not match, `n` matches, | |
29 /// and all items after `n` match too. The result is -1 when there are no | |
30 /// items, 0 when all items match, and list.length when none does. | |
31 // TODO(scheglov) remove this function after dartbug.com/5624 is fixed. | |
32 int binarySearch(List list, bool matches(item)) { | |
33 if (list.length == 0) return -1; | |
34 if (matches(list.first)) return 0; | |
35 if (!matches(list.last)) return list.length; | |
36 var min = 0; | |
37 var max = list.length - 1; | |
38 while (min < max) { | |
39 var half = min + ((max - min) ~/ 2); | |
40 if (matches(list[half])) { | |
41 max = half; | |
42 } else { | |
43 min = half + 1; | |
44 } | |
45 } | |
46 return max; | |
47 } | |
OLD | NEW |