Mercury.Formats library  1.0
The library provides format parsers for the Mercury library components.
 All Classes Namespaces Files Functions Properties
FmtChk.cs
Go to the documentation of this file.
1 using Mercury.Scanning;
2 using System;
3 using System.Collections.Generic;
4 using System.Linq;
5 
6 namespace Mercury.Formats
7 {
9  internal static class FmtChk
10  {
11  public static void AssertCount<T>(int count, ICollection<T> collection, string message = null)
12  {
13  if (count > collection.Count)
14  throw new FormatException(message ?? "Not enough elements in collection");
15  }
16 
17  public static void AssertNotEmpty<T>(ICollection<T> collection, string message = null)
18  {
19  AssertCount(1, collection, message ?? "Collection is empty");
20  }
21 
22  public static void AssertNotNull(object obj, string message)
23  {
24  if (obj == null)
25  throw new ArgumentNullException("message");
26  }
27 
28  public static void AssertToken(Token token, string value, string message = null)
29  {
30  if (token.Value != value)
31  throw new FormatException(message ?? string.Format("Expected '{0}', got '{1}'", value, token.Value));
32  }
33 
34  public static void AssertPattern<T>(ICollection<T> pattern, ICollection<T> source, string message = null)
35  {
36  if (pattern.Count > source.Count)
37  throw new FormatException(message ?? "Invalid sequence");
38 
39  Func<T, T, bool> f = (l, r) =>
40  {
41  if ((l != null) && (!l.Equals(r)))
42  throw new FormatException(message ?? string.Format("Expected '{0}', got '{1}'", l, r));
43 
44  return true;
45  };
46 
47  pattern.Zip(source, f);
48  }
49 
50  public static void AssertPattern<T,U>(ICollection<T> pattern, ICollection<U> source, Func<U,T> convert, string message = null)
51  {
52  if (pattern.Count > source.Count)
53  throw new FormatException(message ?? "Invalid sequence");
54 
55  AssertPattern(pattern, source.Take(pattern.Count).Select(convert).ToArray(), message);
56  }
57 
58  public static void AssertTrue(bool condition, string message)
59  {
60  if (!condition) throw new FormatException(message);
61  }
62 
63  public static void AssertFalse(bool condition, string message)
64  {
65  if (condition) throw new FormatException(message);
66  }
67  }
68 }