matcher_util.dart 2 KB
Newer Older
1 2 3 4 5 6 7 8
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:matcher/matcher.dart';

/// Matches [value] against the [matcher].
MatchResult match(dynamic value, Matcher matcher) {
pq's avatar
pq committed
9
  Map<dynamic, dynamic> matchState = <dynamic, dynamic>{};
10
  if (matcher.matches(value, matchState)) {
11 12 13
    return new MatchResult._matched();
  } else {
    Description description =
14
        matcher.describeMismatch(value, new _TextDescription(), matchState, false);
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
    return new MatchResult._mismatched(description.toString());
  }
}

/// Result of matching a value against a matcher.
class MatchResult {
  MatchResult._matched()
    : hasMatched = true,
      mismatchDescription = null;

  MatchResult._mismatched(String mismatchDescription)
    : hasMatched = false,
      mismatchDescription = mismatchDescription;

  /// Whether the match succeeded.
  final bool hasMatched;

  /// If the match did not succeed, this field contains the explanation.
  final String mismatchDescription;
}

/// Writes description into a string.
class _TextDescription implements Description {
  final StringBuffer _text = new StringBuffer();

40
  @override
41 42
  int get length => _text.length;

43
  @override
44 45 46 47 48
  Description add(String text) {
    _text.write(text);
    return this;
  }

49
  @override
50 51 52 53 54 55
  Description replace(String text) {
    _text.clear();
    _text.write(text);
    return this;
  }

56
  @override
57
  Description addDescriptionOf(dynamic value) {
58 59 60 61 62 63 64 65
    if (value is Matcher) {
      value.describe(this);
      return this;
    } else {
      return add('$value');
    }
  }

66
  @override
67
  Description addAll(String start, String separator, String end, Iterable<dynamic> list) {
68 69 70 71 72 73 74 75 76 77 78 79
    add(start);
    if (list.isNotEmpty) {
      addDescriptionOf(list.first);
      for (dynamic item in list.skip(1)) {
        add(separator);
        addDescriptionOf(item);
      }
    }
    add(end);
    return this;
  }

80
  @override
81 82
  String toString() => '$_text';
}