Skip to content

Commit

Permalink
Merge pull request #773 from heygsc/feat/cow
Browse files Browse the repository at this point in the history
use `cow-utils` instead
  • Loading branch information
jaytaph authored Jan 14, 2025
2 parents 0c5d668 + b676000 commit 142c33f
Show file tree
Hide file tree
Showing 24 changed files with 77 additions and 45 deletions.
6 changes: 6 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions clippy.toml
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
disallowed-methods = [
{ path = "str::to_ascii_lowercase", reason = "To avoid memory allocation, use `cow_utils::CowUtils::cow_to_ascii_lowercase` instead." },
{ path = "str::to_ascii_uppercase", reason = "To avoid memory allocation, use `cow_utils::CowUtils::cow_to_ascii_uppercase` instead." },
{ path = "str::to_lowercase", reason = "To avoid memory allocation, use `cow_utils::CowUtils::cow_to_lowercase` instead." },
{ path = "str::to_uppercase", reason = "To avoid memory allocation, use `cow_utils::CowUtils::cow_to_uppercase` instead." },
{ path = "str::replace", reason = "To avoid memory allocation, use `cow_utils::CowUtils::cow_replace` instead." },
{ path = "str::replacen", reason = "To avoid memory allocation, use `cow_utils::CowUtils::cow_replacen` instead." },
]
1 change: 1 addition & 0 deletions crates/gosub_config/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ log = "0.4.22"
testing_logger = "0.1.1"
url = "2.5.4"
anyhow = "1.0.94"
cow-utils = "0.1.3"

[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
rusqlite = "0.32.1"
Expand Down
5 changes: 3 additions & 2 deletions crates/gosub_config/src/settings.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::errors::Error;
use core::fmt::Display;
use cow_utils::CowUtils;
use log::warn;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::str::FromStr;
Expand Down Expand Up @@ -94,8 +95,8 @@ impl Setting {
}

fn is_bool_value(s: &str) -> bool {
let us = s.to_uppercase();
if ["YES", "ON", "TRUE", "1"].contains(&us.as_str()) {
let us = s.cow_to_uppercase();
if ["YES", "ON", "TRUE", "1"].contains(&us.as_ref()) {
return true;
}

Expand Down
5 changes: 3 additions & 2 deletions crates/gosub_css3/src/matcher/styling.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use core::fmt::Debug;
use cow_utils::CowUtils;
use itertools::Itertools;
use std::cmp::Ordering;
use std::collections::HashMap;
Expand Down Expand Up @@ -127,8 +128,8 @@ fn match_selector_part<'a, C: HasDocument>(
let mut _got_buf = String::new();
// If we need to match case-insensitive, just convert everything to lowercase for comparison
if attr.case_insensitive {
_wanted_buf = wanted_attr_name.to_lowercase();
_got_buf = got_attr_value.to_lowercase();
_wanted_buf = wanted_attr_name.cow_to_lowercase().to_string();
_got_buf = got_attr_value.cow_to_lowercase().to_string();

wanted_attr_value = &_wanted_buf;
got_attr_value = &_got_buf;
Expand Down
5 changes: 3 additions & 2 deletions crates/gosub_css3/src/parser/at_rule.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use crate::node::{Node, NodeType};
use crate::parser::block::BlockParseMode;
use crate::tokenizer::TokenType;
use crate::Css3;
use cow_utils::CowUtils;
use gosub_shared::errors::{CssError, CssResult};

impl Css3<'_> {
Expand Down Expand Up @@ -59,7 +60,7 @@ impl Css3<'_> {
log::trace!("parse_at_rule_prelude");

self.consume_whitespace_comments();
let node = match name.to_lowercase().as_str() {
let node = match name.cow_to_lowercase().as_ref() {
"container" => Some(self.parse_at_rule_container_prelude()?),
"font-face" => None,
"import" => Some(self.parse_at_rule_import_prelude()?),
Expand Down Expand Up @@ -102,7 +103,7 @@ impl Css3<'_> {
}

// parse block. They may or may not have nested rules depending on the is_declaration and block type
let node = match name.to_lowercase().as_str() {
let node = match name.cow_to_lowercase().as_ref() {
"container" => Some(self.parse_block(mode)?),
"font-face" => Some(self.parse_block(BlockParseMode::StyleBlock)?),
"import" => None,
Expand Down
17 changes: 9 additions & 8 deletions crates/gosub_css3/src/parser/at_rule/media.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::node::{FeatureKind, Node, NodeType};
use crate::tokenizer::TokenType;
use crate::Css3;
use cow_utils::CowUtils;
use gosub_shared::errors::{CssError, CssResult};

impl Css3<'_> {
Expand All @@ -15,13 +16,13 @@ impl Css3<'_> {
TokenType::Number(value) => Ok(Node::new(NodeType::Number { value }, loc)),
TokenType::Dimension { value, unit } => Ok(Node::new(NodeType::Dimension { value, unit }, loc)),
TokenType::Function(name) => {
let name = name.to_lowercase();
let args = self.parse_pseudo_function(name.as_str())?;
let name = name.cow_to_lowercase();
let args = self.parse_pseudo_function(name.as_ref())?;
self.consume(TokenType::RParen)?;

Ok(Node::new(
NodeType::Function {
name,
name: name.to_string(),
arguments: vec![args],
},
loc,
Expand Down Expand Up @@ -111,13 +112,13 @@ impl Css3<'_> {
}
TokenType::Ident(value) => Some(Node::new(NodeType::Ident { value }, t.location)),
TokenType::Function(name) => {
let name = name.to_lowercase();
let args = self.parse_pseudo_function(name.as_str())?;
let name = name.cow_to_lowercase();
let args = self.parse_pseudo_function(name.as_ref())?;
self.consume(TokenType::RParen)?;

Some(Node::new(
NodeType::Function {
name,
name: name.to_string(),
arguments: vec![args],
},
t.location,
Expand Down Expand Up @@ -208,8 +209,8 @@ impl Css3<'_> {
_ => unreachable!(),
};

let s = ident.to_lowercase();
media_type = if ["not", "only"].contains(&s.as_str()) {
let s = ident.cow_to_lowercase();
media_type = if ["not", "only"].contains(&s.as_ref()) {
self.consume_whitespace_comments();
modifier = ident;
self.consume_any_ident()?
Expand Down
7 changes: 4 additions & 3 deletions crates/gosub_css3/src/parser/selector.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::node::{Node, NodeType};
use crate::tokenizer::TokenType;
use crate::Css3;
use cow_utils::CowUtils;
use gosub_shared::errors::CssError;
use gosub_shared::errors::CssResult;

Expand Down Expand Up @@ -222,13 +223,13 @@ impl Css3<'_> {
let value = match t.token_type {
TokenType::Ident(value) => Node::new(NodeType::Ident { value }, t.location),
TokenType::Function(name) => {
let name = name.to_lowercase();
let args = self.parse_pseudo_function(name.as_str())?;
let name = name.cow_to_lowercase();
let args = self.parse_pseudo_function(name.as_ref())?;
self.consume(TokenType::RParen)?;

Node::new(
NodeType::Function {
name,
name: name.to_string(),
arguments: vec![args],
},
t.location,
Expand Down
1 change: 1 addition & 0 deletions crates/gosub_html5/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ regex = "1"
serde = { version = "1.0", features = ["derive"] }
serde_json = { version = "1.0", features = ["preserve_order"] }
serde_derive = "1.0"
cow-utils = "0.1.3"

[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
ureq = "2.12.1"
Expand Down
9 changes: 5 additions & 4 deletions crates/gosub_html5/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use crate::parser::errors::{ErrorLogger, ParserError};
use crate::tokenizer::state::State;
use crate::tokenizer::token::Token;
use crate::tokenizer::{ParserData, Tokenizer, CHAR_REPLACEMENT};
use cow_utils::CowUtils;
use gosub_interface::config::HasDocument;
use gosub_interface::css3::{CssOrigin, CssSystem};
use gosub_interface::document::{Document, DocumentFragment, DocumentType};
Expand Down Expand Up @@ -595,7 +596,7 @@ impl<'a, C: HasDocument> Html5Parser<'a, C> {
let mut node_idx = self.open_elements.len() - 1;
let mut node = get_node_by_id!(self.document, self.open_elements[node_idx]);

if get_element_data!(node).name().to_lowercase() != *name {
if get_element_data!(node).name().cow_to_lowercase() != *name {
self.parse_error("end tag does not match current node");
}

Expand All @@ -607,7 +608,7 @@ impl<'a, C: HasDocument> Html5Parser<'a, C> {
_ => {}
}

if get_element_data!(node).name().to_lowercase() == *name {
if get_element_data!(node).name().cow_to_lowercase() == *name {
while let Some(node_id) = self.open_elements.pop() {
if node_id == node.id() {
break;
Expand Down Expand Up @@ -2771,7 +2772,7 @@ impl<'a, C: HasDocument> Html5Parser<'a, C> {

self.acknowledge_closing_tag(*is_self_closing);

if !attributes.contains_key("type") || attributes.get("type").unwrap().to_lowercase() != *"hidden" {
if !attributes.contains_key("type") || attributes.get("type").unwrap().cow_to_lowercase() != *"hidden" {
self.frameset_ok = false;
}
}
Expand Down Expand Up @@ -3329,7 +3330,7 @@ impl<'a, C: HasDocument> Html5Parser<'a, C> {
attributes,
..
} if name == "input" => {
if !attributes.contains_key("type") || attributes.get("type").unwrap().to_lowercase() != *"hidden" {
if !attributes.contains_key("type") || attributes.get("type").unwrap().cow_to_lowercase() != *"hidden" {
anything_else = true;
} else {
self.parse_error("input tag not allowed in in table insertion mode");
Expand Down
17 changes: 9 additions & 8 deletions crates/gosub_html5/src/parser/quirks.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::parser::Html5Parser;
use cow_utils::CowUtils;
use gosub_interface::config::HasDocument;
use gosub_interface::node::QuirksMode;

Expand All @@ -16,47 +17,47 @@ impl<C: HasDocument> Html5Parser<'_, C> {
}

if let Some(value) = pub_identifier {
let pub_id = value.to_lowercase();
if QUIRKS_PUB_IDENTIFIER_EQ.contains(&pub_id.as_str()) {
let pub_id = value.cow_to_lowercase();
if QUIRKS_PUB_IDENTIFIER_EQ.contains(&pub_id.as_ref()) {
return QuirksMode::Quirks;
}

if QUIRKS_PUB_IDENTIFIER_PREFIX
.iter()
.any(|&prefix| pub_id.as_str().starts_with(prefix))
.any(|&prefix| pub_id.as_ref().starts_with(prefix))
{
return QuirksMode::Quirks;
}

if sys_identifier.is_some()
&& LIMITED_QUIRKS_PUB_IDENTIFIER_PREFIX_NOT_MISSING_SYS
.iter()
.any(|&prefix| pub_id.as_str().starts_with(prefix))
.any(|&prefix| pub_id.as_ref().starts_with(prefix))
{
return QuirksMode::LimitedQuirks;
}

if sys_identifier.is_none()
&& QUIRKS_PUB_IDENTIFIER_PREFIX_MISSING_SYS
.iter()
.any(|&prefix| pub_id.as_str().starts_with(prefix))
.any(|&prefix| pub_id.as_ref().starts_with(prefix))
{
return QuirksMode::Quirks;
}

if LIMITED_QUIRKS_PUB_IDENTIFIER_PREFIX
.iter()
.any(|&prefix| pub_id.as_str().starts_with(prefix))
.any(|&prefix| pub_id.as_ref().starts_with(prefix))
{
return QuirksMode::LimitedQuirks;
}
}

if let Some(value) = sys_identifier {
let sys_id = value.to_lowercase();
let sys_id = value.cow_to_lowercase();
if QUIRKS_SYS_IDENTIFIER_EQ
.iter()
.any(|&prefix| sys_id.as_str().starts_with(prefix))
.any(|&prefix| sys_id.as_ref().starts_with(prefix))
{
return QuirksMode::Quirks;
}
Expand Down
3 changes: 2 additions & 1 deletion crates/gosub_html5/src/testing/tree_construction/fixture.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::testing::tree_construction::parser::{parse_fixture, QUOTED_DOUBLE_NEWLINE};
use crate::testing::tree_construction::Test;
use crate::testing::{FIXTURE_ROOT, TREE_CONSTRUCTION_PATH};
use cow_utils::CowUtils;
use gosub_shared::types::Result;
use std::fs;
use std::path::{Path, PathBuf};
Expand Down Expand Up @@ -77,7 +78,7 @@ pub fn read_fixtures(filenames: Option<&[&str]>) -> Result<Vec<FixtureFile>> {
// have a "|" prefix using an "\n" delimiter. Otherwise strip "\n" from lines.
fn create_document_array(s: &str) -> Vec<String> {
let document = s
.replace(QUOTED_DOUBLE_NEWLINE, "\"\n\n\"")
.cow_replace(QUOTED_DOUBLE_NEWLINE, "\"\n\n\"")
.split('|')
.skip(1)
.flat_map(|l| (!l.is_empty()).then(|| format!("|{}", l.trim_end())))
Expand Down
3 changes: 2 additions & 1 deletion crates/gosub_html5/src/testing/tree_construction/parser.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// See https://github.com/html5lib/html5lib-tests/tree/master/tree-construction
use cow_utils::CowUtils;
use gosub_shared::types::{Error, Result};
use nom::{
branch::alt,
Expand Down Expand Up @@ -302,7 +303,7 @@ fn trim_last_newline(s: String) -> String {

pub fn parse_fixture(i: &str) -> Result<Vec<TestSpec>> {
// Deal with a corner case that makes it hard to parse tricky01.dat.
let input = i.replace("\"\n\n\"", QUOTED_DOUBLE_NEWLINE).clone() + "\n";
let input = i.cow_replace("\"\n\n\"", QUOTED_DOUBLE_NEWLINE).clone() + "\n";

let files = map(
tuple((separated_list1(tag("\n\n"), test), multispace0)),
Expand Down
7 changes: 4 additions & 3 deletions crates/gosub_html5/src/tokenizer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use crate::node::HTML_NAMESPACE;
use crate::parser::errors::{ErrorLogger, ParserError};
use crate::tokenizer::state::State;
use crate::tokenizer::token::Token;
use cow_utils::CowUtils;
use gosub_shared::byte_stream::Character::{Ch, StreamEnd};
use gosub_shared::byte_stream::{ByteStream, Character, Location, LocationHandler, Stream};
use gosub_shared::types::Result;
Expand Down Expand Up @@ -1235,7 +1236,7 @@ impl<'stream> Tokenizer<'stream> {
continue;
}

if Character::slice_to_string(self.stream.get_slice(7)).to_uppercase() == "DOCTYPE" {
if Character::slice_to_string(self.stream.get_slice(7)).cow_to_uppercase() == "DOCTYPE" {
self.stream_next_n(7);
self.state = State::DOCTYPE;
continue;
Expand Down Expand Up @@ -1605,12 +1606,12 @@ impl<'stream> Tokenizer<'stream> {
}
_ => {
self.stream_prev();
if Character::slice_to_string(self.stream.get_slice(6)).to_uppercase() == "PUBLIC" {
if Character::slice_to_string(self.stream.get_slice(6)).cow_to_uppercase() == "PUBLIC" {
self.stream_next_n(6);
self.state = State::AfterDOCTYPEPublicKeyword;
continue;
}
if Character::slice_to_string(self.stream.get_slice(6)).to_uppercase() == "SYSTEM" {
if Character::slice_to_string(self.stream.get_slice(6)).cow_to_uppercase() == "SYSTEM" {
self.stream_next_n(6);
self.state = State::AfterDOCTYPESystemKeyword;
continue;
Expand Down
1 change: 1 addition & 0 deletions crates/gosub_jsapi/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ description = "Web Javascript API"
gosub_shared = { version = "0.1.1", registry = "gosub", path = "../gosub_shared", features = [] }
uuid = { version = "1.11.0", features = ["v4"] }
regex = "1"
cow-utils = "0.1.3"
Loading

0 comments on commit 142c33f

Please sign in to comment.