Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve badge ordering #28

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions fuzz/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
target
corpus
artifacts
145 changes: 145 additions & 0 deletions fuzz/Cargo.lock

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

26 changes: 26 additions & 0 deletions fuzz/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
[package]
name = "twitch_message-fuzz"
version = "0.0.0"
authors = ["Automatically generated"]
publish = false
edition = "2018"

[package.metadata]
cargo-fuzz = true

[dependencies]
itertools = "0.10.5"
libfuzzer-sys = "0.4"

[dependencies.twitch_message]
path = ".."

# Prevent this from interfering with workspaces
[workspace]
members = ["."]

[[bin]]
name = "badge_fuzz"
path = "fuzz_targets/badge_fuzz.rs"
test = false
doc = false
74 changes: 74 additions & 0 deletions fuzz/fuzz_targets/badge_fuzz.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
#![no_main]
use libfuzzer_sys::fuzz_target;

use itertools::Itertools;
fuzz_target!(|data: &str| { fun(data) });

// notes on ord: https://doc.rust-lang.org/std/cmp/trait.Ord.html
// Implementations must be consistent with the PartialOrd implementation, and ensure max, min, and clamp are consistent with cmp:
//
// partial_cmp(a, b) == Some(cmp(a, b)).
// max(a, b) == max_by(a, b, cmp) (ensured by the default implementation).
// min(a, b) == min_by(a, b, cmp) (ensured by the default implementation).
// For a.clamp(min, max), see the method docs (ensured by the default implementation).
//
// It’s easy to accidentally make cmp and partial_cmp disagree by deriving some of the traits and manually implementing others.
// Corollaries
//
// From the above and the requirements of PartialOrd, it follows that < defines a strict total order. This means that for all a, b and c:
//
// exactly one of a < b, a == b or a > b is true; and
// < is transitive: a < b and b < c implies a < c. The same must hold for both == and >.

pub fn fun(data: &str) {
if data.is_empty()
|| data.chars().any(|c: char| {
!c.is_ascii_alphanumeric() && c != '_' && c != '-' && c != '/' && c != ','
})
{
return;
}
let Ok(badges) = std::panic::catch_unwind(|| twitch_message::parse_badges(data).collect::<Vec<_>>()) else {
return;
};
for badge in &badges {
if badge.set_id.as_str().is_empty() || badge.id.as_str().is_empty() {
return;
}
}
if badges.len() == 2 {
for (a, b) in [(0, 1), (1, 0)] {
//dbg!(badges[a].partial_cmp(&badges[b]), Some(badges[a].cmp(&badges[b])));
assert!(badges[a].partial_cmp(&badges[b]) == Some(badges[a].cmp(&badges[b])))
}
}
if badges.len() != 3 {
return;
}

for vec in [0, 1, 2].iter().permutations(3) {
let a = &badges[*vec[0]];
let b = &badges[*vec[1]];
let c = &badges[*vec[2]];
let res = [a > b, a == b, a < b];
assert!(
res.iter().filter(|x| **x).count() == 1,
"{a:?} {b:?} {c:?} {:?}",
res
);
let res = [c > b, c == b, c < b];
assert!(
res.iter().filter(|x| **x).count() == 1,
"{a:?} {b:?} {c:?} {:?}",
res
);

if a < b && b < c {
assert!(a < c, "{a:?} < {b:?} && {b:?} < {c:?}", a = a);
} else if a == b && b == c {
assert!(a == c, "{a:?} == {b:?} && {b:?} == {c:?}", a = a);
} else if a > b && b > c {
assert!(a > c, "{a:?} > {b:?} && {b:?} > {c:?}", a = a);
}
}
}
101 changes: 87 additions & 14 deletions src/badges.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ use crate::{
///
/// let input = "broadcaster/1,foo/bar";
/// let expected = [
/// Badge{ name: Cow::Borrowed("broadcaster".into()), version: Cow::Borrowed("1".into()) },
/// Badge{ name: Cow::Borrowed("foo".into()), version: Cow::Borrowed("bar".into()) },
/// Badge{ set_id: Cow::Borrowed("broadcaster".into()), id: Cow::Borrowed("1".into()) },
/// Badge{ set_id: Cow::Borrowed("foo".into()), id: Cow::Borrowed("bar".into()) },
/// ];
/// for (i, badge) in parse_badges(input).enumerate() {
/// assert_eq!(expected[i], badge)
Expand All @@ -26,24 +26,73 @@ pub fn parse_badges(input: &str) -> impl Iterator<Item = Badge<'_>> + '_ {
input
.split(',')
.flat_map(|badge| badge.split_once('/'))
.map(|(name, version)| {
let mut version = Cow::Borrowed(version);
Badge::unescape(&mut version);
.map(|(set_id, id)| {
let mut id = Cow::Borrowed(id);
Badge::unescape(&mut id);
Badge {
name: Cow::Borrowed(name.into()),
version: IntoCow::into_cow(version),
set_id: Cow::Borrowed(set_id.into()),
id: IntoCow::into_cow(id),
}
})
}

/// A badge attached to a message
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(::serde::Serialize, ::serde::Deserialize))]
pub struct Badge<'a> {
/// The name of the badge
pub name: Cow<'a, BadgeSetIdRef>,
/// The version (or, more specifically the metadata) for the badge
pub version: Cow<'a, ChatBadgeIdRef>,
/// The set_id or name of the badge
pub set_id: Cow<'a, BadgeSetIdRef>,
/// The id, version or metadata for the badge
pub id: Cow<'a, ChatBadgeIdRef>,
}
impl Ord for Badge<'_> {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.partial_cmp(other).expect("badges are fully")
museun marked this conversation as resolved.
Show resolved Hide resolved
}
}

impl<'a> PartialOrd for Badge<'a> {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
static KNOWN_BADGES: &[&'_ str] = &[
"staff",
"admin",
"global_mod",
"broadcaster",
"vip",
"moderator",
"partner",
"subscriber",
"artist-badge",
"turbo",
"premium",
"bits-leader",
"bits",
];
match self.set_id.partial_cmp(&other.set_id) {
Some(core::cmp::Ordering::Equal) => {}
// XXX: order known badges like first-party site
// FIXME: is the reflexive and transitive? as needed by Ord
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this needs to be fixed

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How does this fail?

ord => match (
KNOWN_BADGES.iter().position(|b| *b == self.set_id.as_str()),
KNOWN_BADGES
.iter()
.position(|b| *b == other.set_id.as_str()),
) {
(Some(s), Some(other)) => return s.partial_cmp(&other),
(Some(_), None) => return Some(core::cmp::Ordering::Less),
(None, Some(_)) => return Some(core::cmp::Ordering::Greater),
_ => return ord,
},
}
// XXX: numerical partial_cmp on self.id, so that subscriber/12 > subscriber/9
match (
self.id.as_str().parse::<u32>(),
other.id.as_str().parse::<u32>(),
) {
(Ok(s), Ok(other)) if s != other => s.partial_cmp(&other),
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"01".parse() == "1".parse(), but they are not equal, this fixes that

(_, _) => self.id.partial_cmp(&other.id),
}
}
}

impl<'a> Badge<'a> {
Expand All @@ -55,8 +104,8 @@ impl<'a> Badge<'a> {
///
/// let tags = Tags::builder().add("badges", "broadcaster/1,foo/bar").finish();
/// let expected = [
/// Badge{ name: Cow::Borrowed("broadcaster".into()), version: Cow::Borrowed("1".into()) },
/// Badge{ name: Cow::Borrowed("foo".into()), version: Cow::Borrowed("bar".into()) },
/// Badge{ set_id: Cow::Borrowed("broadcaster".into()), id: Cow::Borrowed("1".into()) },
/// Badge{ set_id: Cow::Borrowed("foo".into()), id: Cow::Borrowed("bar".into()) },
/// ];
/// for (i, badge) in Badge::from_tags(&tags).enumerate() {
/// assert_eq!(expected[i], badge)
Expand Down Expand Up @@ -95,3 +144,27 @@ impl Badge<'_> {
.into();
}
}

#[cfg(test)]
#[test]
fn badge_ordering() {
#[track_caller]
fn parse(s: &str) -> Badge<'_> {
parse_badges(s).next().unwrap()
}
assert!(parse("subscriber/12") > parse("subscriber/9"));
assert!(parse("subscriber/0") < parse("subscriber/1"));
let mut badges: Vec<_> = parse_badges("bits/1,staff/1,broadcaster/1").collect();
badges.sort();
assert_eq!(
badges.iter().map(|b| b.set_id.as_str()).collect::<Vec<_>>(),
vec!["staff", "broadcaster", "bits"]
);

let mut badges: Vec<_> = parse_badges("aaa/1,zzz/1,staff/1").collect();
badges.sort();
assert_eq!(
badges.iter().map(|b| b.set_id.as_str()).collect::<Vec<_>>(),
vec!["staff", "aaa", "zzz"]
);
}
4 changes: 2 additions & 2 deletions src/into_static.rs
Original file line number Diff line number Diff line change
Expand Up @@ -543,8 +543,8 @@ impl<'a> IntoStatic for Badge<'a> {

fn into_static(self) -> Self::Output {
Badge {
name: self.name.into_static(),
version: self.version.into_static(),
set_id: self.set_id.into_static(),
id: self.id.into_static(),
}
}
}
Loading