Files
sdk/utils/pub/utils.dart
T
nweiz@google.com 5a6998d14e Add a Pub source for pub.dartlang.org.
This fixes a race condition in commit 9094.

Review URL: https://chromiumcodereview.appspot.com//10636045

git-svn-id: https://dart.googlecode.com/svn/branches/bleeding_edge/dart@9132 260f80e4-7a28-3924-810f-c04153c831b5
2012-06-26 20:01:30 +00:00

98 lines
2.2 KiB
Dart

// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/**
* Generic utility functions. Stuff that should possibly be in core.
*/
#library('utils');
/** Thrown by methods that parse text when the text isn't a valid. */
class FormatException implements Exception {
final String message;
FormatException(this.message);
String toString() => message;
}
/** A pair of values. */
class Pair<E, F> {
E first;
F last;
Pair(this.first, this.last);
String toString() => '($first, $last)';
}
// TODO(rnystrom): Move into String?
/** Pads [source] to [length] by adding spaces at the end. */
String padRight(String source, int length) {
final result = new StringBuffer();
result.add(source);
while (result.length < length) {
result.add(' ');
}
return result.toString();
}
/**
* Runs [fn] after [future] completes, whether it completes successfully or not.
* Essentially an asynchronous `finally` block.
*/
always(Future future, fn()) {
var completer = new Completer();
future.then((_) => fn());
future.handleException((_) {
fn();
return false;
});
}
/**
* Flattens nested lists into a single list containing only non-list elements.
*/
List flatten(List nested) {
var result = [];
helper(list) {
for (var element in list) {
if (element is List) {
helper(element);
} else {
result.add(element);
}
}
}
helper(nested);
return result;
}
/**
* Asserts that [iter] contains only one element, and returns it.
*/
only(Iterable iter) {
var iterator = iter.iterator();
assert(iterator.hasNext());
var obj = iterator.next();
assert(!iterator.hasNext());
return obj;
}
/**
* Replace each instance of [matcher] in [source] with the return value of [fn].
*/
String replace(String source, Pattern matcher, String fn(Match)) {
var buffer = new StringBuffer();
var start = 0;
for (var match in matcher.allMatches(source)) {
buffer.add(source.substring(start, match.start()));
start = match.end();
buffer.add(fn(match));
}
buffer.add(source.substring(start));
return buffer.toString();
}