@@ -512,18 +512,39 @@ impl<'a> MetricEncoder<'a> {
512
512
additional_labels. encode ( LabelSetEncoder :: new ( self . writer ) . into ( ) ) ?;
513
513
}
514
514
515
- if let Some ( labels) = & self . family_labels {
516
- let mut string_writer = String :: new ( ) ;
517
- labels. encode ( LabelSetEncoder :: new ( & mut string_writer) . into ( ) ) ?;
515
+ /// Writer impl which prepends a comma on the first call to write output to the wrapped writer
516
+ struct CommaPrependingWriter < ' a > {
517
+ writer : & ' a mut dyn Write ,
518
+ should_prepend : bool ,
519
+ }
518
520
519
- if !string_writer. is_empty ( ) {
520
- if !self . const_labels . is_empty ( ) || additional_labels. is_some ( ) {
521
- self . writer . write_str ( "," ) ?;
521
+ impl Write for CommaPrependingWriter < ' _ > {
522
+ fn write_str ( & mut self , s : & str ) -> std:: fmt:: Result {
523
+ if self . should_prepend {
524
+ self . writer . write_char ( ',' ) ?;
525
+ self . should_prepend = false ;
522
526
}
523
- self . writer . write_str ( string_writer . as_str ( ) ) ? ;
527
+ self . writer . write_str ( s )
524
528
}
525
529
}
526
530
531
+ if let Some ( labels) = self . family_labels {
532
+ // if const labels or additional labels have been written, a comma must be prepended before writing the family labels.
533
+ // However, it could be the case that the family labels are `Some` and yet empty, so the comma should _only_
534
+ // be prepended if one of the `Write` methods are actually called when attempting to write the family labels.
535
+ // Therefore, wrap the writer on `Self` with a CommaPrependingWriter if other labels have been written and
536
+ // there may be a need to prepend an extra comma before writing additional labels.
537
+ if !self . const_labels . is_empty ( ) || additional_labels. is_some ( ) {
538
+ let mut writer = CommaPrependingWriter {
539
+ writer : self . writer ,
540
+ should_prepend : true ,
541
+ } ;
542
+ labels. encode ( LabelSetEncoder :: new ( & mut writer) . into ( ) ) ?;
543
+ } else {
544
+ labels. encode ( LabelSetEncoder :: new ( self . writer ) . into ( ) ) ?;
545
+ } ;
546
+ }
547
+
527
548
self . writer . write_str ( "}" ) ?;
528
549
529
550
Ok ( ( ) )
0 commit comments