[go: up one dir, main page]

Struct Networks

Source
pub struct Networks { /* private fields */ }
Expand description

Interacting with network interfaces.

use sysinfo::Networks;

let networks = Networks::new_with_refreshed_list();
for (interface_name, network) in &networks {
    println!("[{interface_name}]: {network:?}");
}

Implementations§

Source§

impl Networks

Source

pub fn new() -> Self

Creates a new empty Networks type.

If you want it to be filled directly, take a look at Networks::new_with_refreshed_list.

use sysinfo::Networks;

let mut networks = Networks::new();
networks.refresh(true);
for (interface_name, network) in &networks {
    println!("[{interface_name}]: {network:?}");
}
Source

pub fn new_with_refreshed_list() -> Self

Creates a new Networks type with the network interfaces list loaded.

use sysinfo::Networks;

let networks = Networks::new_with_refreshed_list();
for network in &networks {
    println!("{network:?}");
}
Examples found in repository?
examples/simple.rs (line 463)
460fn main() {
461    println!("Getting system information...");
462    let mut system = System::new_all();
463    let mut networks = Networks::new_with_refreshed_list();
464    let mut disks = Disks::new_with_refreshed_list();
465    let mut components = Components::new_with_refreshed_list();
466    let mut users = Users::new_with_refreshed_list();
467
468    println!("Done.");
469    let t_stin = io::stdin();
470    let mut stin = t_stin.lock();
471    let mut done = false;
472
473    println!("To get the commands' list, enter 'help'.");
474    while !done {
475        let mut input = String::new();
476        write!(&mut io::stdout(), "> ");
477        io::stdout().flush();
478
479        stin.read_line(&mut input);
480        if input.is_empty() {
481            // The string is empty, meaning there is no '\n', meaning
482            // that the user used CTRL+D so we can just quit!
483            println!("\nLeaving, bye!");
484            break;
485        }
486        if (&input as &str).ends_with('\n') {
487            input.pop();
488        }
489        done = interpret_input(
490            input.as_ref(),
491            &mut system,
492            &mut networks,
493            &mut disks,
494            &mut components,
495            &mut users,
496        );
497    }
498}
Source

pub fn list(&self) -> &HashMap<String, NetworkData>

Returns the network interfaces map.

use sysinfo::Networks;

let networks = Networks::new_with_refreshed_list();
for network in networks.list() {
    println!("{network:?}");
}
Source

pub fn refresh(&mut self, remove_not_listed_interfaces: bool)

Refreshes the network interfaces.

use sysinfo::Networks;

let mut networks = Networks::new_with_refreshed_list();
// Wait some time...? Then refresh the data of each network.
networks.refresh(true);
Examples found in repository?
examples/simple.rs (line 171)
149fn interpret_input(
150    input: &str,
151    sys: &mut System,
152    networks: &mut Networks,
153    disks: &mut Disks,
154    components: &mut Components,
155    users: &mut Users,
156) -> bool {
157    match input.trim() {
158        "help" => print_help(),
159        "refresh_disks" => {
160            writeln!(&mut io::stdout(), "Refreshing disk list...");
161            disks.refresh(true);
162            writeln!(&mut io::stdout(), "Done.");
163        }
164        "refresh_users" => {
165            writeln!(&mut io::stdout(), "Refreshing user list...");
166            users.refresh();
167            writeln!(&mut io::stdout(), "Done.");
168        }
169        "refresh_networks" => {
170            writeln!(&mut io::stdout(), "Refreshing network list...");
171            networks.refresh(true);
172            writeln!(&mut io::stdout(), "Done.");
173        }
174        "refresh_components" => {
175            writeln!(&mut io::stdout(), "Refreshing component list...");
176            components.refresh(true);
177            writeln!(&mut io::stdout(), "Done.");
178        }
179        "refresh_cpu" => {
180            writeln!(&mut io::stdout(), "Refreshing CPUs...");
181            sys.refresh_cpu_all();
182            writeln!(&mut io::stdout(), "Done.");
183        }
184        "signals" => {
185            let mut nb = 1i32;
186
187            for sig in signals {
188                writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
189                nb += 1;
190            }
191        }
192        "cpus" => {
193            // Note: you should refresh a few times before using this, so that usage statistics
194            // can be ascertained
195            writeln!(
196                &mut io::stdout(),
197                "number of physical cores: {}",
198                sys.physical_core_count()
199                    .map(|c| c.to_string())
200                    .unwrap_or_else(|| "Unknown".to_owned()),
201            );
202            writeln!(
203                &mut io::stdout(),
204                "total CPU usage: {}%",
205                sys.global_cpu_usage(),
206            );
207            for cpu in sys.cpus() {
208                writeln!(&mut io::stdout(), "{cpu:?}");
209            }
210        }
211        "memory" => {
212            writeln!(
213                &mut io::stdout(),
214                "total memory:     {: >10} KB",
215                sys.total_memory() / 1_000
216            );
217            writeln!(
218                &mut io::stdout(),
219                "available memory: {: >10} KB",
220                sys.available_memory() / 1_000
221            );
222            writeln!(
223                &mut io::stdout(),
224                "used memory:      {: >10} KB",
225                sys.used_memory() / 1_000
226            );
227            writeln!(
228                &mut io::stdout(),
229                "total swap:       {: >10} KB",
230                sys.total_swap() / 1_000
231            );
232            writeln!(
233                &mut io::stdout(),
234                "used swap:        {: >10} KB",
235                sys.used_swap() / 1_000
236            );
237        }
238        "quit" | "exit" => return true,
239        "all" => {
240            for (pid, proc_) in sys.processes() {
241                writeln!(
242                    &mut io::stdout(),
243                    "{}:{} status={:?}",
244                    pid,
245                    proc_.name().to_string_lossy(),
246                    proc_.status()
247                );
248            }
249        }
250        "frequency" => {
251            for cpu in sys.cpus() {
252                writeln!(
253                    &mut io::stdout(),
254                    "[{}] {} MHz",
255                    cpu.name(),
256                    cpu.frequency(),
257                );
258            }
259        }
260        "vendor_id" => {
261            writeln!(
262                &mut io::stdout(),
263                "vendor ID: {}",
264                sys.cpus()[0].vendor_id()
265            );
266        }
267        "brand" => {
268            writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
269        }
270        "load_avg" => {
271            let load_avg = System::load_average();
272            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
273            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
274            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
275        }
276        e if e.starts_with("show ") => {
277            let tmp: Vec<&str> = e.split(' ').collect();
278
279            if tmp.len() != 2 {
280                writeln!(
281                    &mut io::stdout(),
282                    "show command takes a pid or a name in parameter!"
283                );
284                writeln!(&mut io::stdout(), "example: show 1254");
285            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
286                match sys.process(pid) {
287                    Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
288                    None => writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found"),
289                };
290            } else {
291                let proc_name = tmp[1];
292                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
293                    writeln!(
294                        &mut io::stdout(),
295                        "==== {} ====",
296                        proc_.name().to_string_lossy()
297                    );
298                    writeln!(&mut io::stdout(), "{proc_:?}");
299                }
300            }
301        }
302        "temperature" => {
303            for component in components.iter() {
304                writeln!(&mut io::stdout(), "{component:?}");
305            }
306        }
307        "network" => {
308            for (interface_name, data) in networks.iter() {
309                writeln!(
310                    &mut io::stdout(),
311                    "{}:\n  ether {}\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
312                    interface_name,
313                    data.mac_address(),
314                    data.received(),
315                    data.total_received(),
316                    data.transmitted(),
317                    data.total_transmitted(),
318                );
319            }
320        }
321        "show" => {
322            writeln!(
323                &mut io::stdout(),
324                "'show' command expects a pid number or a process name"
325            );
326        }
327        e if e.starts_with("kill ") => {
328            let tmp: Vec<&str> = e.split(' ').collect();
329
330            if tmp.len() != 3 {
331                writeln!(
332                    &mut io::stdout(),
333                    "kill command takes the pid and a signal number in parameter!"
334                );
335                writeln!(&mut io::stdout(), "example: kill 1254 9");
336            } else {
337                let pid = Pid::from_str(tmp[1]).unwrap();
338                let signal = i32::from_str(tmp[2]).unwrap();
339
340                if signal < 1 || signal > 31 {
341                    writeln!(
342                        &mut io::stdout(),
343                        "Signal must be between 0 and 32 ! See the signals list with the \
344                         signals command"
345                    );
346                } else {
347                    match sys.process(pid) {
348                        Some(p) => {
349                            if let Some(res) =
350                                p.kill_with(*signals.get(signal as usize - 1).unwrap())
351                            {
352                                writeln!(&mut io::stdout(), "kill: {res}");
353                            } else {
354                                writeln!(
355                                    &mut io::stdout(),
356                                    "kill: signal not supported on this platform"
357                                );
358                            }
359                        }
360                        None => {
361                            writeln!(&mut io::stdout(), "pid not found");
362                        }
363                    };
364                }
365            }
366        }
367        "disks" => {
368            for disk in disks {
369                writeln!(&mut io::stdout(), "{disk:?}");
370            }
371        }
372        "users" => {
373            for user in users {
374                writeln!(
375                    &mut io::stdout(),
376                    "{:?} => {:?}",
377                    user.name(),
378                    user.groups()
379                );
380            }
381        }
382        "boot_time" => {
383            writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
384        }
385        "uptime" => {
386            let up = System::uptime();
387            let mut uptime = up;
388            let days = uptime / 86400;
389            uptime -= days * 86400;
390            let hours = uptime / 3600;
391            uptime -= hours * 3600;
392            let minutes = uptime / 60;
393            writeln!(
394                &mut io::stdout(),
395                "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
396            );
397        }
398        x if x.starts_with("refresh") => {
399            if x == "refresh" {
400                writeln!(&mut io::stdout(), "Getting processes' information...");
401                sys.refresh_all();
402                writeln!(&mut io::stdout(), "Done.");
403            } else if x.starts_with("refresh ") {
404                writeln!(&mut io::stdout(), "Getting process' information...");
405                if let Some(pid) = x
406                    .split(' ')
407                    .filter_map(|pid| pid.parse().ok())
408                    .take(1)
409                    .next()
410                {
411                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
412                        writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
413                    } else {
414                        writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
415                    }
416                } else {
417                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
418                }
419            } else {
420                writeln!(
421                    &mut io::stdout(),
422                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
423                     list.",
424                );
425            }
426        }
427        "pid" => {
428            writeln!(
429                &mut io::stdout(),
430                "PID: {}",
431                sysinfo::get_current_pid().expect("failed to get PID")
432            );
433        }
434        "system" => {
435            writeln!(
436                &mut io::stdout(),
437                "System name:              {}\n\
438                 System kernel version:    {}\n\
439                 System OS version:        {}\n\
440                 System OS (long) version: {}\n\
441                 System host name:         {}",
442                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
443                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
444                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
445                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
446                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
447            );
448        }
449        e => {
450            writeln!(
451                &mut io::stdout(),
452                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
453                 list.",
454            );
455        }
456    }
457    false
458}

Methods from Deref<Target = HashMap<String, NetworkData>>§

1.0.0

pub fn capacity(&self) -> usize

Returns the number of elements the map can hold without reallocating.

This number is a lower bound; the HashMap<K, V> might be able to hold more, but is guaranteed to be able to hold at least this many.

§Examples
use std::collections::HashMap;
let map: HashMap<i32, i32> = HashMap::with_capacity(100);
assert!(map.capacity() >= 100);
1.0.0

pub fn keys(&self) -> Keys<'_, K, V>

An iterator visiting all keys in arbitrary order. The iterator element type is &'a K.

§Examples
use std::collections::HashMap;

let map = HashMap::from([
    ("a", 1),
    ("b", 2),
    ("c", 3),
]);

for key in map.keys() {
    println!("{key}");
}
§Performance

In the current implementation, iterating over keys takes O(capacity) time instead of O(len) because it internally visits empty buckets too.

1.0.0

pub fn values(&self) -> Values<'_, K, V>

An iterator visiting all values in arbitrary order. The iterator element type is &'a V.

§Examples
use std::collections::HashMap;

let map = HashMap::from([
    ("a", 1),
    ("b", 2),
    ("c", 3),
]);

for val in map.values() {
    println!("{val}");
}
§Performance

In the current implementation, iterating over values takes O(capacity) time instead of O(len) because it internally visits empty buckets too.

1.0.0

pub fn iter(&self) -> Iter<'_, K, V>

An iterator visiting all key-value pairs in arbitrary order. The iterator element type is (&'a K, &'a V).

§Examples
use std::collections::HashMap;

let map = HashMap::from([
    ("a", 1),
    ("b", 2),
    ("c", 3),
]);

for (key, val) in map.iter() {
    println!("key: {key} val: {val}");
}
§Performance

In the current implementation, iterating over map takes O(capacity) time instead of O(len) because it internally visits empty buckets too.

Examples found in repository?
examples/simple.rs (line 308)
149fn interpret_input(
150    input: &str,
151    sys: &mut System,
152    networks: &mut Networks,
153    disks: &mut Disks,
154    components: &mut Components,
155    users: &mut Users,
156) -> bool {
157    match input.trim() {
158        "help" => print_help(),
159        "refresh_disks" => {
160            writeln!(&mut io::stdout(), "Refreshing disk list...");
161            disks.refresh(true);
162            writeln!(&mut io::stdout(), "Done.");
163        }
164        "refresh_users" => {
165            writeln!(&mut io::stdout(), "Refreshing user list...");
166            users.refresh();
167            writeln!(&mut io::stdout(), "Done.");
168        }
169        "refresh_networks" => {
170            writeln!(&mut io::stdout(), "Refreshing network list...");
171            networks.refresh(true);
172            writeln!(&mut io::stdout(), "Done.");
173        }
174        "refresh_components" => {
175            writeln!(&mut io::stdout(), "Refreshing component list...");
176            components.refresh(true);
177            writeln!(&mut io::stdout(), "Done.");
178        }
179        "refresh_cpu" => {
180            writeln!(&mut io::stdout(), "Refreshing CPUs...");
181            sys.refresh_cpu_all();
182            writeln!(&mut io::stdout(), "Done.");
183        }
184        "signals" => {
185            let mut nb = 1i32;
186
187            for sig in signals {
188                writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
189                nb += 1;
190            }
191        }
192        "cpus" => {
193            // Note: you should refresh a few times before using this, so that usage statistics
194            // can be ascertained
195            writeln!(
196                &mut io::stdout(),
197                "number of physical cores: {}",
198                sys.physical_core_count()
199                    .map(|c| c.to_string())
200                    .unwrap_or_else(|| "Unknown".to_owned()),
201            );
202            writeln!(
203                &mut io::stdout(),
204                "total CPU usage: {}%",
205                sys.global_cpu_usage(),
206            );
207            for cpu in sys.cpus() {
208                writeln!(&mut io::stdout(), "{cpu:?}");
209            }
210        }
211        "memory" => {
212            writeln!(
213                &mut io::stdout(),
214                "total memory:     {: >10} KB",
215                sys.total_memory() / 1_000
216            );
217            writeln!(
218                &mut io::stdout(),
219                "available memory: {: >10} KB",
220                sys.available_memory() / 1_000
221            );
222            writeln!(
223                &mut io::stdout(),
224                "used memory:      {: >10} KB",
225                sys.used_memory() / 1_000
226            );
227            writeln!(
228                &mut io::stdout(),
229                "total swap:       {: >10} KB",
230                sys.total_swap() / 1_000
231            );
232            writeln!(
233                &mut io::stdout(),
234                "used swap:        {: >10} KB",
235                sys.used_swap() / 1_000
236            );
237        }
238        "quit" | "exit" => return true,
239        "all" => {
240            for (pid, proc_) in sys.processes() {
241                writeln!(
242                    &mut io::stdout(),
243                    "{}:{} status={:?}",
244                    pid,
245                    proc_.name().to_string_lossy(),
246                    proc_.status()
247                );
248            }
249        }
250        "frequency" => {
251            for cpu in sys.cpus() {
252                writeln!(
253                    &mut io::stdout(),
254                    "[{}] {} MHz",
255                    cpu.name(),
256                    cpu.frequency(),
257                );
258            }
259        }
260        "vendor_id" => {
261            writeln!(
262                &mut io::stdout(),
263                "vendor ID: {}",
264                sys.cpus()[0].vendor_id()
265            );
266        }
267        "brand" => {
268            writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
269        }
270        "load_avg" => {
271            let load_avg = System::load_average();
272            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
273            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
274            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
275        }
276        e if e.starts_with("show ") => {
277            let tmp: Vec<&str> = e.split(' ').collect();
278
279            if tmp.len() != 2 {
280                writeln!(
281                    &mut io::stdout(),
282                    "show command takes a pid or a name in parameter!"
283                );
284                writeln!(&mut io::stdout(), "example: show 1254");
285            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
286                match sys.process(pid) {
287                    Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
288                    None => writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found"),
289                };
290            } else {
291                let proc_name = tmp[1];
292                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
293                    writeln!(
294                        &mut io::stdout(),
295                        "==== {} ====",
296                        proc_.name().to_string_lossy()
297                    );
298                    writeln!(&mut io::stdout(), "{proc_:?}");
299                }
300            }
301        }
302        "temperature" => {
303            for component in components.iter() {
304                writeln!(&mut io::stdout(), "{component:?}");
305            }
306        }
307        "network" => {
308            for (interface_name, data) in networks.iter() {
309                writeln!(
310                    &mut io::stdout(),
311                    "{}:\n  ether {}\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
312                    interface_name,
313                    data.mac_address(),
314                    data.received(),
315                    data.total_received(),
316                    data.transmitted(),
317                    data.total_transmitted(),
318                );
319            }
320        }
321        "show" => {
322            writeln!(
323                &mut io::stdout(),
324                "'show' command expects a pid number or a process name"
325            );
326        }
327        e if e.starts_with("kill ") => {
328            let tmp: Vec<&str> = e.split(' ').collect();
329
330            if tmp.len() != 3 {
331                writeln!(
332                    &mut io::stdout(),
333                    "kill command takes the pid and a signal number in parameter!"
334                );
335                writeln!(&mut io::stdout(), "example: kill 1254 9");
336            } else {
337                let pid = Pid::from_str(tmp[1]).unwrap();
338                let signal = i32::from_str(tmp[2]).unwrap();
339
340                if signal < 1 || signal > 31 {
341                    writeln!(
342                        &mut io::stdout(),
343                        "Signal must be between 0 and 32 ! See the signals list with the \
344                         signals command"
345                    );
346                } else {
347                    match sys.process(pid) {
348                        Some(p) => {
349                            if let Some(res) =
350                                p.kill_with(*signals.get(signal as usize - 1).unwrap())
351                            {
352                                writeln!(&mut io::stdout(), "kill: {res}");
353                            } else {
354                                writeln!(
355                                    &mut io::stdout(),
356                                    "kill: signal not supported on this platform"
357                                );
358                            }
359                        }
360                        None => {
361                            writeln!(&mut io::stdout(), "pid not found");
362                        }
363                    };
364                }
365            }
366        }
367        "disks" => {
368            for disk in disks {
369                writeln!(&mut io::stdout(), "{disk:?}");
370            }
371        }
372        "users" => {
373            for user in users {
374                writeln!(
375                    &mut io::stdout(),
376                    "{:?} => {:?}",
377                    user.name(),
378                    user.groups()
379                );
380            }
381        }
382        "boot_time" => {
383            writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
384        }
385        "uptime" => {
386            let up = System::uptime();
387            let mut uptime = up;
388            let days = uptime / 86400;
389            uptime -= days * 86400;
390            let hours = uptime / 3600;
391            uptime -= hours * 3600;
392            let minutes = uptime / 60;
393            writeln!(
394                &mut io::stdout(),
395                "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
396            );
397        }
398        x if x.starts_with("refresh") => {
399            if x == "refresh" {
400                writeln!(&mut io::stdout(), "Getting processes' information...");
401                sys.refresh_all();
402                writeln!(&mut io::stdout(), "Done.");
403            } else if x.starts_with("refresh ") {
404                writeln!(&mut io::stdout(), "Getting process' information...");
405                if let Some(pid) = x
406                    .split(' ')
407                    .filter_map(|pid| pid.parse().ok())
408                    .take(1)
409                    .next()
410                {
411                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
412                        writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
413                    } else {
414                        writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
415                    }
416                } else {
417                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
418                }
419            } else {
420                writeln!(
421                    &mut io::stdout(),
422                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
423                     list.",
424                );
425            }
426        }
427        "pid" => {
428            writeln!(
429                &mut io::stdout(),
430                "PID: {}",
431                sysinfo::get_current_pid().expect("failed to get PID")
432            );
433        }
434        "system" => {
435            writeln!(
436                &mut io::stdout(),
437                "System name:              {}\n\
438                 System kernel version:    {}\n\
439                 System OS version:        {}\n\
440                 System OS (long) version: {}\n\
441                 System host name:         {}",
442                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
443                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
444                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
445                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
446                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
447            );
448        }
449        e => {
450            writeln!(
451                &mut io::stdout(),
452                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
453                 list.",
454            );
455        }
456    }
457    false
458}
1.0.0

pub fn len(&self) -> usize

Returns the number of elements in the map.

§Examples
use std::collections::HashMap;

let mut a = HashMap::new();
assert_eq!(a.len(), 0);
a.insert(1, "a");
assert_eq!(a.len(), 1);
1.0.0

pub fn is_empty(&self) -> bool

Returns true if the map contains no elements.

§Examples
use std::collections::HashMap;

let mut a = HashMap::new();
assert!(a.is_empty());
a.insert(1, "a");
assert!(!a.is_empty());
1.9.0

pub fn hasher(&self) -> &S

Returns a reference to the map’s [BuildHasher].

§Examples
use std::collections::HashMap;
use std::hash::RandomState;

let hasher = RandomState::new();
let map: HashMap<i32, i32> = HashMap::with_hasher(hasher);
let hasher: &RandomState = map.hasher();
1.0.0

pub fn get<Q>(&self, k: &Q) -> Option<&V>
where K: Borrow<Q>, Q: Hash + Eq + ?Sized,

Returns a reference to the value corresponding to the key.

The key may be any borrowed form of the map’s key type, but [Hash] and [Eq] on the borrowed form must match those for the key type.

§Examples
use std::collections::HashMap;

let mut map = HashMap::new();
map.insert(1, "a");
assert_eq!(map.get(&1), Some(&"a"));
assert_eq!(map.get(&2), None);
1.40.0

pub fn get_key_value<Q>(&self, k: &Q) -> Option<(&K, &V)>
where K: Borrow<Q>, Q: Hash + Eq + ?Sized,

Returns the key-value pair corresponding to the supplied key. This is potentially useful:

  • for key types where non-identical keys can be considered equal;
  • for getting the &K stored key value from a borrowed &Q lookup key; or
  • for getting a reference to a key with the same lifetime as the collection.

The supplied key may be any borrowed form of the map’s key type, but [Hash] and [Eq] on the borrowed form must match those for the key type.

§Examples
use std::collections::HashMap;
use std::hash::{Hash, Hasher};

#[derive(Clone, Copy, Debug)]
struct S {
    id: u32,
    name: &'static str, // ignored by equality and hashing operations
}

impl PartialEq for S {
    fn eq(&self, other: &S) -> bool {
        self.id == other.id
    }
}

impl Eq for S {}

impl Hash for S {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.id.hash(state);
    }
}

let j_a = S { id: 1, name: "Jessica" };
let j_b = S { id: 1, name: "Jess" };
let p = S { id: 2, name: "Paul" };
assert_eq!(j_a, j_b);

let mut map = HashMap::new();
map.insert(j_a, "Paris");
assert_eq!(map.get_key_value(&j_a), Some((&j_a, &"Paris")));
assert_eq!(map.get_key_value(&j_b), Some((&j_a, &"Paris"))); // the notable case
assert_eq!(map.get_key_value(&p), None);
1.0.0

pub fn contains_key<Q>(&self, k: &Q) -> bool
where K: Borrow<Q>, Q: Hash + Eq + ?Sized,

Returns true if the map contains a value for the specified key.

The key may be any borrowed form of the map’s key type, but [Hash] and [Eq] on the borrowed form must match those for the key type.

§Examples
use std::collections::HashMap;

let mut map = HashMap::new();
map.insert(1, "a");
assert_eq!(map.contains_key(&1), true);
assert_eq!(map.contains_key(&2), false);

pub fn raw_entry(&self) -> RawEntryBuilder<'_, K, V, S>

🔬This is a nightly-only experimental API. (hash_raw_entry)

Creates a raw immutable entry builder for the HashMap.

Raw entries provide the lowest level of control for searching and manipulating a map. They must be manually initialized with a hash and then manually searched.

This is useful for

  • Hash memoization
  • Using a search key that doesn’t work with the Borrow trait
  • Using custom comparison logic without newtype wrappers

Unless you are in such a situation, higher-level and more foolproof APIs like get should be preferred.

Immutable raw entries have very limited use; you might instead want raw_entry_mut.

Trait Implementations§

Source§

impl Debug for Networks

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Networks

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Deref for Networks

Source§

type Target = HashMap<String, NetworkData>

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl<'a> IntoIterator for &'a Networks

Source§

type Item = (&'a String, &'a NetworkData)

The type of the elements being iterated over.
Source§

type IntoIter = Iter<'a, String, NetworkData>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl Serialize for Networks

Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

§

impl Freeze for Networks

§

impl RefUnwindSafe for Networks

§

impl Send for Networks

§

impl Sync for Networks

§

impl Unpin for Networks

§

impl UnwindSafe for Networks

Blanket Implementations§

§

impl<T> Any for T
where T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for T
where T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for T
where T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T, U> Into<U> for T
where U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of [From]<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.