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 : /// Encoding implementation that can encode and decode strings in the MQTT string format.
11 : ///
12 : /// The MQTT string format is simply a pascal string with ANSI character encoding. The first 2 bytes define
13 : /// the length of the string, and they are followed by the string itself.
14 : class MqttEncoding extends Utf8Codec {
15 : /// Encodes all the characters in the specified string into a sequence of bytes.
16 : typed.Uint8Buffer getBytes(String s) {
17 5 : _validateString(s);
18 5 : final typed.Uint8Buffer stringBytes = new typed.Uint8Buffer();
19 15 : stringBytes.add(s.length >> 8);
20 15 : stringBytes.add(s.length & 0xFF);
21 15 : stringBytes.addAll(encoder.convert(s));
22 : return stringBytes;
23 : }
24 :
25 : /// Decodes the bytes in the specified byte array into a string.
26 : String getString(typed.Uint8Buffer bytes) {
27 15 : return decoder.convert(bytes.toList());
28 : }
29 :
30 : /// When overridden in a derived class, calculates the number of characters produced by decoding all the bytes in the specified byte array.
31 : int getCharCount(typed.Uint8Buffer bytes) {
32 10 : if (bytes.length < 2) {
33 1 : throw new Exception(
34 : "mqtt_client::MQTTEncoding: Length byte array must comprise 2 bytes");
35 : }
36 20 : return ((bytes[0] << 8) + bytes[1]);
37 : }
38 :
39 : /// Calculates the number of bytes produced by encoding the characters in the specified.
40 : int getByteCount(String chars) {
41 5 : _validateString(chars);
42 10 : return getBytes(chars).length;
43 : }
44 :
45 : /// Validates the string to ensure it doesn't contain any characters invalid within the Mqtt string format.
46 : static void _validateString(String s) {
47 15 : for (int i = 0; i < s.length; i++) {
48 10 : if (s.codeUnitAt(i) > 0x7F) {
49 1 : throw new Exception(
50 : "mqtt_client::MQTTEncoding: The input string has extended "
51 : "UTF characters, which are not supported");
52 : }
53 : }
54 : }
55 : }
|