]> git.ipfire.org Git - thirdparty/suricata.git/commitdiff
jsonbuilder: add append_hex - add hex to array
authorJason Ish <jason.ish@oisf.net>
Thu, 8 Sep 2022 16:41:10 +0000 (10:41 -0600)
committerVictor Julien <vjulien@oisf.net>
Fri, 28 Oct 2022 09:48:13 +0000 (11:48 +0200)
New method, append_hex to add a byte array to a JSON array in hex
encoding.

rust/src/jsonbuilder.rs

index e3d47dad92807f7d7496c55456e8306ec895e429..721e90844a970220ea6aecd6bea889024611c77a 100644 (file)
@@ -328,6 +328,36 @@ impl JsonBuilder {
         }
     }
 
+    /// Add a byte array to a JSON array encoded as hex.
+    pub fn append_hex(&mut self, val: &[u8]) -> Result<&mut Self, JsonError> {
+        match self.current_state() {
+            State::ArrayFirst => {
+                self.buf.push('"');
+                for i in 0..val.len() {
+                    self.buf.push(HEX[(val[i] >>  4) as usize] as char);
+                    self.buf.push(HEX[(val[i] & 0xf) as usize] as char);
+                }
+                self.buf.push('"');
+                self.set_state(State::ArrayNth);
+                Ok(self)
+            }
+            State::ArrayNth => {
+                self.buf.push(',');
+                self.buf.push('"');
+                for i in 0..val.len() {
+                    self.buf.push(HEX[(val[i] >>  4) as usize] as char);
+                    self.buf.push(HEX[(val[i] & 0xf) as usize] as char);
+                }
+                self.buf.push('"');
+                Ok(self)
+            }
+            _ => {
+                debug_validate_fail!("invalid state");
+                Err(JsonError::InvalidState)
+            }
+        }
+    }
+
     /// Add an unsigned integer to an array.
     pub fn append_uint(&mut self, val: u64) -> Result<&mut Self, JsonError> {
         match self.current_state() {