confluent_kafka/common/
topic_partition.rs1use std::fmt;
18use std::sync::Arc;
19
20#[derive(Clone, Debug, Eq)]
22#[doc(alias = "org.apache.kafka.common.TopicPartition")]
23pub struct TopicPartition {
24 partition: i32,
25 topic: Arc<str>,
26}
27
28impl TopicPartition {
29 #[doc(alias = "org.apache.kafka.common.TopicPartition#TopicPartition")]
36 pub fn new(topic: impl Into<Arc<str>>, partition: i32) -> Self {
37 Self { partition, topic: topic.into() }
38 }
39
40 #[doc(alias = "org.apache.kafka.common.TopicPartition#partition")]
42 pub fn partition(&self) -> i32 {
43 self.partition
44 }
45
46 #[doc(alias = "org.apache.kafka.common.TopicPartition#topic")]
48 pub fn topic(&self) -> &str {
49 &self.topic
50 }
51
52 pub(crate) fn topic_arc(&self) -> &Arc<str> {
54 &self.topic
55 }
56}
57
58impl PartialEq for TopicPartition {
59 fn eq(&self, other: &Self) -> bool {
60 self.partition == other.partition && self.topic == other.topic
61 }
62}
63
64impl std::hash::Hash for TopicPartition {
65 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
66 self.partition.hash(state);
67 self.topic.hash(state);
68 }
69}
70
71impl fmt::Display for TopicPartition {
72 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73 write!(f, "{}-{}", self.topic, self.partition)
74 }
75}
76
77#[cfg(test)]
78mod tests {
79 use super::*;
80
81 #[test]
82 fn test_topic_partition_creation() {
83 let tp = TopicPartition::new("mytopic".to_string(), 5);
84 assert_eq!(tp.partition(), 5);
85 assert_eq!(tp.topic(), "mytopic");
86 }
87
88 #[test]
89 fn test_topic_partition_equality() {
90 let tp1 = TopicPartition::new("test".to_string(), 0);
91 let tp2 = TopicPartition::new("test".to_string(), 0);
92 let tp3 = TopicPartition::new("test".to_string(), 1);
93 let tp4 = TopicPartition::new("other".to_string(), 0);
94
95 assert_eq!(tp1, tp2);
96 assert_ne!(tp1, tp3);
97 assert_ne!(tp1, tp4);
98 }
99
100 #[test]
101 fn test_topic_partition_hash() {
102 use std::collections::HashSet;
103 let mut set = HashSet::new();
104 set.insert(TopicPartition::new("test".to_string(), 0));
105 set.insert(TopicPartition::new("test".to_string(), 0));
106 assert_eq!(set.len(), 1);
107
108 set.insert(TopicPartition::new("test".to_string(), 1));
109 assert_eq!(set.len(), 2);
110 }
111
112 #[test]
113 fn test_topic_partition_display() {
114 let tp = TopicPartition::new("mytopic".to_string(), 5);
115 assert_eq!(tp.to_string(), "mytopic-5");
116 }
117}