Browse Source

chore: use HashMap intead of Vec (#8090)

Fangdun Tsai 2 years ago
parent
commit
62dd923132
2 changed files with 9 additions and 8 deletions
  1. 3 3
      frameworks/Rust/viz/Cargo.toml
  2. 6 5
      frameworks/Rust/viz/src/db_pg.rs

+ 3 - 3
frameworks/Rust/viz/Cargo.toml

@@ -24,7 +24,7 @@ path = "src/main_diesel.rs"
 required-features = ["diesel", "diesel-async", "sailfish"]
 
 [dependencies]
-viz = "0.4.9"
+viz = "0.4.10"
 hyper = "0.14.25"
 atoi = "2.0"
 serde = { version = "1.0", features = ["derive"] }
@@ -32,8 +32,8 @@ nanorand = "0.7"
 thiserror = "1.0"
 futures-util = "0.3.27"
 
-tokio = { version = "1.26", features = ["full"] }
-tokio-postgres = { version = "0.7.7", optional = true }
+tokio = { version = "1.27", features = ["full"] }
+tokio-postgres = { version = "0.7.8", optional = true }
 sqlx = { version = "0.6.3", features = [
   "postgres",
   "macros",

+ 6 - 5
frameworks/Rust/viz/src/db_pg.rs

@@ -1,4 +1,4 @@
-use std::{borrow::Cow, fmt::Write, io, sync::Arc};
+use std::{borrow::Cow, collections::HashMap, fmt::Write, io, sync::Arc};
 
 use futures_util::{stream::FuturesUnordered, TryFutureExt, TryStreamExt};
 use nanorand::{Rng, WyRand};
@@ -37,7 +37,7 @@ pub struct PgConnection {
     client: Client,
     world: Statement,
     fortune: Statement,
-    updates: Vec<Statement>,
+    updates: HashMap<u16, Statement>,
 }
 
 impl PgConnection {
@@ -54,7 +54,7 @@ impl PgConnection {
         });
 
         let fortune = client.prepare("SELECT * FROM fortune").await.unwrap();
-        let mut updates = Vec::new();
+        let mut updates = HashMap::new();
 
         for num in 1..=500u16 {
             let mut pl = 1;
@@ -77,7 +77,7 @@ impl PgConnection {
             q.pop();
             q.push(')');
 
-            updates.push(client.prepare(&q).await.unwrap());
+            updates.insert(num, client.prepare(&q).await.unwrap());
         }
 
         let world = client
@@ -137,6 +137,7 @@ impl PgConnection {
             }));
         }
 
+        let st = self.updates.get(&num).unwrap();
         let worlds = worlds.try_collect::<Vec<World>>().await?;
 
         let num = num as usize;
@@ -151,7 +152,7 @@ impl PgConnection {
             params.push(&w.id);
         }
 
-        self.client.query(&self.updates[num - 1], &params).await?;
+        self.client.query(st, &params).await?;
 
         Ok(worlds)
     }