remove unused struct and put its functions as top level

This commit is contained in:
Edgar 2021-12-14 08:52:40 +01:00
parent 8aff8a93b6
commit 669d4ead81
No known key found for this signature in database
GPG key ID: 8731E6C0166EAA85
4 changed files with 76 additions and 78 deletions

View file

@ -1,6 +1,6 @@
[package] [package]
name = "sitewriter" name = "sitewriter"
version = "0.4.2" version = "0.5.0"
authors = ["Edgar <git@edgarluque.com>"] authors = ["Edgar <git@edgarluque.com>"]
edition = "2021" edition = "2021"
description = "A sitemap writing library." description = "A sitemap writing library."

View file

@ -1,5 +1,5 @@
use criterion::{black_box, criterion_group, criterion_main, Criterion}; use criterion::{black_box, criterion_group, criterion_main, Criterion};
use sitewriter::*; use sitewriter::{ChangeFreq, UrlEntry, UrlEntryBuilder};
fn benchmark(c: &mut Criterion) { fn benchmark(c: &mut Criterion) {
use chrono::Utc; use chrono::Utc;
@ -52,11 +52,11 @@ fn benchmark(c: &mut Criterion) {
]; ];
c.bench_function("generate_str", |b| { c.bench_function("generate_str", |b| {
b.iter(|| Sitemap::generate_str(black_box(&urls))) b.iter(|| sitewriter::generate_str(black_box(&urls)))
}); });
c.bench_function("generate_bytes", |b| { c.bench_function("generate_bytes", |b| {
b.iter(|| Sitemap::generate_bytes(black_box(&urls))) b.iter(|| sitewriter::generate_bytes(black_box(&urls)))
}); });
} }

View file

@ -1,5 +1,5 @@
use chrono::prelude::*; use chrono::prelude::*;
use sitewriter::*; use sitewriter::{ChangeFreq, UrlEntry, UrlEntryBuilder};
fn main() { fn main() {
let urls = vec![ let urls = vec![
@ -48,6 +48,6 @@ fn main() {
}, },
]; ];
let result = Sitemap::generate_str(&urls).unwrap(); let result = sitewriter::generate_str(&urls);
println!("{}", result); println!("{}", result);
} }

View file

@ -13,7 +13,7 @@
//! //!
//! ```rust //! ```rust
//! use chrono::prelude::*; //! use chrono::prelude::*;
//! use sitewriter::*; //! use sitewriter::{ChangeFreq, UrlEntry, UrlEntryBuilder};
//! //!
//! let urls = vec![ //! let urls = vec![
//! UrlEntryBuilder::default() //! UrlEntryBuilder::default()
@ -61,7 +61,7 @@
//! }, //! },
//! ]; //! ];
//! //!
//! let result = Sitemap::generate_str(&urls).unwrap(); //! let result = sitewriter::generate_str(&urls);
//! println!("{}", result); //! println!("{}", result);
//! ``` //! ```
//! //!
@ -77,25 +77,20 @@
//! Help other developers, inform them and share your opinion.\ //! Help other developers, inform them and share your opinion.\
//! Use [cargo_crev_reviews](https://crates.io/crates/cargo_crev_reviews) to write reviews easily. //! Use [cargo_crev_reviews](https://crates.io/crates/cargo_crev_reviews) to write reviews easily.
use chrono::{DateTime, SecondsFormat, Utc}; use chrono::{DateTime, SecondsFormat, Utc};
use derive_builder::Builder; use derive_builder::Builder;
pub use url;
use url::Url;
use quick_xml::{ use quick_xml::{
events::{BytesDecl, BytesEnd, BytesStart, BytesText, Event}, events::{BytesDecl, BytesEnd, BytesStart, BytesText, Event},
Writer, Writer,
}; };
use std::{fmt::Display, io::Cursor};
use quick_xml::Result; pub use quick_xml::Result;
use std::fmt::Display; pub use url::Url;
use std::io::Cursor;
pub use quick_xml; /// How frequently the page is likely to change. This value provides general
/// information to search engines and may not correlate exactly to how often they crawl the page.
/// How frequently the page is likely to change. This value provides general information to search engines and may not correlate exactly to how often they crawl the page. #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub enum ChangeFreq { pub enum ChangeFreq {
/// Changes each time it's accessed. /// Changes each time it's accessed.
Always, Always,
@ -129,7 +124,7 @@ impl Display for ChangeFreq {
} }
/// A sitemap url entry. /// A sitemap url entry.
#[derive(Debug, Clone, Builder)] #[derive(Debug, Clone, Builder, PartialEq, PartialOrd)]
#[builder(setter(strip_option))] #[builder(setter(strip_option))]
pub struct UrlEntry { pub struct UrlEntry {
/// URL of the page. /// URL of the page.
@ -150,7 +145,8 @@ pub struct UrlEntry {
} }
impl UrlEntry { impl UrlEntry {
pub fn new( #[must_use]
pub const fn new(
loc: Url, loc: Url,
lastmod: Option<DateTime<Utc>>, lastmod: Option<DateTime<Utc>>,
changefreq: Option<ChangeFreq>, changefreq: Option<ChangeFreq>,
@ -165,10 +161,6 @@ impl UrlEntry {
} }
} }
/// Struct that implements the sitemap generation function.
#[derive(Debug)]
pub struct Sitemap;
fn write_tag<T>(writer: &mut Writer<T>, tag: &str, text: &str) -> Result<()> fn write_tag<T>(writer: &mut Writer<T>, tag: &str, text: &str) -> Result<()>
where where
T: std::io::Write, T: std::io::Write,
@ -180,65 +172,71 @@ where
Ok(()) Ok(())
} }
impl Sitemap { /// Generates the sitemap and saves it using the provided writer.
/// Generates the sitemap and saves it using the provided writer. ///
/// /// It's recommended to use [`Sitemap::generate_bytes`] or [`Sitemap::generate_str`] if you need a
/// It's recommended to use [`Sitemap::into_bytes`] or [`Sitemap::into_str`] if you need a /// String or a Vec<u8>.
/// String or a Vec<u8>. ///
pub fn generate<T>(inner_writer: T, urls: &[UrlEntry]) -> Result<T> /// # Errors
where ///
T: std::io::Write, /// Will return `Err` if it fails to write to the writer.
{ pub fn generate<T>(inner_writer: T, urls: &[UrlEntry]) -> Result<T>
let mut writer = Writer::new_with_indent(inner_writer, b' ', 4); where
writer.write_event(Event::Decl(BytesDecl::new(b"1.0", Some(b"UTF-8"), None)))?; T: std::io::Write,
{
let mut writer = Writer::new_with_indent(inner_writer, b' ', 4);
writer.write_event(Event::Decl(BytesDecl::new(b"1.0", Some(b"UTF-8"), None)))?;
let urlset_name = b"urlset"; let urlset_name = b"urlset";
let mut urlset = BytesStart::borrowed_name(urlset_name); let mut urlset = BytesStart::borrowed_name(urlset_name);
urlset.push_attribute(("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9")); urlset.push_attribute(("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9"));
writer.write_event(Event::Start(urlset))?; writer.write_event(Event::Start(urlset))?;
for entry in urls { for entry in urls {
writer writer
.write_event(Event::Start(BytesStart::borrowed_name(b"url"))) .write_event(Event::Start(BytesStart::borrowed_name(b"url")))
.expect("error opening url"); .expect("error opening url");
write_tag(&mut writer, "loc", entry.loc.as_str())?; write_tag(&mut writer, "loc", entry.loc.as_str())?;
if let Some(lastmod) = &entry.lastmod { if let Some(lastmod) = &entry.lastmod {
write_tag( write_tag(
&mut writer, &mut writer,
"lastmod", "lastmod",
&lastmod.to_rfc3339_opts(SecondsFormat::Secs, true), &lastmod.to_rfc3339_opts(SecondsFormat::Secs, true),
)?; )?;
} }
if let Some(priority) = &entry.priority { if let Some(priority) = &entry.priority {
write_tag(&mut writer, "priority", &format!("{:.1}", priority))?; write_tag(&mut writer, "priority", &format!("{:.1}", priority))?;
} }
if let Some(changefreq) = &entry.changefreq { if let Some(changefreq) = &entry.changefreq {
write_tag(&mut writer, "changefreq", &changefreq.to_string())?; write_tag(&mut writer, "changefreq", &changefreq.to_string())?;
}
writer.write_event(Event::End(BytesEnd::borrowed(b"url")))?;
} }
writer.write_event(Event::End(BytesEnd::borrowed(urlset_name)))?; writer.write_event(Event::End(BytesEnd::borrowed(b"url")))?;
Ok(writer.into_inner())
} }
/// Generates the sitemap. writer.write_event(Event::End(BytesEnd::borrowed(urlset_name)))?;
pub fn generate_bytes(urls: &[UrlEntry]) -> Result<Vec<u8>> {
let inner = Cursor::new(Vec::new());
let result = Sitemap::generate(inner, urls)?;
Ok(result.into_inner())
}
/// Generates the sitemap returning a string. Ok(writer.into_inner())
pub fn generate_str(urls: &[UrlEntry]) -> Result<String> { }
let bytes = Sitemap::generate_bytes(urls)?;
let res = std::str::from_utf8(&bytes).expect("to be valid utf8"); /// Generates the sitemap.
Ok(res.to_owned()) #[must_use]
} pub fn generate_bytes(urls: &[UrlEntry]) -> Vec<u8> {
let inner = Cursor::new(Vec::new());
let result = generate(inner, urls).expect(
"it should never error, please report this bug to https://github.com/edg-l/sitewriter/issues",
);
result.into_inner()
}
/// Generates the sitemap returning a string.
#[must_use]
pub fn generate_str(urls: &[UrlEntry]) -> String {
let bytes = generate_bytes(urls);
let res = std::str::from_utf8(&bytes).expect("to be valid utf8");
res.to_owned()
} }
#[cfg(test)] #[cfg(test)]
@ -296,7 +294,7 @@ mod tests {
}, },
]; ];
Sitemap::generate_str(&urls).unwrap(); let _result = generate_str(&urls);
} }
#[test] #[test]