fuchsia_inspect/writer/
utils.rs

1// Copyright 2021 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use std::sync::atomic::{AtomicUsize, Ordering};
6
7// Suffix used for unique names.
8static UNIQUE_NAME_SUFFIX: AtomicUsize = AtomicUsize::new(0);
9
10/// Generates a unique name that can be used in inspect nodes and properties that will be prefixed
11/// by the given `prefix`.
12pub fn unique_name(prefix: &str) -> String {
13    let suffix = UNIQUE_NAME_SUFFIX.fetch_add(1, Ordering::Relaxed);
14    format!("{}{}", prefix, suffix)
15}
16
17#[cfg(test)]
18mod tests {
19    use super::*;
20    use crate::writer::Inspector;
21    use diagnostics_assertions::assert_data_tree;
22
23    #[fuchsia::test]
24    fn test_unique_name() {
25        let inspector = Inspector::default();
26
27        let name_1 = unique_name("a");
28        assert_eq!(name_1, "a0");
29        inspector.root().record_uint(name_1, 1);
30
31        let name_2 = unique_name("a");
32        assert_eq!(name_2, "a1");
33        inspector.root().record_uint(name_2, 1);
34
35        assert_data_tree!(inspector, root: {
36            a0: 1u64,
37            a1: 1u64,
38        });
39    }
40}