Line data Source code
1 : /*
2 : * Package : mqtt_client
3 : * Author : S. Hamblett <steve.hamblett@linux.com>
4 : * Date : 31/05/2017
5 : * Copyright : S.Hamblett
6 : */
7 :
8 : part of mqtt_client;
9 :
10 : /// Provides the base implementation of an MQTT topic.
11 : abstract class Topic {
12 : static const String topicSeparator = "/";
13 : static const String multiWildcard = "#";
14 : static const String multiWildcardValidEnd = topicSeparator + multiWildcard;
15 : static const String wildcard = "+";
16 : static const int maxTopicLength = 65535;
17 :
18 : String rawTopic;
19 : List<String> topicFragments;
20 :
21 : /// Creates a new instance of a rawTopic from a rawTopic string.
22 : /// rawTopic - The topic to represent.
23 : /// validations - The validations to run on the rawTopic.
24 4 : Topic(String rawTopic, List<dynamic> validations) {
25 4 : this.rawTopic = rawTopic;
26 12 : this.topicFragments = rawTopic.split(topicSeparator[0]);
27 : // run all validations
28 8 : for (var validation in validations) {
29 4 : validation(this);
30 : }
31 : }
32 :
33 : /// Validates that the topic does not exceed the maximum length.
34 : /// topicInstance - The instance to check.
35 : static void validateMaxLength(Topic topicInstance) {
36 12 : if (topicInstance.rawTopic.length > maxTopicLength) {
37 1 : throw new Exception(
38 : "mqtt_client::Topic: The length of the supplied rawTopic "
39 1 : "(${topicInstance.rawTopic
40 2 : .length}) is longer than the maximum allowable ($maxTopicLength)");
41 : }
42 : }
43 :
44 : /// Returns true if there are any wildcards in the specified rawTopic, otherwise false.
45 : bool get hasWildcards {
46 8 : return this.rawTopic.contains(multiWildcard) ||
47 8 : this.rawTopic.contains(wildcard);
48 : }
49 :
50 : /// Validates that the topic does not fall below the minimum length.
51 : /// topicInstance - The instance to check.
52 : static void validateMinLength(Topic topicInstance) {
53 8 : if (topicInstance.rawTopic.isEmpty) {
54 1 : throw new Exception(
55 : "mqtt_client::Topic: rawTopic must contain at least one character");
56 : }
57 : }
58 :
59 : /// Serves as a hash function for a topics.
60 : @override
61 : int get hashCode {
62 2 : return this.rawTopic.hashCode;
63 : }
64 :
65 : /// Checks if one topic equals another topic exactly.
66 : @override
67 : bool operator ==(Object other) {
68 : if (identical(this, other)) {
69 : return true;
70 : }
71 4 : return other is Topic && this.rawTopic == other.rawTopic;
72 : }
73 :
74 : /// Returns a String representation of the topic.
75 : @override
76 : String toString() {
77 3 : return this.rawTopic;
78 : }
79 : }
|