Allow comparing UserIds and ChatIds

This commit is contained in:
Maybe Waffle 2023-07-29 14:07:19 +04:00
parent 529b38afee
commit 4ccf24c7ab
3 changed files with 28 additions and 0 deletions

View file

@ -17,6 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `VideoChatEnded::duration` field that was previously missed ([#859][pr859])
- `ThreadId` newtype over `MessageId`, used for identifying reply threads ([#887][pr887])
- `ChatId::as_user` ([#905][pr905])
- Implement `PartialEq<ChatId> for UserId` and `PartialEq<UserId> for ChatId` ([#905][pr905])
[pr851]: https://github.com/teloxide/teloxide/pull/851
[pr887]: https://github.com/teloxide/teloxide/pull/887

View file

@ -82,6 +82,12 @@ impl From<UserId> for ChatId {
}
}
impl PartialEq<UserId> for ChatId {
fn eq(&self, other: &UserId) -> bool {
self.is_user() && *self == ChatId::from(*other)
}
}
impl BareChatId {
/// Converts bare chat id back to normal bot API [`ChatId`].
#[allow(unused)]
@ -152,4 +158,16 @@ mod tests {
fn display() {
assert_eq!(ChatId(1).to_string(), "1");
}
#[test]
fn user_id_eq() {
assert_eq!(ChatId(12), UserId(12));
assert_eq!(ChatId(4652762), UserId(4652762));
assert_ne!(ChatId(17), UserId(42));
// The user id is not well formed, so even though `-1 == max` is true,
// we don't want user id to match
assert_eq!(-1i64, u64::MAX as i64);
assert_ne!(ChatId(-1), UserId(u64::MAX));
}
}

View file

@ -1,5 +1,7 @@
use serde::{Deserialize, Serialize};
use crate::types::ChatId;
/// Identifier of a user.
#[derive(Clone, Copy)]
#[derive(Debug, derive_more::Display)]
@ -52,6 +54,13 @@ impl UserId {
}
}
impl PartialEq<ChatId> for UserId {
fn eq(&self, other: &ChatId) -> bool {
// Reuse `PartialEq<UserId> for ChatId` impl
other == self
}
}
#[cfg(test)]
mod tests {
use serde::{Deserialize, Serialize};