View Javadoc
1   package org.metricshub.ipmi.core.common;
2   
3   /*-
4    * ╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲
5    * IPMI Java Client
6    * ჻჻჻჻჻჻
7    * Copyright 2023 Verax Systems, MetricsHub
8    * ჻჻჻჻჻჻
9    * This program is free software: you can redistribute it and/or modify
10   * it under the terms of the GNU Lesser General Public License as
11   * published by the Free Software Foundation, either version 3 of the
12   * License, or (at your option) any later version.
13   *
14   * This program is distributed in the hope that it will be useful,
15   * but WITHOUT ANY WARRANTY; without even the implied warranty of
16   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17   * GNU General Lesser Public License for more details.
18   *
19   * You should have received a copy of the GNU General Lesser Public
20   * License along with this program.  If not, see
21   * <http://www.gnu.org/licenses/lgpl-3.0.html>.
22   * ╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱
23   */
24  
25  /**
26   * Class used for composing byte messages aout from smaller byte subarrays.
27   */
28  public class MessageComposer {
29  
30      private final byte[] message;
31      private int pointer = 0;
32  
33      public static MessageComposer get(int messageSize) {
34          return new MessageComposer(messageSize);
35      }
36  
37      private MessageComposer(int messageSize) {
38          if (messageSize < 0) {
39              throw new IllegalArgumentException("Message size cannot be negative");
40          }
41  
42          this.message = new byte[messageSize];
43      }
44  
45      /**
46       * Append single-byte field to the message.
47       *
48       * @param fieldData
49       *          single byte containing data that should be appended
50       */
51      public MessageComposer appendField(byte fieldData) {
52          message[pointer++] = fieldData;
53  
54          return this;
55      }
56  
57      /**
58       * Append byte arrach field to the message.
59       *
60       * @param fieldData
61       *          byte array containing data that should be appended
62       */
63      public MessageComposer appendField(byte[] fieldData) {
64          System.arraycopy(fieldData, 0, message, pointer, fieldData.length);
65  
66          pointer += fieldData.length;
67  
68          return this;
69      }
70  
71      /**
72       * Returns final message consisting all messages appended till now.
73       *
74       * @return composed message
75       */
76      public byte[] getMessage() {
77          return message;
78      }
79  }