This commit is contained in:
Robin Appelman 2025-06-02 23:14:57 +02:00
commit 95119b9347
13 changed files with 157 additions and 161 deletions

View file

@ -14,21 +14,16 @@ use std::ops::{Index, IndexMut};
use std::str::FromStr;
use steamid_ng::{AccountType, Instance, SteamID, Universe};
#[derive(Serialize, Copy, Clone, Eq, PartialEq, Debug, Ord, PartialOrd, Hash)]
#[derive(Serialize, Copy, Clone, Eq, PartialEq, Debug, Ord, PartialOrd, Hash, Default)]
pub enum Team {
Red,
Blue,
#[default]
Spectator,
}
impl EventFieldFromStr for Team {}
impl Default for Team {
fn default() -> Self {
Team::Spectator
}
}
impl Team {
pub fn as_str(self) -> &'static str {
match self {
@ -58,7 +53,9 @@ impl FromStr for Team {
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Sequence, Serialize)]
#[derive(
Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Sequence, Serialize, Default,
)]
#[serde(rename_all = "lowercase")]
pub enum Class {
Scout,
@ -70,6 +67,7 @@ pub enum Class {
Medic,
Sniper,
Spy,
#[default]
Unknown,
}
@ -92,12 +90,6 @@ impl Class {
}
}
impl Default for Class {
fn default() -> Self {
Class::Unknown
}
}
impl FromStr for Class {
type Err = ();
@ -242,7 +234,7 @@ impl TryFrom<&RawSubject<'_>> for SubjectId {
}
}
let Ok((_, user_id, steam_id, _)) = split_player_subject(raw) else {
return Ok(SubjectId::MalformedPlayer(hash_player_str(*raw)));
return Ok(SubjectId::MalformedPlayer(hash_player_str(raw)));
};
if let Ok(steam_id) = SteamID::from_steam2(steam_id) {
SubjectId::Player(steam_id.account_id())
@ -250,7 +242,7 @@ impl TryFrom<&RawSubject<'_>> for SubjectId {
user_id
.parse()
.map(SubjectId::Bot)
.unwrap_or_else(|_| SubjectId::MalformedPlayer(hash_player_str(*raw)))
.unwrap_or_else(|_| SubjectId::MalformedPlayer(hash_player_str(raw)))
}
}
RawSubject::Team(team) => SubjectId::Team(*team),
@ -290,7 +282,7 @@ impl SubjectData {
SubjectData::Bot { user_id, .. } => SubjectId::Bot(*user_id),
SubjectData::Console => SubjectId::Console,
SubjectData::World => SubjectId::World,
SubjectData::MalformedPlayer(raw) => SubjectId::MalformedPlayer(hash_player_str(&raw)),
SubjectData::MalformedPlayer(raw) => SubjectId::MalformedPlayer(hash_player_str(raw)),
}
}
}
@ -347,7 +339,7 @@ pub struct SteamId3(pub SteamID);
impl PartialOrd<Self> for SteamId3 {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
(u64::from(self.0)).partial_cmp(&u64::from(other.0))
Some(self.cmp(other))
}
}

View file

@ -2,7 +2,6 @@ mod game;
mod medic;
mod player;
use crate::event::game::{RoundLengthEvent, RoundWinEvent};
use crate::parsing::{skip, skip_matches, split_once, split_subject_end};
use crate::raw_event::{against_subject_parser, RawSubject};
use crate::{Error, Events, IResult, RawEvent, RawEventType, Result, SubjectId};
@ -29,7 +28,7 @@ trait GameEventErrTrait<T> {
fn with_raw(self, raw: &RawEvent) -> Result<T, GameEventError>;
}
impl<'a, T> GameEventErrTrait<T> for Result<T> {
impl<T> GameEventErrTrait<T> for Result<T> {
fn with_raw(self, raw: &RawEvent) -> Result<T, GameEventError> {
self.map_err(|err| GameEventError::Error {
err: Box::new(err),
@ -275,7 +274,7 @@ impl<'a, T: EventField<'a>> EventField<'a> for (T, T, T) {
impl<'a> EventField<'a> for Option<NonZeroU32> {
fn parse_field(input: &'a str) -> Result<Self> {
u32::parse_field(input).map(|int| NonZeroU32::new(int))
u32::parse_field(input).map(NonZeroU32::new)
}
}

View file

@ -4,7 +4,7 @@ use crate::module::{
ChatMessages, ClassStatsHandler, HealSpread, MedicStatsBuilder, PlayerHandler,
};
pub use crate::subjectmap::SubjectMap;
use chrono::{Duration, NaiveDate, NaiveDateTime};
use chrono::{DateTime, Duration, NaiveDate, NaiveDateTime};
pub(crate) use error::ResultExt;
pub use error::{Error, IResult, Result};
pub use event::{Event, EventMeta, GameEvent};
@ -23,31 +23,24 @@ pub(crate) mod parsing;
pub mod raw_event;
mod subjectmap;
pub type PerSubjectMap = BTreeMap<SteamId3, <LogHandler as EventHandler>::PerSubjectOutput>;
pub fn parse(
log: &str,
) -> Result<
(
<LogHandler as EventHandler>::GlobalOutput,
BTreeMap<SteamId3, <LogHandler as EventHandler>::PerSubjectOutput>,
),
Error,
> {
) -> Result<(<LogHandler as EventHandler>::GlobalOutput, PerSubjectMap), Error> {
parse_with_handler::<LogHandler>(log)
}
pub fn raw_events<'a>(log: &'a str) -> impl Iterator<Item = Result<RawEvent<'a>>> + 'a {
pub fn raw_events(log: &str) -> impl Iterator<Item = Result<RawEvent>> {
LineSplit::new(log).map(RawEvent::parse)
}
pub type PerSubjectMapForHandler<Handler> =
BTreeMap<SteamId3, <Handler as EventHandler>::PerSubjectOutput>;
pub fn parse_with_handler<Handler: EventHandler>(
log: &str,
) -> Result<
(
Handler::GlobalOutput,
BTreeMap<SteamId3, Handler::PerSubjectOutput>,
),
Error,
> {
) -> Result<(Handler::GlobalOutput, PerSubjectMapForHandler<Handler>), Error> {
let mut events = raw_events(log);
let mut handler = Handler::default();
@ -63,43 +56,40 @@ pub fn parse_with_handler<Handler: EventHandler>(
Err(e) => return Err(e),
};
let should_handle = Handler::does_handle(raw_event.ty);
if should_handle || start_time.is_none() {
if should_handle {
let event = match GameEvent::parse(&raw_event) {
Ok(event) => event,
Err(e) => {
let old_date: NaiveDateTime = raw_event
.date
.try_into()
.unwrap_or_else(|_| NaiveDateTime::from_timestamp(0, 0));
if should_handle && start_time.is_none() {
let event = match GameEvent::parse(&raw_event) {
Ok(event) => event,
Err(e) => {
let old_date: NaiveDateTime = raw_event
.date
.try_into()
.unwrap_or_else(|_| DateTime::from_timestamp(0, 0).unwrap().naive_utc());
// truncated newline during log combining, ignore error
if contains_line_start(raw_event.params, &old_date.date()) {
// truncated newline during log combining, ignore error
if contains_line_start(raw_event.params, &old_date.date()) {
continue;
}
let Some(next) = events.next() else {
// log is truncated
break;
};
if let Ok(next) = next {
let new_date: NaiveDateTime = next.date.try_into().unwrap_or_else(|_| {
DateTime::from_timestamp(0, 0).unwrap().naive_utc()
});
// truncated lines during log combining, ignore error
if new_date.signed_duration_since(old_date) > Duration::seconds(60) {
continue;
}
let Some(next) = events.next() else {
// log is truncated
break;
};
if let Ok(next) = next {
let new_date: NaiveDateTime = next
.date
.try_into()
.unwrap_or_else(|_| NaiveDateTime::from_timestamp(0, 0));
// truncated lines during log combining, ignore error
if new_date.signed_duration_since(old_date) > Duration::seconds(60) {
continue;
}
}
return Err(e.into());
}
};
handler.process(&raw_event, &event, &mut start_time, &mut subjects)?;
}
return Err(e.into());
}
};
handler.process(&raw_event, &event, &mut start_time, &mut subjects)?;
}
}

View file

@ -19,11 +19,7 @@ impl PlayerSpecificData for HealSpread {
fn handle_event(&mut self, _meta: &EventMeta, _subject: SubjectId, event: &GameEvent) {
if let GameEvent::Healed(heal_event) = event {
if let Some(Ok(target_subject)) = heal_event
.target
.as_ref()
.map(|target| SubjectId::try_from(target))
{
if let Some(Ok(target_subject)) = heal_event.target.as_ref().map(SubjectId::try_from) {
if let Some(target_steam_id) = target_subject.steam_id() {
let healed = self.0.entry(SteamId3(target_steam_id)).or_default();
*healed += heal_event.amount

View file

@ -3,7 +3,7 @@ use crate::event::GameEvent;
use crate::module::GlobalData;
use crate::raw_event::RawEventType;
use crate::{EventMeta, SubjectMap};
use chrono::{DateTime, FixedOffset, NaiveDateTime, TimeZone, Utc};
use chrono::{DateTime, FixedOffset, NaiveDate, NaiveDateTime, TimeZone, Utc};
use serde::{Serialize, Serializer};
use std::num::ParseIntError;
use std::str::{FromStr, ParseBoolError};
@ -108,7 +108,11 @@ impl Settings {
balancing: false,
restriction: "".to_string(),
mumble_required: false,
date: Utc.ymd(1, 1, 1).and_hms(0, 0, 0),
date: NaiveDate::from_ymd_opt(1, 1, 1)
.unwrap()
.and_hms_opt(0, 0, 0)
.unwrap()
.and_utc(),
server: "".to_string(),
}
}
@ -143,18 +147,14 @@ impl Serialize for LobbySettingsError {
}
}
#[derive(Default)]
pub enum LobbySettingsHandler {
#[default]
NotAvailable,
Active(Settings),
Err(LobbySettingsError),
}
impl Default for LobbySettingsHandler {
fn default() -> Self {
LobbySettingsHandler::NotAvailable
}
}
impl LobbySettingsHandler {
fn try_handle(&mut self, msg: &str) -> Result<(), LobbySettingsError> {
match self {
@ -230,9 +230,9 @@ impl GlobalData for LobbySettingsHandler {
fn get_timezone(date: &str) -> Result<FixedOffset, LobbySettingsError> {
if date.contains("CEST") {
Ok(FixedOffset::east(2 * 60 * 60))
Ok(FixedOffset::east_opt(2 * 60 * 60).unwrap())
} else if date.contains("CET") {
Ok(FixedOffset::east(60 * 60))
Ok(FixedOffset::east_opt(60 * 60).unwrap())
} else {
Err(LobbySettingsError::UnknownTimezone(date.into()))
}

View file

@ -47,7 +47,7 @@ pub trait EventHandler: Default {
time: match_time,
subject,
};
self.handle(&meta, subject, data, &event);
self.handle(&meta, subject, data, event);
Ok(())
}

View file

@ -20,7 +20,7 @@ thread_local! {
static SUBJECT_END_FINDER: Lazy<Finder<'static>> = Lazy::new(|| Finder::new(br#">""#));
}
pub fn split_subject_end<'a>(input: &'a str, offset: usize) -> Result<(&'a str, &'a str)> {
pub fn split_subject_end(input: &str, offset: usize) -> Result<(&str, &str)> {
let start_offset = 1;
let end_offset = start_offset + offset;
debug_assert!(offset <= 2);
@ -51,11 +51,9 @@ pub fn skip(input: &str, count: usize) -> Result<&str> {
}
pub fn skip_matches(input: &str, char: u8) -> (&str, bool) {
if input.as_bytes().get(0) == Some(&char) {
// safety, we verified that the input has a length of at least 1
(unsafe { input.get_unchecked(1..) }, true)
} else {
(input, false)
match input.split_at_checked(1) {
Some((first, rest)) if first.as_bytes() == [char] => (rest, true),
_ => (input, false),
}
}
@ -64,7 +62,7 @@ pub fn find_between_end(input: &str, start: u8, end: u8) -> Option<&str> {
let bytes = input.as_bytes();
let end = memrchr(end, bytes)?;
// safety, memchr returns indices that are inside the input
let start = memrchr(start, unsafe { &bytes.get_unchecked(0..end) })?;
let start = memrchr(start, unsafe { bytes.get_unchecked(0..end) })?;
// safety, memchr returns indices that are inside the input length and we only split on ascii
Some(unsafe { input.get_unchecked((start + 1)..end) })
}

View file

@ -52,12 +52,14 @@ impl<'a> TryFrom<RawDate<'a>> for NaiveDateTime {
fn try_from(RawDate(raw): RawDate<'a>) -> Result<Self, Self::Error> {
Ok(
NaiveDate::from_ymd(raw[6..10].parse()?, raw[0..2].parse()?, raw[3..5].parse()?)
.and_hms(
NaiveDate::from_ymd_opt(raw[6..10].parse()?, raw[0..2].parse()?, raw[3..5].parse()?)
.unwrap()
.and_hms_opt(
raw[13..15].parse()?,
raw[16..18].parse()?,
raw[19..21].parse()?,
),
)
.unwrap(),
)
}
}
@ -66,7 +68,10 @@ impl<'a> TryFrom<RawDate<'a>> for NaiveDateTime {
fn test_parse_date() {
let raw = RawDate("08/06/2018 - 21:13:57");
assert_eq!(
NaiveDate::from_ymd(2018, 08, 06).and_hms(21, 13, 57),
NaiveDate::from_ymd_opt(2018, 8, 6)
.unwrap()
.and_hms_opt(21, 13, 57)
.unwrap(),
raw.try_into().unwrap()
);
}
@ -86,7 +91,7 @@ impl Default for RawSubject<'static> {
}
}
impl<'a> RawSubject<'a> {
impl RawSubject<'_> {
pub fn id(&self) -> Result<SubjectId, SubjectError> {
self.try_into()
}