commit d7db8e7783e3330a9427af2966ee82af236f7a5d
parent 5beb70c07ecc35b109f7d3b891227f50a20b5660
Author: thomas.vigouroux@protonmail.com <thomas.vigouroux@protonmail.com>
Date: Fri, 17 Dec 2021 12:53:48 +0000
Update
Diffstat:
3 files changed, 103 insertions(+), 0 deletions(-)
diff --git a/src/cmds/mod.rs b/src/cmds/mod.rs
@@ -0,0 +1,22 @@
+pub mod stats;
+use std::default::Default;
+use std::future::Future;
+use futures::future::BoxFuture;
+
+pub struct Command {
+ name: &'static str,
+ description: &'static str,
+ args: &'static [&'static str],
+ opt_args: &'static [&'static str],
+}
+
+impl Default for Command {
+ fn default() -> Self {
+ Command {
+ name: "",
+ description: "",
+ args: &[],
+ opt_args: &[],
+ }
+ }
+}
diff --git a/src/cmds/stats.rs b/src/cmds/stats.rs
@@ -0,0 +1,62 @@
+use std::collections::HashMap;
+use crate::pack::{pack_data, unpack_data};
+use crate::requests::difinu;
+use super::Command;
+
+const VORTO_PATH: &'static str = "vorto.bincode";
+pub async fn add_words(frazo: String) {
+ let mut h: HashMap<String, usize> = unpack_data(VORTO_PATH).unwrap_or_default();
+
+ for vorto in frazo.split_ascii_whitespace() {
+ if let Ok(tro) = difinu(vorto.to_owned()).await {
+ if let Some(vf) = tro
+ .vortfarado
+ .iter()
+ .filter(|vf| vf.partoj.len() > 1)
+ .next()
+ {
+ let mut vera_vorto = String::with_capacity(vorto.len());
+
+ if vf.partoj.len() > 1 {
+ // Konstrui la vera vorto
+ // sen la termnoj
+ for p in vf.partoj.iter().take_while(|p| p.vorto.is_some()) {
+ vera_vorto.push_str(p.parto.as_str());
+ }
+ vera_vorto.push('-');
+ } else {
+ // vorto estas la vera, nura, vorto
+ vera_vorto = vorto.to_owned()
+ }
+
+ if let Some(v) = h.get_mut(&vera_vorto) {
+ *v += 1;
+ } else {
+ h.insert(vera_vorto, 1);
+ }
+ }
+ }
+ }
+
+ pack_data(VORTO_PATH, &h).unwrap(); // Tre neebla, sed...
+}
+
+pub fn stats() -> Result<String, String> {
+ let mut h: HashMap<String, usize> = unpack_data(VORTO_PATH)?;
+ let mut h: Vec<(String, usize)> = h.drain().collect();
+ h.sort_by_cached_key(|(_, s)| *s);
+ h.reverse();
+
+ Ok(h.iter()
+ .take(10)
+ .map(|(v, o)| format!("{}: {}", v, o))
+ .collect::<Vec<String>>()
+ .join(", "))
+}
+
+pub const STAT_CMD: Command = Command {
+ name: "statistiko",
+ description: "Donu la 10 vortoj plej uzataj.",
+ args: &[],
+ opt_args: &[],
+};
diff --git a/src/pack.rs b/src/pack.rs
@@ -0,0 +1,19 @@
+use serde::{de::DeserializeOwned, ser::Serialize};
+
+pub fn unpack_data<T>(fname: &str) -> Result<T, String>
+where
+ T: DeserializeOwned,
+{
+ let r = snap::read::FrameDecoder::new(std::fs::File::open(fname).map_err(|e| e.to_string())?);
+ bincode::deserialize_from(r).map_err(|e| e.to_string())
+}
+
+pub fn pack_data<T>(fname: &str, data: &T) -> Result<(), String>
+where
+ T: Serialize,
+{
+ let f = std::fs::File::create(fname).map_err(|e| e.to_string())?;
+ let w = snap::write::FrameEncoder::new(f);
+ bincode::serialize_into(w, data).map_err(|e| e.to_string())?;
+ Ok(())
+}