easyfix_core/serializer.rs
1//! Writing FIX tag-value messages.
2//!
3//! [`Serializer`] appends fields into a caller-owned buffer; the generated
4//! message types drive it one field at a time. Nothing is allocated, so the
5//! buffer's length is the message size limit.
6
7use std::fmt::{self, Write};
8
9use chrono::Datelike;
10
11use crate::basic_types::{
12 Amt, Boolean, Char, Country, Currency, Data, DayOfMonth, Exchange, FixStr, Float, Int,
13 Language, Length, LocalMktDate, LocalMktTime, MonthYear, MultipleCharValue,
14 MultipleStringValue, NumInGroup, Percentage, Price, PriceOffset, Qty, SeqNum, TagNum, Tenor,
15 TzTimeOnly, TzTimestamp, UtcDateOnly, UtcTimeOnly, UtcTimestamp, XmlData,
16 offset_is_wire_representable, second_is_wire_representable, year_is_wire_representable,
17};
18
19#[cfg(test)]
20mod tests;
21
22/// Number of digits reserved for the BodyLength(9) placeholder, derived
23/// from the output buffer size. Capped at 8 digits: with a buffer of
24/// 100 MB or more the encodable body length tops out at 99 999 999 bytes,
25/// and a body that does not fit the placeholder fails serialization with
26/// `MaxMessageSizeExceeded` when the value is patched in.
27const fn max_body_len_digits(max_msg_size: usize) -> usize {
28 if max_msg_size < 10 {
29 1
30 } else if max_msg_size < 100 {
31 2
32 } else if max_msg_size < 1000 {
33 3
34 } else if max_msg_size < 10_000 {
35 4
36 } else if max_msg_size < 100_000 {
37 5
38 } else if max_msg_size < 1_000_000 {
39 6
40 } else if max_msg_size < 10_000_000 {
41 7
42 } else {
43 8
44 }
45}
46
47/// Why a value could not be written to the wire.
48#[derive(Debug, thiserror::Error)]
49pub enum SerializeError {
50 /// The write would run past the end of the output buffer, or the patched
51 /// BodyLength(9) does not fit the placeholder reserved for it.
52 #[error("max message size exceeded")]
53 MaxMessageSizeExceeded,
54 /// A field that must carry at least one byte was empty: `FixStr`, `Country`,
55 /// `Currency`, `Exchange`, `Language`, `Data`, `XmlData`, a `MultipleCharValue`
56 /// / `MultipleStringValue` collection or one of its elements, or an enum collection.
57 #[error("empty value")]
58 EmptyValue,
59 /// A value outside the range its FIX datatype allows: a zero `TagNum`,
60 /// `NumInGroup` or `Length`, a `Char` outside printable ASCII
61 /// (`0x20..=0x7e`), or a timestamp the wire grammar cannot render (year
62 /// outside `0000-9999`, sub-minute UTC offset, leap second in a zoned
63 /// type).
64 #[error("invalid value")]
65 InvalidValue,
66}
67
68fn validate_char(c: Char) -> Result<(), SerializeError> {
69 if matches!(c, 0x20..=0x7e) {
70 Ok(())
71 } else {
72 Err(SerializeError::InvalidValue)
73 }
74}
75
76/// Writes FIX tag-value fields into a caller-provided byte buffer.
77///
78/// The buffer is the message size limit: nothing is ever allocated, and a
79/// message that does not fit fails with
80/// [`SerializeError::MaxMessageSizeExceeded`] rather than growing. Size the
81/// buffer for the largest message the session may emit.
82///
83/// A field is three calls - tag prefix, typed value, delimiter:
84///
85/// ```
86/// # use easyfix_core::{basic_types::FixStr, fix_str, serializer::Serializer};
87/// # fn main() -> Result<(), easyfix_core::serializer::SerializeError> {
88/// let mut buf = [0u8; 64];
89/// let mut serializer = Serializer::new(&mut buf);
90/// serializer.put_slice(b"49=")?;
91/// serializer.serialize_string(fix_str!("SENDER"))?;
92/// serializer.put_soh()?;
93/// assert_eq!(serializer.written(), b"49=SENDER\x01");
94/// # Ok(())
95/// # }
96/// ```
97///
98/// A whole message additionally brackets the body with
99/// [`serialize_body_len`](Self::serialize_body_len) (which reserves the
100/// BodyLength(9) placeholder) and [`serialize_checksum`](Self::serialize_checksum)
101/// (which patches that placeholder and appends CheckSum(10)).
102pub struct Serializer<'a> {
103 output: &'a mut [u8],
104 pos: usize,
105 body_start_idx: usize,
106 /// Width of the BodyLength(9) placeholder written by
107 /// `serialize_body_len`; `0` until then.
108 body_len_digits: usize,
109}
110
111impl<'a> Serializer<'a> {
112 /// Wraps `output`, whose length becomes this message's size limit.
113 pub fn new(output: &'a mut [u8]) -> Serializer<'a> {
114 Serializer {
115 output,
116 pos: 0,
117 body_start_idx: 0,
118 body_len_digits: 0,
119 }
120 }
121
122 /// Number of bytes written so far.
123 pub fn pos(&self) -> usize {
124 self.pos
125 }
126
127 /// The bytes written so far.
128 pub fn written(&self) -> &[u8] {
129 &self.output[..self.pos]
130 }
131
132 /// Append raw bytes.
133 pub fn put_slice(&mut self, bytes: &[u8]) -> Result<(), SerializeError> {
134 if bytes.len() > self.output.len() - self.pos {
135 return Err(SerializeError::MaxMessageSizeExceeded);
136 }
137 let end = self.pos + bytes.len();
138 self.output[self.pos..end].copy_from_slice(bytes);
139 self.pos = end;
140 Ok(())
141 }
142
143 /// Append a single byte.
144 pub fn put_u8(&mut self, byte: u8) -> Result<(), SerializeError> {
145 if self.pos >= self.output.len() {
146 return Err(SerializeError::MaxMessageSizeExceeded);
147 }
148 self.output[self.pos] = byte;
149 self.pos += 1;
150 Ok(())
151 }
152
153 /// Write the FIX field delimiter (SOH, 0x01).
154 pub fn put_soh(&mut self) -> Result<(), SerializeError> {
155 self.put_u8(b'\x01')
156 }
157
158 /// Write the BodyLength(9) field as an all-zero placeholder and mark the
159 /// body start.
160 ///
161 /// The placeholder width comes from the buffer size, not from the message,
162 /// so the real length is patched in later by
163 /// [`serialize_checksum`](Self::serialize_checksum). Call this once,
164 /// directly after BeginString(8).
165 pub fn serialize_body_len(&mut self) -> Result<(), SerializeError> {
166 const PLACEHOLDERS: [&[u8]; 8] = [
167 b"9=0\x01",
168 b"9=00\x01",
169 b"9=000\x01",
170 b"9=0000\x01",
171 b"9=00000\x01",
172 b"9=000000\x01",
173 b"9=0000000\x01",
174 b"9=00000000\x01",
175 ];
176 let digits = max_body_len_digits(self.output.len());
177 self.put_slice(PLACEHOLDERS[digits - 1])?;
178 self.body_start_idx = self.pos;
179 self.body_len_digits = digits;
180 Ok(())
181 }
182
183 /// Close the message: patch the real body length into the placeholder,
184 /// then append CheckSum(10) over every byte written before it.
185 ///
186 /// Returns [`SerializeError::MaxMessageSizeExceeded`] when the body length
187 /// needs more digits than the placeholder reserved - including the case
188 /// where [`serialize_body_len`](Self::serialize_body_len) was never
189 /// called, which leaves no placeholder to patch.
190 pub fn serialize_checksum(&mut self) -> Result<(), SerializeError> {
191 let mut buffer = itoa::Buffer::new();
192
193 let body_len = self.pos - self.body_start_idx;
194 let body_len_slice = buffer.format(body_len).as_bytes();
195
196 // Also rejects calling `serialize_checksum` without a preceding
197 // `serialize_body_len` (`body_len_digits` is 0 then).
198 if body_len_slice.len() > self.body_len_digits {
199 return Err(SerializeError::MaxMessageSizeExceeded);
200 }
201
202 self.output[self.body_start_idx - body_len_slice.len() - 1..self.body_start_idx - 1]
203 .copy_from_slice(body_len_slice);
204
205 let checksum = self.output[..self.pos]
206 .iter()
207 .fold(0u8, |acc, &byte| u8::wrapping_add(acc, byte));
208
209 self.put_slice(b"10=")?;
210 if checksum < 10 {
211 self.put_slice(b"00")?;
212 } else if checksum < 100 {
213 self.put_u8(b'0')?;
214 }
215 self.put_slice(buffer.format(checksum).as_bytes())?;
216 self.put_u8(b'\x01')?;
217 Ok(())
218 }
219
220 /// Serialize sequence of character digits without commas or decimals.
221 /// Value must be positive and may not contain leading zeros.
222 pub fn serialize_tag_num(&mut self, tag_num: &TagNum) -> Result<(), SerializeError> {
223 if *tag_num == 0 {
224 return Err(SerializeError::InvalidValue);
225 }
226 let mut buffer = itoa::Buffer::new();
227 self.put_slice(buffer.format(*tag_num).as_bytes())
228 }
229
230 /// Serialize sequence of character digits without commas or decimals
231 /// and optional sign character (characters `-` and `0` - `9`).
232 /// The sign character utilizes one octet (i.e., positive int is `99999`
233 /// while negative int is `-99999`).
234 pub fn serialize_int(&mut self, int: &Int) -> Result<(), SerializeError> {
235 let mut buffer = itoa::Buffer::new();
236 self.put_slice(buffer.format(*int).as_bytes())
237 }
238
239 /// Serialize sequence of character digits without commas or decimals.
240 ///
241 /// Zero is a legal value here, unlike for the other digit types. Several
242 /// SeqNum-typed fields give it a meaning of their own: `EndSeqNo(16)` and
243 /// `ApplEndSeqNum(1183)` use it for "no upper bound", and
244 /// `LastMsgSeqNumProcessed(369)` for "nothing processed yet". Which zeros
245 /// are legal is a per-tag question the codec has no way to answer -
246 /// [`Deserializer::deserialize_seq_num`] already accepts every one of
247 /// them, and rejecting them on the way out would leave the codec able to
248 /// read messages it cannot write.
249 ///
250 /// Sequence-number *validity* belongs to the session layer, which owns
251 /// the counters and checks them against protocol state.
252 ///
253 /// [`Deserializer::deserialize_seq_num`]: crate::deserializer::Deserializer::deserialize_seq_num
254 pub fn serialize_seq_num(&mut self, seq_num: &SeqNum) -> Result<(), SerializeError> {
255 let mut buffer = itoa::Buffer::new();
256 self.put_slice(buffer.format(*seq_num).as_bytes())
257 }
258
259 /// Serialize sequence of character digits without commas or decimals.
260 /// Value must be positive.
261 pub fn serialize_num_in_group(
262 &mut self,
263 num_in_group: &NumInGroup,
264 ) -> Result<(), SerializeError> {
265 if *num_in_group == 0 {
266 return Err(SerializeError::InvalidValue);
267 }
268 let mut buffer = itoa::Buffer::new();
269 self.put_slice(buffer.format(*num_in_group).as_bytes())
270 }
271
272 /// Serialize sequence of character digits without commas or decimals
273 /// (values 1 to 31).
274 pub fn serialize_day_of_month(
275 &mut self,
276 day_of_month: DayOfMonth,
277 ) -> Result<(), SerializeError> {
278 let mut buffer = itoa::Buffer::new();
279 self.put_slice(buffer.format(day_of_month).as_bytes())
280 }
281
282 /// Serialize sequence of character digits with optional decimal point
283 /// and sign character (characters `-`, `0` - `9` and `.`);
284 /// the absence of the decimal point within the string will be interpreted
285 /// as the float representation of an integer value. Note that float values
286 /// may contain leading zeros (e.g. `00023.23` = `23.23`) and may contain
287 /// or omit trailing zeros after the decimal point
288 /// (e.g. `23.0` = `23.0000` = `23` = `23.`).
289 ///
290 /// All float fields must accommodate up to fifteen significant digits.
291 /// The number of decimal places used should be a factor of business/market
292 /// needs and mutual agreement between counterparties.
293 pub fn serialize_float(&mut self, float: &Float) -> Result<(), SerializeError> {
294 self.put_slice(float.to_string().as_bytes())
295 }
296
297 /// Serialize a `Qty` - the `Float` grammar under a different name.
298 pub fn serialize_qty(&mut self, qty: &Qty) -> Result<(), SerializeError> {
299 self.serialize_float(qty)
300 }
301
302 /// Serialize a `Price` - the `Float` grammar under a different name.
303 pub fn serialize_price(&mut self, price: &Price) -> Result<(), SerializeError> {
304 self.serialize_float(price)
305 }
306
307 /// Serialize a `PriceOffset` - the `Float` grammar under a different name.
308 pub fn serialize_price_offset(
309 &mut self,
310 price_offset: &PriceOffset,
311 ) -> Result<(), SerializeError> {
312 self.serialize_float(price_offset)
313 }
314
315 /// Serialize an `Amt` - the `Float` grammar under a different name.
316 pub fn serialize_amt(&mut self, amt: &Amt) -> Result<(), SerializeError> {
317 self.serialize_float(amt)
318 }
319
320 /// Serialize a `Percentage` - the `Float` grammar under a different name.
321 pub fn serialize_percentage(&mut self, percentage: &Percentage) -> Result<(), SerializeError> {
322 self.serialize_float(percentage)
323 }
324
325 /// Serialize a single-character boolean: `Y` for true, `N` for false.
326 pub fn serialize_boolean(&mut self, boolean: &Boolean) -> Result<(), SerializeError> {
327 if *boolean {
328 self.put_u8(b'Y')
329 } else {
330 self.put_u8(b'N')
331 }
332 }
333
334 /// Use any ASCII character except control characters.
335 pub fn serialize_char(&mut self, c: &Char) -> Result<(), SerializeError> {
336 validate_char(*c)?;
337 self.put_u8(*c)
338 }
339
340 /// Serialize string containing one or more space-delimited single
341 /// character values, e.g. `2 A F`.
342 pub fn serialize_multiple_char_value(
343 &mut self,
344 mcv: &MultipleCharValue,
345 ) -> Result<(), SerializeError> {
346 if mcv.is_empty() {
347 return Err(SerializeError::EmptyValue);
348 }
349 for c in mcv {
350 validate_char(*c)?;
351 self.put_u8(*c)?;
352 self.put_u8(b' ')?;
353 }
354 // Drop trailing space (mirrors Vec::pop's no-op-on-empty behavior).
355 self.pos = self.pos.saturating_sub(1);
356 Ok(())
357 }
358
359 /// Serialize alphanumeric free-format strings can include any character
360 /// except control characters.
361 pub fn serialize_string(&mut self, input: &FixStr) -> Result<(), SerializeError> {
362 if input.is_empty() {
363 return Err(SerializeError::EmptyValue);
364 }
365 self.put_slice(input.as_bytes())
366 }
367
368 /// Serialize string containing one or more space-delimited multiple
369 /// character values, e.g. `AV AN A`.
370 pub fn serialize_multiple_string_value(
371 &mut self,
372 input: &MultipleStringValue,
373 ) -> Result<(), SerializeError> {
374 if input.is_empty() {
375 return Err(SerializeError::EmptyValue);
376 }
377 for s in input {
378 if s.is_empty() {
379 return Err(SerializeError::EmptyValue);
380 }
381 self.put_slice(s.as_bytes())?;
382 self.put_u8(b' ')?;
383 }
384 // Drop trailing space (mirrors Vec::pop's no-op-on-empty behavior).
385 self.pos = self.pos.saturating_sub(1);
386 Ok(())
387 }
388
389 /// Serialize ISO 3166-1:2013 Codes for the representation of names of
390 /// countries and their subdivision (2-character code).
391 ///
392 /// Returns [`SerializeError::EmptyValue`] when the country is unspecified.
393 pub fn serialize_country(&mut self, country: &Country) -> Result<(), SerializeError> {
394 self.serialize_string(country.as_fix_str())
395 }
396
397 /// Serialize ISO 4217:2015 Codes for the representation of currencies
398 /// and funds (3-character code).
399 ///
400 /// Returns [`SerializeError::EmptyValue`] when the currency is unspecified.
401 pub fn serialize_currency(&mut self, currency: &Currency) -> Result<(), SerializeError> {
402 self.serialize_string(currency.as_fix_str())
403 }
404
405 /// Serialize ISO 10383:2012 Securities and related financial
406 /// instruments - Codes for exchanges and market identification (MIC)
407 /// (4-character code).
408 ///
409 /// Returns [`SerializeError::EmptyValue`] when the code is not set.
410 pub fn serialize_exchange(&mut self, exchange: &Exchange) -> Result<(), SerializeError> {
411 self.serialize_string(exchange.as_fix_str())
412 }
413
414 /// Serialize string representing month of a year.
415 /// An optional day of the month can be appended or an optional week code.
416 ///
417 /// # Valid formats:
418 /// YYYYMM
419 /// YYYYMMDD
420 /// YYYYMMWW
421 ///
422 /// # Valid values:
423 /// YYYY = 0000-9999; MM = 01-12; DD = 01-31;
424 /// WW = w1, w2, w3, w4, w5.
425 pub fn serialize_month_year(&mut self, input: &MonthYear) -> Result<(), SerializeError> {
426 self.serialize_string(input)
427 }
428
429 /// Serialize ISO 639-1:2002 Codes for the representation of names
430 /// of languages (2-character code).
431 ///
432 /// Returns [`SerializeError::EmptyValue`] when the language is unspecified.
433 pub fn serialize_language(&mut self, input: &Language) -> Result<(), SerializeError> {
434 self.serialize_string(input.as_fix_str())
435 }
436
437 /// Serialize string representing time/date combination represented
438 /// in UTC (Universal Time Coordinated) in either YYYYMMDD-HH:MM:SS
439 /// (whole seconds) or YYYYMMDD-HH:MM:SS.sss* format, colons, dash,
440 /// and period required.
441 ///
442 /// # Valid values:
443 /// - YYYY = 0000-9999,
444 /// - MM = 01-12,
445 /// - DD = 01-31,
446 /// - HH = 00-23,
447 /// - MM = 0059,
448 /// - SS = 00-60 (60 only if UTC leap second),
449 /// - sss* fractions of seconds. The fractions of seconds may be empty when
450 /// no fractions of seconds are conveyed (in such a case the period
451 /// is not conveyed), it may include 3 digits to convey
452 /// milliseconds, 6 digits to convey microseconds, 9 digits
453 /// to convey nanoseconds, 12 digits to convey picoseconds;
454 pub fn serialize_utc_timestamp(&mut self, input: &UtcTimestamp) -> Result<(), SerializeError> {
455 if !year_is_wire_representable(input.timestamp().year()) {
456 return Err(SerializeError::InvalidValue);
457 }
458 write!(self, "{}", input.format_precisely())
459 .map_err(|_| SerializeError::MaxMessageSizeExceeded)
460 }
461
462 /// Serialize string representing time-only represented in UTC
463 /// (Universal Time Coordinated) in either HH:MM:SS (whole seconds)
464 /// or HH:MM:SS.sss* (milliseconds) format, colons, and period required.
465 ///
466 /// This special-purpose field is paired with UTCDateOnly to form a proper
467 /// UTCTimestamp for bandwidth-sensitive messages.
468 ///
469 /// # Valid values:
470 /// - HH = 00-23,
471 /// - MM = 00-59,
472 /// - SS = 00-60 (60 only if UTC leap second),
473 /// - sss* fractions of seconds. The fractions of seconds may be empty when
474 /// no fractions of seconds are conveyed (in such a case the period
475 /// is not conveyed), it may include 3 digits to convey
476 /// milliseconds, 6 digits to convey microseconds, 9 digits
477 /// to convey nanoseconds, 12 digits to convey picoseconds;
478 pub fn serialize_utc_time_only(&mut self, input: &UtcTimeOnly) -> Result<(), SerializeError> {
479 write!(self, "{input}").map_err(|_| SerializeError::MaxMessageSizeExceeded)
480 }
481
482 /// Serialize date represented in UTC (Universal Time Coordinated)
483 /// in YYYYMMDD format.
484 ///
485 /// # Valid values:
486 /// - YYYY = 0000-9999,
487 /// - MM = 01-12,
488 /// - DD = 01-31.
489 pub fn serialize_utc_date_only(&mut self, input: &UtcDateOnly) -> Result<(), SerializeError> {
490 if !year_is_wire_representable(input.year()) {
491 return Err(SerializeError::InvalidValue);
492 }
493 write!(self, "{}", input.format("%Y%m%d"))
494 .map_err(|_| SerializeError::MaxMessageSizeExceeded)
495 }
496
497 /// Serialize time local to a market center. Used where offset to UTC
498 /// varies throughout the year and the defining market center is identified
499 /// in a corresponding field.
500 ///
501 /// Format is HH:MM:SS where:
502 /// - HH = 00-23 hours,
503 /// - MM = 00-59 minutes,
504 /// - SS = 00-59 seconds.
505 ///
506 /// In general only the hour token is non-zero.
507 pub fn serialize_local_mkt_time(&mut self, input: &LocalMktTime) -> Result<(), SerializeError> {
508 if !second_is_wire_representable(input) {
509 return Err(SerializeError::InvalidValue);
510 }
511 write!(self, "{}", input.format("%H:%M:%S"))
512 .map_err(|_| SerializeError::MaxMessageSizeExceeded)
513 }
514
515 /// Serialize date of local market (as opposed to UTC) in YYYYMMDD
516 /// format.
517 ///
518 /// # Valid values:
519 /// - YYYY = 0000-9999,
520 /// - MM = 01-12,
521 /// - DD = 01-31.
522 pub fn serialize_local_mkt_date(&mut self, input: &LocalMktDate) -> Result<(), SerializeError> {
523 if !year_is_wire_representable(input.year()) {
524 return Err(SerializeError::InvalidValue);
525 }
526 write!(self, "{}", input.format("%Y%m%d"))
527 .map_err(|_| SerializeError::MaxMessageSizeExceeded)
528 }
529
530 /// Serialize string representing a time/date combination representing
531 /// local time with an offset to UTC to allow identification of local time
532 /// and time zone offset of that time.
533 ///
534 /// The representation is based on ISO 8601.
535 ///
536 /// Format is `YYYYMMDD-HH:MM:SS.sss*[Z | [ + | - hh[:mm]]]` where:
537 /// - YYYY = 0000 to 9999,
538 /// - MM = 01-12,
539 /// - DD = 01-31 HH = 00-23 hours,
540 /// - MM = 00-59 minutes,
541 /// - SS = 00-59 seconds,
542 /// - hh = 01-12 offset hours,
543 /// - mm = 00-59 offset minutes,
544 /// - sss* fractions of seconds. The fractions of seconds may be empty when
545 /// no fractions of seconds are conveyed (in such a case the period
546 /// is not conveyed), it may include 3 digits to convey
547 /// milliseconds, 6 digits to convey microseconds, 9 digits
548 /// to convey nanoseconds, 12 digits to convey picoseconds;
549 pub fn serialize_tz_timestamp(&mut self, input: &TzTimestamp) -> Result<(), SerializeError> {
550 let timestamp = input.timestamp();
551 if !year_is_wire_representable(timestamp.year())
552 || !offset_is_wire_representable(*timestamp.offset())
553 || !second_is_wire_representable(×tamp)
554 {
555 return Err(SerializeError::InvalidValue);
556 }
557 write!(self, "{input}").map_err(|_| SerializeError::MaxMessageSizeExceeded)
558 }
559
560 /// Serialize time of day with timezone. Time represented based on
561 /// ISO 8601. This is the time with a UTC offset to allow identification of
562 /// local time and time zone of that time.
563 ///
564 /// Format is `HH:MM[:SS][Z | [ + | - hh[:mm]]]` where:
565 /// - HH = 00-23 hours,
566 /// - MM = 00-59 minutes,
567 /// - SS = 00-59 seconds,
568 /// - hh = 01-12 offset hours,
569 /// - mm = 00-59 offset minutes.
570 pub fn serialize_tz_timeonly(&mut self, input: &TzTimeOnly) -> Result<(), SerializeError> {
571 if !offset_is_wire_representable(input.offset())
572 || !second_is_wire_representable(&input.timestamp())
573 {
574 return Err(SerializeError::InvalidValue);
575 }
576 write!(self, "{input}").map_err(|_| SerializeError::MaxMessageSizeExceeded)
577 }
578
579 /// Serialize sequence of character digits without commas or decimals.
580 pub fn serialize_length(&mut self, length: &Length) -> Result<(), SerializeError> {
581 if *length == 0 {
582 return Err(SerializeError::InvalidValue);
583 }
584 let mut buffer = itoa::Buffer::new();
585 self.put_slice(buffer.format(*length).as_bytes())
586 }
587
588 /// Serialize raw data with no format or content restrictions,
589 /// or a character string encoded as specified by MessageEncoding(347).
590 pub fn serialize_data(&mut self, data: &Data) -> Result<(), SerializeError> {
591 if data.is_empty() {
592 return Err(SerializeError::EmptyValue);
593 }
594 self.put_slice(data)
595 }
596
597 /// Serialize XML document.
598 pub fn serialize_xml(&mut self, xml_data: &XmlData) -> Result<(), SerializeError> {
599 if xml_data.is_empty() {
600 return Err(SerializeError::EmptyValue);
601 }
602 self.put_slice(xml_data)
603 }
604
605 /// Serialize a tenor: the unit code (`D`, `M`, `W` or `Y`) followed by its
606 /// value, e.g. `M3` for three months.
607 pub fn serialize_tenor(&mut self, input: &Tenor) -> Result<(), SerializeError> {
608 self.put_u8(input.unit.as_byte())?;
609 let mut buffer = itoa::Buffer::new();
610 self.put_slice(buffer.format(input.value.get()).as_bytes())
611 }
612
613 /// Serialize an enum as its FIX wire value.
614 ///
615 /// The value is a `&'static [u8]` held in read-only memory, so this is a
616 /// single copy with nothing allocated.
617 pub fn serialize_enum<T>(&mut self, value: &T) -> Result<(), SerializeError>
618 where
619 T: Copy + Into<&'static [u8]>,
620 {
621 self.put_slice((*value).into())
622 }
623
624 /// Serialize enums as a space-delimited list of their FIX wire values.
625 ///
626 /// An empty slice is [`SerializeError::EmptyValue`] - a FIX field must
627 /// carry at least one byte.
628 pub fn serialize_enum_collection<T>(&mut self, values: &[T]) -> Result<(), SerializeError>
629 where
630 T: Copy + Into<&'static [u8]>,
631 {
632 if values.is_empty() {
633 return Err(SerializeError::EmptyValue);
634 }
635 for value in values {
636 self.put_slice((*value).into())?;
637 self.put_u8(b' ')?;
638 }
639 // Drop last space (mirrors Vec::pop's no-op-on-empty behavior).
640 self.pos = self.pos.saturating_sub(1);
641 Ok(())
642 }
643}
644
645impl<'a> Write for Serializer<'a> {
646 fn write_str(&mut self, s: &str) -> fmt::Result {
647 let bytes = s.as_bytes();
648 let end = self.pos + bytes.len();
649 if end > self.output.len() {
650 return Err(fmt::Error);
651 }
652 self.output[self.pos..end].copy_from_slice(bytes);
653 self.pos = end;
654 Ok(())
655 }
656}