Skip to content

web search done right

Replay ToString with Display (#134)

SekoiaTreeffbec7ac8068
diff --git a/crates/core/src/entrypoint/autosuggest_scrape.rs b/crates/core/src/entrypoint/autosuggest_scrape.rs
index be05a226..e05129d8 100644
--- a/crates/core/src/entrypoint/autosuggest_scrape.rs
+++ b/crates/core/src/entrypoint/autosuggest_scrape.rs
@@ -19,6 +19,7 @@ use std::{
path::Path,
str::FromStr,
};
+use std::fmt::Display;
use csv::Writer;
use indicatif::{ProgressBar, ProgressStyle};
@@ -65,11 +66,11 @@ pub enum Gl {
Us,
}
-impl ToString for Gl {
- fn to_string(&self) -> String {
- match self {
- Gl::Us => "us".to_string(),
- }
+impl Display for Gl {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}", match self {
+ Gl::Us => "us",
+ })
}
}
diff --git a/crates/core/src/query/parser.rs b/crates/core/src/query/parser.rs
index 03cbe67c..83cd8ad8 100644
--- a/crates/core/src/query/parser.rs
+++ b/crates/core/src/query/parser.rs
@@ -14,6 +14,7 @@
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
+use std::fmt::Display;
use tantivy::{
query::{BooleanQuery, Occur, PhraseQuery, TermQuery},
tokenizer::Tokenizer,
@@ -82,17 +83,17 @@ pub enum Term {
PossibleBang(String),
}
-impl ToString for Term {
- fn to_string(&self) -> String {
+impl Display for Term {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
- Term::Simple(term) => term.0.clone(),
- Term::Phrase(phrase) => "\"".to_string() + phrase.as_str() + "\"",
- Term::Not(term) => "-".to_string() + term.to_string().as_str(),
- Term::Site(site) => "site:".to_string() + site.as_str(),
- Term::Title(title) => "intitle:".to_string() + title.as_str(),
- Term::Body(body) => "inbody:".to_string() + body.as_str(),
- Term::Url(url) => "inurl:".to_string() + url.as_str(),
- Term::PossibleBang(bang) => BANG_PREFIXES[0].to_string() + bang.as_str(),
+ Term::Simple(term) => write!(f, "{}", term.0),
+ Term::Phrase(phrase) => write!(f, "\"{}\"", phrase),
+ Term::Not(term) => write!(f, "-{}", term),
+ Term::Site(site) => write!(f, "site:{}", site),
+ Term::Title(title) => write!(f, "intitle:{}", title),
+ Term::Body(body) => write!(f, "inbody:{}", body),
+ Term::Url(url) => write!(f, "inurl:{}", url),
+ Term::PossibleBang(bang) => write!(f, "{}{}", BANG_PREFIXES[0], bang),
}
}
}
diff --git a/crates/core/src/warc.rs b/crates/core/src/warc.rs
index 44336fa8..38fc9b01 100644
--- a/crates/core/src/warc.rs
+++ b/crates/core/src/warc.rs
@@ -17,6 +17,7 @@
use crate::distributed::retry_strategy::ExponentialBackoff;
use crate::{config::S3Config, config::WarcSource, Error, Result};
use std::collections::BTreeMap;
+use std::fmt::Display;
use std::fs::File;
use std::io::{BufRead, BufReader, Cursor, Read, Seek, Write};
use std::path::Path;
@@ -262,14 +263,15 @@ impl FromStr for PayloadType {
}
}
-impl ToString for PayloadType {
- fn to_string(&self) -> String {
- match self {
- Self::Html => "text/html".to_string(),
- Self::Pdf => "application/pdf".to_string(),
- Self::Rss => "application/rss".to_string(),
- Self::Atom => "application/atom".to_string(),
- }
+impl Display for PayloadType {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let str = match self {
+ Self::Html => "text/html",
+ Self::Pdf => "application/pdf",
+ Self::Rss => "application/rss",
+ Self::Atom => "application/atom",
+ };
+ write!(f, "{}", str)
}
}
diff --git a/crates/core/src/webpage/safety_classifier.rs b/crates/core/src/webpage/safety_classifier.rs
index d4de713c..dc48ab00 100644
--- a/crates/core/src/webpage/safety_classifier.rs
+++ b/crates/core/src/webpage/safety_classifier.rs
@@ -14,6 +14,7 @@
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
+use std::fmt::Display;
use std::fs::OpenOptions;
use std::path::Path;
@@ -32,12 +33,12 @@ pub enum Label {
NSFW,
}
-impl ToString for Label {
- fn to_string(&self) -> String {
- match self {
+impl Display for Label {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}", match self {
Label::SFW => "SFW".to_string(),
Label::NSFW => "NSFW".to_string(),
- }
+ })
}
}
diff --git a/crates/kuchiki/src/serializer.rs b/crates/kuchiki/src/serializer.rs
index b0456762..c9b9598d 100644
--- a/crates/kuchiki/src/serializer.rs
+++ b/crates/kuchiki/src/serializer.rs
@@ -1,10 +1,10 @@
+use std::fmt::Display;
use html5ever::serialize::TraversalScope::*;
use html5ever::serialize::{serialize, Serialize, SerializeOpts, Serializer, TraversalScope};
use html5ever::QualName;
use std::fs::File;
use std::io::{Result, Write};
use std::path::Path;
-use std::string::ToString;
use crate::tree::{NodeData, NodeRef};
@@ -71,12 +71,11 @@ impl Serialize for NodeRef {
}
}
-impl ToString for NodeRef {
- #[inline]
- fn to_string(&self) -> String {
+impl Display for NodeRef {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut u8_vec = Vec::new();
self.serialize(&mut u8_vec).unwrap();
- String::from_utf8(u8_vec).unwrap()
+ write!(f, "{}", String::from_utf8(u8_vec).unwrap())
}
}
diff --git a/crates/optics/src/ast.rs b/crates/optics/src/ast.rs
index 5988480c..d23ea679 100644
--- a/crates/optics/src/ast.rs
+++ b/crates/optics/src/ast.rs
@@ -14,6 +14,7 @@
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
+use std::fmt::Display;
use super::Error;
use super::Result as ModResult;
use lalrpop_util::lalrpop_mod;
@@ -38,23 +39,17 @@ pub struct RankingCoeff {
pub value: f64,
}
-impl ToString for RankingCoeff {
- fn to_string(&self) -> String {
- let mut res = String::new();
-
- res.push_str("Ranking(");
+impl Display for RankingCoeff {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "Ranking(")?;
match &self.target {
RankingTarget::Signal(signal) => {
- res.push_str(&format!("Signal(\"{}\")", signal));
+ write!(f, "Signal(\"{}\")", signal)?;
}
}
- res.push_str(", ");
- res.push_str(&self.value.to_string());
- res.push(')');
-
- res
+ write!(f, ", {})", self.value)
}
}
diff --git a/crates/optics/src/lib.rs b/crates/optics/src/lib.rs
index 87d71e8e..fb4d7f6b 100644
--- a/crates/optics/src/lib.rs
+++ b/crates/optics/src/lib.rs
@@ -20,6 +20,7 @@ mod lexer;
use ast::RankingCoeff;
use serde::{Deserialize, Serialize};
use std::convert::TryFrom;
+use std::fmt::Display;
use thiserror::Error;
use utoipa::ToSchema;
@@ -145,30 +146,25 @@ pub struct Matching {
pub location: MatchLocation,
}
-impl ToString for Matching {
- fn to_string(&self) -> String {
- let mut s = String::new();
- match self.location {
- MatchLocation::Site => s.push_str("Site"),
- MatchLocation::Url => s.push_str("Url"),
- MatchLocation::Domain => s.push_str("Domain"),
- MatchLocation::Title => s.push_str("Title"),
- MatchLocation::Description => s.push_str("Description"),
- MatchLocation::Content => s.push_str("Content"),
- MatchLocation::MicroformatTag => s.push_str("MicroformatTag"),
- MatchLocation::Schema => s.push_str("Schema"),
- }
- s.push('(');
- s.push('"');
+impl Display for Matching {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let s = match self.location {
+ MatchLocation::Site => "Site",
+ MatchLocation::Url => "Url",
+ MatchLocation::Domain => "Domain",
+ MatchLocation::Title => "Title",
+ MatchLocation::Description => "Description",
+ MatchLocation::Content => "Content",
+ MatchLocation::MicroformatTag => "MicroformatTag",
+ MatchLocation::Schema => "Schema",
+ };
+ write!(f, "{}(\"", s)?;
for part in &self.pattern {
- s.push_str(&part.to_string());
+ write!(f, "{}", part)?;
}
- s.push('"');
- s.push(')');
-
- s
+ write!(f, "\")")
}
}
@@ -274,12 +270,12 @@ pub enum PatternPart {
Anchor,
}
-impl ToString for PatternPart {
- fn to_string(&self) -> String {
+impl Display for PatternPart {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
- PatternPart::Raw(s) => s.to_string(),
- PatternPart::Wildcard => "*".to_string(),
- PatternPart::Anchor => "|".to_string(),
+ PatternPart::Raw(s) => write!(f, "{}", s),
+ PatternPart::Wildcard => write!(f, "*"),
+ PatternPart::Anchor => write!(f, "|"),
}
}
}
@@ -303,20 +299,17 @@ pub enum Action {
Discard,
}
-impl ToString for Action {
- fn to_string(&self) -> String {
- let mut res = String::new();
- res.push_str("Action(");
+impl Display for Action {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "Action(")?;
match self {
- Action::Boost(b) => res.push_str(&format!("Boost({})", b)),
- Action::Downrank(d) => res.push_str(&format!("Downrank({})", d)),
- Action::Discard => res.push_str("Discard"),
+ Action::Boost(b) => write!(f, "Boost({})", b)?,
+ Action::Downrank(d) => write!(f, "Downrank({})", d)?,
+ Action::Discard => write!(f, "Discard")?,
}
- res.push(')');
-
- res
+ write!(f, ")")
}
}
@@ -334,25 +327,21 @@ impl Optic {
}
}
-impl ToString for Optic {
- fn to_string(&self) -> String {
- let mut res = String::new();
-
+impl Display for Optic {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.discard_non_matching {
- res.push_str("DiscardNonMatching;\n");
+ writeln!(f, "DiscardNonMatching;")?;
}
for rule in &self.rules {
- res.push_str(&rule.to_string());
+ write!(f, "{}", rule)?;
}
for ranking in &self.rankings {
- res.push_str(&format!("{};\n", ranking.to_string()));
+ writeln!(f, "{};", ranking)?;
}
- res.push_str(&self.host_rankings.to_string());
-
- res
+ write!(f, "{}", self.host_rankings)
}
}
@@ -364,25 +353,20 @@ pub struct Rule {
pub action: Action,
}
-impl ToString for Rule {
- fn to_string(&self) -> String {
- let mut res = String::new();
-
- res.push_str("Rule {\n");
+impl Display for Rule {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ writeln!(f, "Rule {{")?;
if !self.matches.is_empty() {
for matcher in &self.matches {
- res.push_str("\tMatches {\n");
+ writeln!(f, "\tMatches {{")?;
for m in matcher {
- res.push_str(&format!("\t\t{},\n", m.to_string()));
+ writeln!(f, "\t\t{},", m)?;
}
- res.push_str("\t}")
+ writeln!(f, "\t}},")?;
}
}
- res.push_str(&format!("\t{}\n", self.action.to_string()));
- res.push_str("};\n");
-
- res
+ writeln!(f, "\t{}\n}};", self.action.to_string())
}
}
@@ -394,16 +378,14 @@ pub struct HostRankings {
pub blocked: Vec<String>,
}
-impl ToString for HostRankings {
- fn to_string(&self) -> String {
- let mut res = String::new();
-
+impl Display for HostRankings {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for liked in &self.liked {
- res.push_str(&format!("Like(Site(\"{}\"));\n", liked));
+ writeln!(f, "Like(Site(\"{}\"));", liked)?;
}
for disliked in &self.disliked {
- res.push_str(&format!("Dislike(Site(\"{}\"));\n", disliked));
+ writeln!(f, "Dislike(Site(\"{}\"));", disliked)?;
}
let matches : Vec<_> = self.blocked
@@ -416,7 +398,7 @@ impl ToString for HostRankings {
.map(|host| vec![Matching {
pattern: vec![
PatternPart::Anchor,
- PatternPart::Raw(host.clone()),
+ PatternPart::Raw(host),
PatternPart::Anchor,
],
location: MatchLocation::Site,
@@ -430,10 +412,10 @@ impl ToString for HostRankings {
action: Action::Discard,
};
- res.push_str(&rule.to_string());
+ write!(f, "{}", rule)?;
}
- res
+ Ok(())
}
}