Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] String copies refactor #41

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions src/akka/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,25 +32,25 @@ async fn get_actors_async(url: &String, timeout: u64) -> Result<Vec<ActorTreeNod
let url = format!("{}?timeout={}", url, timeout);
let response = reqwest::get(&url).await.map_err(|e| e.to_string())?;
if response.status().is_success() {
let mut response_body: HashMap<String, Value> = response.json().await.map_err(|e| e.to_string())?;
Ok(build_actor_tree(&mut response_body))
let response_body: HashMap<String, Value> = response.json().await.map_err(|e| e.to_string())?;
Ok(build_actor_tree(response_body))
} else {
Err(format!("Request to get actor tree failed with status: {}", response.status()))
}
}

fn build_actor_tree(json: &mut HashMap<String, Value>) -> Vec<ActorTreeNode> {
fn build_actor_tree(json: HashMap<String, Value>) -> Vec<ActorTreeNode> {
let mut actors: Vec<ActorTreeNode> = vec![];
// user actors should go first
if let Some(v) = json.get("user") {
actors.push(ActorTreeNode { name: "user".to_string(), parent: None, id: 1 });
build_actor_tree_iter(&v, Some(1), &mut actors)
actors.push(ActorTreeNode { name: "user".to_owned(), parent: None, id: 1 });
build_actor_tree_iter(v, Some(1), &mut actors)
}

for (k, v) in json {
if k != "user" {
let id = actors.len() + 1;
actors.push(ActorTreeNode { name: k.to_owned(), parent: None, id });
actors.push(ActorTreeNode { name: k, parent: None, id });
build_actor_tree_iter(&v, Some(id), &mut actors)
}
}
Expand All @@ -75,6 +75,6 @@ async fn get_actor_system_status_async(url: &String, timeout: u64) -> Result<Act
let body: ActorSystemStatus = response.json().await.map_err(|e| e.to_string())?;
Ok(body)
} else {
return Err(format!("Request to get actor count failed with status {}", response.status()))
Err(format!("Request to get actor count failed with status {}", response.status()))
}
}
6 changes: 3 additions & 3 deletions src/akka/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ pub struct ActorSystemStatus {

impl DeadLettersWindow {
pub fn max(&self) -> u32 {
vec![self.dead_letters.count, self.unhandled.count, self.dropped.count].iter().max().map(|x| x.to_owned()).unwrap_or(0)
vec![self.dead_letters.count, self.unhandled.count, self.dropped.count].into_iter().max().unwrap_or(0)
}

pub fn total(&self) -> u32 {
Expand Down Expand Up @@ -154,9 +154,9 @@ impl DeadLettersUIMessage {
if diff <= 0 {
"just now".to_owned()
} else if diff_min > 0 {
format!("{} min ago", diff_min).to_owned()
format!("{} min ago", diff_min)
} else {
format!("{} sec ago", diff_sec).to_owned()
format!("{} sec ago", diff_sec)
};
format!("<{}> {}", ago, self.message)
}
Expand Down
28 changes: 12 additions & 16 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,6 @@ use crate::jmx::model::{HikariMetrics, JMXConnectionSettings, SlickConfig, Slick
use crate::widgets::tree;
use crate::zio::model::{Fiber, FiberCount, FiberStatus};

pub struct UIFiber {
pub label: String,
pub dump: String,
}

#[derive(Clone)]
pub enum AppTabKind {
ZMX,
Expand Down Expand Up @@ -71,7 +66,7 @@ impl ZMXTab {
pub fn new() -> ZMXTab {
ZMXTab {
fibers: StatefulList::with_items(vec![]),
selected_fiber_dump: ("".to_string(), 1),
selected_fiber_dump: ("".to_owned(), 1),
fiber_dump_all: vec![],
scroll: 0,
fiber_counts: VecDeque::new(),
Expand Down Expand Up @@ -106,12 +101,14 @@ impl ZMXTab {
}

pub fn replace_fiber_dump(&mut self, dump: Vec<Fiber>) {
let list: Vec<UIFiber> = tree::tree_list_widget(dump, true)
.iter()
.map(|(label, fb)| UIFiber { label: label.to_owned(), dump: fb.dump.to_owned() })
.collect();
let mut fib_labels: Vec<String> = list.iter().map(|f| f.label.clone()).collect();
let mut fib_dumps = list.iter().map(|f| f.dump.to_owned()).collect::<Vec<String>>();
let mut fib_labels: Vec<String> = Vec::new();
let mut fib_dumps: Vec<String> = Vec::new();
tree::tree_list_widget(dump, true)
.into_iter()
.for_each(|(labels, fiber)| {
fib_labels.push(labels);
fib_dumps.push(fiber.dump);
});

self.fibers.items.clear();
self.fibers.items.append(&mut fib_labels);
Expand Down Expand Up @@ -147,7 +144,7 @@ impl ZMXTab {
}

fn prepare_dump(s: String) -> (String, u16) {
(s.clone(), s.lines().collect::<Vec<&str>>().len() as u16)
(s.to_owned(), s.lines().size_hint().0 as u16)
}
}

Expand Down Expand Up @@ -240,8 +237,8 @@ impl AkkaTab {

pub fn update_actor_tree(&mut self, actors: Vec<ActorTreeNode>) {
let mut list: Vec<String> = tree::tree_list_widget(actors, false)
.iter()
.map(|x| x.0.to_owned())
.into_iter()
.map(|x| x.0)
.collect();

self.actors.items.clear();
Expand Down Expand Up @@ -460,7 +457,6 @@ mod tests {

use crate::app::{StatefulList, ZMXTab};
use crate::zio::model::{Fiber, FiberStatus};
use crate::zio::zmx::StubZMXClient;

#[test]
fn zmx_tab_dumps_fibers() {
Expand Down
2 changes: 1 addition & 1 deletion src/fetcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ impl Fetcher {
"service:jmx:rmi://{}/jndi/rmi://{}/jmxrmi",
&conn.address, &conn.address
);
let url = jmx::MBeanAddress::service_url(url_str.clone());
let url = jmx::MBeanAddress::service_url(&url_str);
MBeanClient::connect(url)
.map(|x| Some(JMXClient::new(x, conn.db_pool_name.clone())))
.map_err(|e| format!(
Expand Down
33 changes: 16 additions & 17 deletions src/widgets/tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,23 +59,22 @@ impl TreeWidgetNode for ActorTreeNode {
/// └#6 Suspended
///
pub fn tree_list_widget<T: Clone + TreeWidgetNode>(items: Vec<T>, print_ids: bool) -> Vec<(String, T)> {
let tree = &make_tree(items);
let tree = make_tree(items);

// get the initial printable tree
let temp: Vec<(String, T)> = match tree.get(&None) {
Some(v) => list_tree_nodes(v.to_vec(), 0, tree, "".to_string(), print_ids),
Some(v) => list_tree_nodes(v, 0, &tree, &"".to_owned(), print_ids),
None => vec![]
};

// find the max length of the line to calculate padding
let max_len = &temp.iter()
let max_len = temp.iter()
.max_by_key(|i| i.0.chars().count())
.map_or(0, |i| i.0.chars().count());


// add label using padding
temp.iter().map(|i| {
(format!("{:width$} {}", i.0, i.1.label(), width = max_len), i.1.to_owned())
temp.into_iter().map(|i| {
(format!("{:width$} {}", i.0, i.1.label(), width = max_len), i.1)
}).collect()
}

Expand Down Expand Up @@ -103,32 +102,32 @@ pub fn tree_list_widget<T: Clone + TreeWidgetNode>(items: Vec<T>, print_ids: boo
/// └#6
///
fn list_tree_nodes<T: Clone + TreeWidgetNode>(
items: Vec<T>,
items: &Vec<T>,
level: usize,
tree: &HashMap<Option<usize>, Vec<T>>,
indent: String,
indent: &String,
print_ids: bool) -> Vec<(String, T)> {
let size = items.len();

if size == 0 {
vec![]
} else {
let i = items.last().unwrap();
let printed_id = if print_ids { i.id().to_string() } else { "".to_string() };
let parent: (String, T) = (format!("{:width$}└─#{}", indent.clone(), printed_id, width = level), i.to_owned());
let printed_id = if print_ids { i.id().to_string() } else { "".to_owned() };
let parent: (String, T) = (format!("{:width$}└─#{}", indent, printed_id, width = level), i.to_owned());
let mut last_node = tree.get(&Some(i.id())).map(|v|
list_tree_nodes(v.to_vec(), level + 1, tree, format!("{} ", indent.clone()), print_ids)
list_tree_nodes(v, level + 1, tree, &format!("{} ", indent), print_ids)
).unwrap_or(vec![]);
last_node.insert(0, parent);

if items.len() > 1 {
let new_indent = format!("{}│ ", indent.clone());
let new_indent = &format!("{}│ ", indent);
let n = items.len() - 1;
let mut all: Vec<(String, T)> = items[..n].iter().fold(vec![], |mut acc, i| {
let printed_id = if print_ids { i.id().to_string() } else { "".to_string() };
let parent: (String, T) = (format!("{:width$}├─#{}", indent.clone(), printed_id, width = level), i.to_owned());
let printed_id = if print_ids { i.id().to_string() } else { "".to_owned() };
let parent: (String, T) = (format!("{:width$}├─#{}", indent, printed_id, width = level), i.to_owned());
let mut nodes: Vec<(String, T)> = tree.get(&Some(i.id())).map(|v|
list_tree_nodes(v.to_vec(), level + 1, tree, new_indent.clone(), print_ids)
list_tree_nodes(v, level + 1, tree, new_indent, print_ids)
).unwrap_or(vec![]);
nodes.insert(0, parent);
acc.append(&mut nodes);
Expand Down Expand Up @@ -161,9 +160,9 @@ fn list_tree_nodes<T: Clone + TreeWidgetNode>(
/// _ -> (0,7,6)
/// 4 -> 5
fn make_tree<T: Clone + TreeWidgetNode>(items: Vec<T>) -> HashMap<Option<usize>, Vec<T>> {
items.iter().fold(HashMap::new(), |mut acc, f| {
items.into_iter().fold(HashMap::new(), |mut acc, f| {
let v = acc.entry(f.parent_id()).or_insert(vec![]);
v.push(f.to_owned());
v.push(f);
acc
})
}