mirror of
https://github.com/sigp/lighthouse.git
synced 2026-04-26 01:03:40 +00:00
Avoid string initialization in network metrics and replace by &str where possible (#1898)
## Issue Addressed NA ## Proposed Changes Removes most of the temporary string initializations in network metrics and replaces them by directly using `&str`. This further improves on PR https://github.com/sigp/lighthouse/pull/1895. For the subnet id handling the current approach uses a build script to create a static map. This has the disadvantage that the build script hardcodes the number of subnets. If we want to use more than 64 subnets we need to adjust this in the build script. ## Additional Info We still have some string initializations for the enum `PeerKind`. To also replace that by `&str` I created a PR in the libp2p dependency: https://github.com/sigp/rust-libp2p/pull/91. Either we wait with merging until this dependency PR is merged (and all conflicts with the newest libp2p version are resolved) or we just merge as is and I will create another PR when the dependency is ready.
This commit is contained in:
@@ -5,6 +5,8 @@
|
||||
// Clippy lint set up
|
||||
#![deny(clippy::integer_arithmetic)]
|
||||
|
||||
#[macro_use]
|
||||
extern crate lazy_static;
|
||||
#[macro_use]
|
||||
pub mod test_utils;
|
||||
|
||||
|
||||
@@ -4,11 +4,34 @@ use safe_arith::{ArithError, SafeArith};
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use std::ops::{Deref, DerefMut};
|
||||
|
||||
const MAX_SUBNET_ID: usize = 64;
|
||||
|
||||
lazy_static! {
|
||||
static ref SUBNET_ID_TO_STRING: Vec<String> = {
|
||||
let mut v = Vec::with_capacity(MAX_SUBNET_ID);
|
||||
|
||||
for i in 0..MAX_SUBNET_ID {
|
||||
v.push(i.to_string());
|
||||
}
|
||||
v
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "arbitrary-fuzz", derive(arbitrary::Arbitrary))]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct SubnetId(#[serde(with = "serde_utils::quoted_u64")] u64);
|
||||
|
||||
pub fn subnet_id_to_string(i: u64) -> &'static str {
|
||||
if i < MAX_SUBNET_ID as u64 {
|
||||
&SUBNET_ID_TO_STRING
|
||||
.get(i as usize)
|
||||
.expect("index below MAX_SUBNET_ID")
|
||||
} else {
|
||||
"subnet id out of range"
|
||||
}
|
||||
}
|
||||
|
||||
impl SubnetId {
|
||||
pub fn new(id: u64) -> Self {
|
||||
id.into()
|
||||
@@ -81,3 +104,9 @@ impl Into<u64> for &SubnetId {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<str> for SubnetId {
|
||||
fn as_ref(&self) -> &str {
|
||||
subnet_id_to_string(self.0)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user