Skip to content

Commit cac25cf

Browse files
implement Display instead of to_string()
When implementing Display for a type, the to_string() method can be called as well. Display is more versatile and is the preferred way. Signed-off-by: Andreea Florescu <[email protected]>
1 parent 22ad768 commit cac25cf

File tree

2 files changed

+18
-13
lines changed

2 files changed

+18
-13
lines changed

mmds/src/data_store.rs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
22
// SPDX-License-Identifier: Apache-2.0
33

4+
use std::fmt;
5+
46
use serde_json::Value;
57

68
/// The Mmds is the Microvm Metadata Service represented as an untyped json.
@@ -16,12 +18,12 @@ pub enum Error {
1618
UnsupportedValueType,
1719
}
1820

19-
impl Error {
20-
pub fn to_string(&self) -> String {
21+
impl fmt::Display for Error {
22+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2123
match *self {
22-
Error::NotFound => "The MMDS resource does not exist.".to_string(),
24+
Error::NotFound => write!(f, "The MMDS resource does not exist."),
2325
Error::UnsupportedValueType => {
24-
"Cannot add non-strings values to the MMDS data-store.".to_string()
26+
write!(f, "Cannot add non-strings values to the MMDS data-store.")
2527
}
2628
}
2729
}

net_util/src/mac.rs

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
// Use of this source code is governed by a BSD-style license that can be
66
// found in the THIRD-PARTY file.
77

8+
use std::fmt;
89
use std::result::Result;
910

1011
use serde::de::{Deserialize, Deserializer, Error};
@@ -19,6 +20,17 @@ pub struct MacAddr {
1920
bytes: [u8; MAC_ADDR_LEN],
2021
}
2122

23+
impl fmt::Display for MacAddr {
24+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
25+
let b = &self.bytes;
26+
write!(
27+
f,
28+
"{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
29+
b[0], b[1], b[2], b[3], b[4], b[5]
30+
)
31+
}
32+
}
33+
2234
impl MacAddr {
2335
/// Try to turn a `&str` into a `MacAddr` object. The method will return the `str` that failed
2436
/// to be parsed.
@@ -114,15 +126,6 @@ impl MacAddr {
114126
pub fn get_bytes(&self) -> &[u8] {
115127
&self.bytes
116128
}
117-
118-
/// Obtain the string representation.
119-
pub fn to_string(self) -> String {
120-
let b = &self.bytes;
121-
format!(
122-
"{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
123-
b[0], b[1], b[2], b[3], b[4], b[5]
124-
)
125-
}
126129
}
127130

128131
impl Serialize for MacAddr {

0 commit comments

Comments
 (0)