src/message/mod.rs
729 lines · 23070 bytes
1use std::borrow::Cow;
2use std::cmp::{Ord, Ordering, PartialOrd};
3use std::collections::hash_map::DefaultHasher;
4use std::collections::BTreeMap;
5use std::convert::TryFrom;
6use std::hash::{Hash, Hasher};
7
8use chrono::{DateTime, NaiveDateTime, Utc};
9use unicode_width::UnicodeWidthStr;
10
11use matrix_sdk::ruma::{
12 events::{
13 room::{
14 message::{
15 FormattedBody,
16 MessageFormat,
17 MessageType,
18 OriginalRoomMessageEvent,
19 RedactedRoomMessageEvent,
20 Relation,
21 RoomMessageEvent,
22 RoomMessageEventContent,
23 },
24 redaction::SyncRoomRedactionEvent,
25 },
26 Redact,
27 },
28 MilliSecondsSinceUnixEpoch,
29 OwnedEventId,
30 OwnedUserId,
31 RoomVersionId,
32 UInt,
33};
34
35use modalkit::tui::{
36 style::{Modifier as StyleModifier, Style},
37 symbols::line::THICK_VERTICAL,
38 text::{Span, Spans, Text},
39};
40
41use modalkit::editing::{base::ViewportContext, cursor::Cursor};
42
43use crate::{
44 base::{IambResult, RoomInfo},
45 config::ApplicationSettings,
46 message::html::{parse_matrix_html, StyleTree},
47 util::{space_span, wrapped_text},
48};
49
50mod html;
51mod printer;
52
53pub type MessageFetchResult = IambResult<(Option<String>, Vec<RoomMessageEvent>)>;
54pub type MessageKey = (MessageTimeStamp, OwnedEventId);
55pub type Messages = BTreeMap<MessageKey, Message>;
56
57const USER_GUTTER: usize = 30;
58const TIME_GUTTER: usize = 12;
59const MIN_MSG_LEN: usize = 30;
60
61const USER_GUTTER_EMPTY: &str = " ";
62const USER_GUTTER_EMPTY_SPAN: Span<'static> = Span {
63 content: Cow::Borrowed(USER_GUTTER_EMPTY),
64 style: Style {
65 fg: None,
66 bg: None,
67 add_modifier: StyleModifier::empty(),
68 sub_modifier: StyleModifier::empty(),
69 },
70};
71
72#[derive(thiserror::Error, Debug)]
73pub enum TimeStampIntError {
74 #[error("Integer conversion error: {0}")]
75 IntError(#[from] std::num::TryFromIntError),
76
77 #[error("UInt conversion error: {0}")]
78 UIntError(<UInt as TryFrom<u64>>::Error),
79}
80
81#[derive(Clone, Copy, Debug, Eq, PartialEq)]
82pub enum MessageTimeStamp {
83 OriginServer(UInt),
84 LocalEcho,
85}
86
87impl MessageTimeStamp {
88 fn show(&self) -> Option<Span> {
89 match self {
90 MessageTimeStamp::OriginServer(ts) => {
91 let time = i64::from(*ts) / 1000;
92 let time = NaiveDateTime::from_timestamp_opt(time, 0)?;
93 let time = DateTime::<Utc>::from_utc(time, Utc);
94 let time = time.format("%T");
95 let time = format!(" [{}]", time);
96
97 Span::raw(time).into()
98 },
99 MessageTimeStamp::LocalEcho => None,
100 }
101 }
102
103 fn is_local_echo(&self) -> bool {
104 matches!(self, MessageTimeStamp::LocalEcho)
105 }
106
107 pub fn as_millis(&self) -> Option<MilliSecondsSinceUnixEpoch> {
108 match self {
109 MessageTimeStamp::OriginServer(ms) => MilliSecondsSinceUnixEpoch(*ms).into(),
110 MessageTimeStamp::LocalEcho => None,
111 }
112 }
113}
114
115impl Ord for MessageTimeStamp {
116 fn cmp(&self, other: &Self) -> Ordering {
117 match (self, other) {
118 (MessageTimeStamp::OriginServer(_), MessageTimeStamp::LocalEcho) => Ordering::Less,
119 (MessageTimeStamp::OriginServer(a), MessageTimeStamp::OriginServer(b)) => a.cmp(b),
120 (MessageTimeStamp::LocalEcho, MessageTimeStamp::OriginServer(_)) => Ordering::Greater,
121 (MessageTimeStamp::LocalEcho, MessageTimeStamp::LocalEcho) => Ordering::Equal,
122 }
123 }
124}
125
126impl PartialOrd for MessageTimeStamp {
127 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
128 self.cmp(other).into()
129 }
130}
131
132impl From<MilliSecondsSinceUnixEpoch> for MessageTimeStamp {
133 fn from(millis: MilliSecondsSinceUnixEpoch) -> Self {
134 MessageTimeStamp::OriginServer(millis.0)
135 }
136}
137
138impl TryFrom<&MessageTimeStamp> for usize {
139 type Error = TimeStampIntError;
140
141 fn try_from(ts: &MessageTimeStamp) -> Result<Self, Self::Error> {
142 let n = match ts {
143 MessageTimeStamp::LocalEcho => 0,
144 MessageTimeStamp::OriginServer(u) => usize::try_from(u64::from(*u))?,
145 };
146
147 Ok(n)
148 }
149}
150
151impl TryFrom<usize> for MessageTimeStamp {
152 type Error = TimeStampIntError;
153
154 fn try_from(u: usize) -> Result<Self, Self::Error> {
155 if u == 0 {
156 Ok(MessageTimeStamp::LocalEcho)
157 } else {
158 let n = u64::try_from(u)?;
159 let n = UInt::try_from(n).map_err(TimeStampIntError::UIntError)?;
160
161 Ok(MessageTimeStamp::OriginServer(n))
162 }
163 }
164}
165
166#[derive(Clone, Debug, Default, Eq, PartialEq)]
167pub struct MessageCursor {
168 /// When timestamp is None, the corner is determined by moving backwards from
169 /// the most recently received message.
170 pub timestamp: Option<MessageKey>,
171
172 /// A row within the [Text] representation of a [Message].
173 pub text_row: usize,
174}
175
176impl MessageCursor {
177 pub fn new(timestamp: MessageKey, text_row: usize) -> Self {
178 MessageCursor { timestamp: Some(timestamp), text_row }
179 }
180
181 /// Get a cursor that refers to the most recent message.
182 pub fn latest() -> Self {
183 MessageCursor::default()
184 }
185
186 pub fn to_key<'a>(&'a self, info: &'a RoomInfo) -> Option<&'a MessageKey> {
187 if let Some(ref key) = self.timestamp {
188 Some(key)
189 } else {
190 Some(info.messages.last_key_value()?.0)
191 }
192 }
193
194 pub fn from_cursor(cursor: &Cursor, info: &RoomInfo) -> Option<Self> {
195 let ev_hash = u64::try_from(cursor.get_x()).ok()?;
196 let ev_term = OwnedEventId::try_from("$").ok()?;
197
198 let ts_start = MessageTimeStamp::try_from(cursor.get_y()).ok()?;
199 let start = (ts_start, ev_term);
200 let mut mc = None;
201
202 for ((ts, event_id), _) in info.messages.range(start..) {
203 let mut hasher = DefaultHasher::new();
204 event_id.hash(&mut hasher);
205
206 if hasher.finish() == ev_hash {
207 mc = Self::from((*ts, event_id.clone())).into();
208 break;
209 }
210
211 if mc.is_none() {
212 mc = Self::from((*ts, event_id.clone())).into();
213 }
214
215 if ts > &ts_start {
216 break;
217 }
218 }
219
220 return mc;
221 }
222
223 pub fn to_cursor(&self, info: &RoomInfo) -> Option<Cursor> {
224 let (ts, event_id) = self.to_key(info)?;
225
226 let y: usize = usize::try_from(ts).ok()?;
227
228 let mut hasher = DefaultHasher::new();
229 event_id.hash(&mut hasher);
230 let x = usize::try_from(hasher.finish()).ok()?;
231
232 Cursor::new(y, x).into()
233 }
234}
235
236impl From<Option<MessageKey>> for MessageCursor {
237 fn from(key: Option<MessageKey>) -> Self {
238 MessageCursor { timestamp: key, text_row: 0 }
239 }
240}
241
242impl From<MessageKey> for MessageCursor {
243 fn from(key: MessageKey) -> Self {
244 MessageCursor { timestamp: Some(key), text_row: 0 }
245 }
246}
247
248impl Ord for MessageCursor {
249 fn cmp(&self, other: &Self) -> Ordering {
250 match (&self.timestamp, &other.timestamp) {
251 (None, None) => self.text_row.cmp(&other.text_row),
252 (None, Some(_)) => Ordering::Greater,
253 (Some(_), None) => Ordering::Less,
254 (Some(st), Some(ot)) => {
255 let pcmp = st.cmp(ot);
256 let tcmp = self.text_row.cmp(&other.text_row);
257
258 pcmp.then(tcmp)
259 },
260 }
261 }
262}
263
264impl PartialOrd for MessageCursor {
265 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
266 self.cmp(other).into()
267 }
268}
269
270#[derive(Clone)]
271pub enum MessageEvent {
272 Original(Box<OriginalRoomMessageEvent>),
273 Redacted(Box<RedactedRoomMessageEvent>),
274 Local(Box<RoomMessageEventContent>),
275}
276
277impl MessageEvent {
278 pub fn body(&self) -> Cow<'_, str> {
279 match self {
280 MessageEvent::Original(ev) => body_cow_content(&ev.content),
281 MessageEvent::Redacted(ev) => {
282 let reason = ev
283 .unsigned
284 .redacted_because
285 .as_ref()
286 .and_then(|e| e.as_original())
287 .and_then(|r| r.content.reason.as_ref());
288
289 if let Some(r) = reason {
290 Cow::Owned(format!("[Redacted: {:?}]", r))
291 } else {
292 Cow::Borrowed("[Redacted]")
293 }
294 },
295 MessageEvent::Local(content) => body_cow_content(content),
296 }
297 }
298
299 pub fn html(&self) -> Option<StyleTree> {
300 let content = match self {
301 MessageEvent::Original(ev) => &ev.content,
302 MessageEvent::Redacted(_) => return None,
303 MessageEvent::Local(content) => content,
304 };
305
306 if let MessageType::Text(content) = &content.msgtype {
307 if let Some(FormattedBody { format: MessageFormat::Html, body }) = &content.formatted {
308 Some(parse_matrix_html(body.as_str()))
309 } else {
310 None
311 }
312 } else {
313 None
314 }
315 }
316
317 pub fn redact(&mut self, redaction: SyncRoomRedactionEvent, version: &RoomVersionId) {
318 match self {
319 MessageEvent::Redacted(_) => return,
320 MessageEvent::Local(_) => return,
321 MessageEvent::Original(ev) => {
322 let redacted = ev.clone().redact(redaction, version);
323 *self = MessageEvent::Redacted(Box::new(redacted));
324 },
325 }
326 }
327}
328
329fn body_cow_content(content: &RoomMessageEventContent) -> Cow<'_, str> {
330 let s = match &content.msgtype {
331 MessageType::Text(content) => content.body.as_str(),
332 MessageType::VerificationRequest(_) => "[Verification Request]",
333 MessageType::Emote(content) => content.body.as_ref(),
334 MessageType::Notice(content) => content.body.as_str(),
335 MessageType::ServerNotice(content) => content.body.as_str(),
336
337 MessageType::Audio(content) => {
338 return Cow::Owned(format!("[Attached Audio: {}]", content.body));
339 },
340 MessageType::File(content) => {
341 return Cow::Owned(format!("[Attached File: {}]", content.body));
342 },
343 MessageType::Image(content) => {
344 return Cow::Owned(format!("[Attached Image: {}]", content.body));
345 },
346 MessageType::Video(content) => {
347 return Cow::Owned(format!("[Attached Video: {}]", content.body));
348 },
349 _ => {
350 return Cow::Owned(format!("[Unknown message type: {:?}]", content.msgtype()));
351 },
352 };
353
354 Cow::Borrowed(s)
355}
356
357enum MessageColumns<'a> {
358 Three(usize, Option<Span<'a>>, Option<Span<'a>>),
359 Two(usize, Option<Span<'a>>),
360 One(usize, Option<Span<'a>>),
361}
362
363impl<'a> MessageColumns<'a> {
364 fn width(&self) -> usize {
365 match self {
366 MessageColumns::Three(fill, _, _) => *fill,
367 MessageColumns::Two(fill, _) => *fill,
368 MessageColumns::One(fill, _) => *fill,
369 }
370 }
371
372 #[inline]
373 fn push_spans(&mut self, spans: Spans<'a>, style: Style, text: &mut Text<'a>) {
374 match self {
375 MessageColumns::Three(_, user, time) => {
376 let user = user.take().unwrap_or(USER_GUTTER_EMPTY_SPAN);
377 let time = time.take().unwrap_or_else(|| Span::from(""));
378
379 let mut line = vec![user];
380 line.extend(spans.0);
381 line.push(time);
382
383 text.lines.push(Spans(line))
384 },
385 MessageColumns::Two(_, opt) => {
386 let user = opt.take().unwrap_or(USER_GUTTER_EMPTY_SPAN);
387 let mut line = vec![user];
388 line.extend(spans.0);
389
390 text.lines.push(Spans(line));
391 },
392 MessageColumns::One(_, opt) => {
393 if let Some(user) = opt.take() {
394 text.lines.push(Spans(vec![user]));
395 }
396
397 let leading = space_span(2, style);
398 let mut line = vec![leading];
399 line.extend(spans.0);
400
401 text.lines.push(Spans(line));
402 },
403 }
404 }
405
406 fn push_text(&mut self, append: Text<'a>, style: Style, text: &mut Text<'a>) {
407 for line in append.lines.into_iter() {
408 self.push_spans(line, style, text);
409 }
410 }
411}
412
413pub struct Message {
414 pub event: MessageEvent,
415 pub sender: OwnedUserId,
416 pub timestamp: MessageTimeStamp,
417 pub downloaded: bool,
418 pub html: Option<StyleTree>,
419}
420
421impl Message {
422 pub fn new(event: MessageEvent, sender: OwnedUserId, timestamp: MessageTimeStamp) -> Self {
423 let html = event.html();
424 let downloaded = false;
425
426 Message { event, sender, timestamp, downloaded, html }
427 }
428
429 pub fn reply_to(&self) -> Option<OwnedEventId> {
430 let content = match &self.event {
431 MessageEvent::Local(content) => content,
432 MessageEvent::Original(ev) => &ev.content,
433 MessageEvent::Redacted(_) => return None,
434 };
435
436 if let Some(Relation::Reply { in_reply_to }) = &content.relates_to {
437 Some(in_reply_to.event_id.clone())
438 } else {
439 None
440 }
441 }
442
443 fn get_render_style(&self, selected: bool) -> Style {
444 let mut style = Style::default();
445
446 if selected {
447 style = style.add_modifier(StyleModifier::REVERSED)
448 }
449
450 if self.timestamp.is_local_echo() {
451 style = style.add_modifier(StyleModifier::ITALIC);
452 }
453
454 return style;
455 }
456
457 fn get_render_format(
458 &self,
459 prev: Option<&Message>,
460 width: usize,
461 settings: &ApplicationSettings,
462 ) -> MessageColumns {
463 if USER_GUTTER + TIME_GUTTER + MIN_MSG_LEN <= width {
464 let lw = width - USER_GUTTER - TIME_GUTTER;
465 let user = self.show_sender(prev, true, settings);
466 let time = self.timestamp.show();
467
468 MessageColumns::Three(lw, user, time)
469 } else if USER_GUTTER + MIN_MSG_LEN <= width {
470 let lw = width - USER_GUTTER;
471 let user = self.show_sender(prev, true, settings);
472
473 MessageColumns::Two(lw, user)
474 } else {
475 let lw = width.saturating_sub(2);
476 let user = self.show_sender(prev, false, settings);
477
478 MessageColumns::One(lw, user)
479 }
480 }
481
482 pub fn show<'a>(
483 &'a self,
484 prev: Option<&Message>,
485 selected: bool,
486 vwctx: &ViewportContext<MessageCursor>,
487 info: &'a RoomInfo,
488 settings: &ApplicationSettings,
489 ) -> Text<'a> {
490 let width = vwctx.get_width();
491
492 let style = self.get_render_style(selected);
493 let mut fmt = self.get_render_format(prev, width, settings);
494 let mut text = Text { lines: vec![] };
495 let width = fmt.width();
496
497 // Show the message that this one replied to, if any.
498 let reply = self.reply_to().and_then(|e| info.get_event(&e));
499
500 if let Some(r) = &reply {
501 let w = width.saturating_sub(2);
502 let mut replied = r.show_msg(w, style, true);
503 let mut sender = r.sender_span(settings);
504 let sender_width = UnicodeWidthStr::width(sender.content.as_ref());
505 let trailing = w.saturating_sub(sender_width + 1);
506
507 sender.style = sender.style.patch(style);
508
509 fmt.push_spans(
510 Spans(vec![
511 Span::styled(" ", style),
512 Span::styled(THICK_VERTICAL, style),
513 sender,
514 Span::styled(":", style),
515 space_span(trailing, style),
516 ]),
517 style,
518 &mut text,
519 );
520
521 for line in replied.lines.iter_mut() {
522 line.0.insert(0, Span::styled(THICK_VERTICAL, style));
523 line.0.insert(0, Span::styled(" ", style));
524 }
525
526 fmt.push_text(replied, style, &mut text);
527 }
528
529 // Now show the message contents, and the inlined reply if we couldn't find it above.
530 let msg = self.show_msg(width, style, reply.is_some());
531 fmt.push_text(msg, style, &mut text);
532
533 if text.lines.is_empty() {
534 // If there was nothing in the body, just show an empty message.
535 fmt.push_spans(space_span(width, style).into(), style, &mut text);
536 }
537
538 return text;
539 }
540
541 pub fn show_msg(&self, width: usize, style: Style, hide_reply: bool) -> Text {
542 if let Some(html) = &self.html {
543 html.to_text(width, style, hide_reply)
544 } else {
545 let mut msg = self.event.body();
546
547 if self.downloaded {
548 msg.to_mut().push_str(" \u{2705}");
549 }
550
551 wrapped_text(msg, width, style)
552 }
553 }
554
555 fn sender_span(&self, settings: &ApplicationSettings) -> Span {
556 settings.get_user_span(self.sender.as_ref())
557 }
558
559 fn show_sender(
560 &self,
561 prev: Option<&Message>,
562 align_right: bool,
563 settings: &ApplicationSettings,
564 ) -> Option<Span> {
565 let user = if matches!(prev, Some(prev) if self.sender == prev.sender) {
566 return None;
567 } else {
568 self.sender_span(settings)
569 };
570
571 let Span { content, style } = user;
572 let stop = content.len().min(28);
573 let s = &content[..stop];
574
575 let sender = if align_right {
576 format!("{: >width$} ", s, width = 28)
577 } else {
578 format!("{: <width$} ", s, width = 28)
579 };
580
581 Span::styled(sender, style).into()
582 }
583}
584
585impl From<OriginalRoomMessageEvent> for Message {
586 fn from(event: OriginalRoomMessageEvent) -> Self {
587 let timestamp = event.origin_server_ts.into();
588 let user_id = event.sender.clone();
589 let content = MessageEvent::Original(event.into());
590
591 Message::new(content, user_id, timestamp)
592 }
593}
594
595impl From<RedactedRoomMessageEvent> for Message {
596 fn from(event: RedactedRoomMessageEvent) -> Self {
597 let timestamp = event.origin_server_ts.into();
598 let user_id = event.sender.clone();
599 let content = MessageEvent::Redacted(event.into());
600
601 Message::new(content, user_id, timestamp)
602 }
603}
604
605impl From<RoomMessageEvent> for Message {
606 fn from(event: RoomMessageEvent) -> Self {
607 match event {
608 RoomMessageEvent::Original(ev) => ev.into(),
609 RoomMessageEvent::Redacted(ev) => ev.into(),
610 }
611 }
612}
613
614impl ToString for Message {
615 fn to_string(&self) -> String {
616 self.event.body().into_owned()
617 }
618}
619
620#[cfg(test)]
621pub mod tests {
622 use super::*;
623 use crate::tests::*;
624
625 #[test]
626 fn test_mc_cmp() {
627 let mc1 = MessageCursor::from(MSG1_KEY.clone());
628 let mc2 = MessageCursor::from(MSG2_KEY.clone());
629 let mc3 = MessageCursor::from(MSG3_KEY.clone());
630 let mc4 = MessageCursor::from(MSG4_KEY.clone());
631 let mc5 = MessageCursor::from(MSG5_KEY.clone());
632
633 // Everything is equal to itself.
634 assert_eq!(mc1.cmp(&mc1), Ordering::Equal);
635 assert_eq!(mc2.cmp(&mc2), Ordering::Equal);
636 assert_eq!(mc3.cmp(&mc3), Ordering::Equal);
637 assert_eq!(mc4.cmp(&mc4), Ordering::Equal);
638 assert_eq!(mc5.cmp(&mc5), Ordering::Equal);
639
640 // Local echo is always greater than an origin server timestamp.
641 assert_eq!(mc1.cmp(&mc2), Ordering::Greater);
642 assert_eq!(mc1.cmp(&mc3), Ordering::Greater);
643 assert_eq!(mc1.cmp(&mc4), Ordering::Greater);
644 assert_eq!(mc1.cmp(&mc5), Ordering::Greater);
645
646 // mc2 is the smallest timestamp.
647 assert_eq!(mc2.cmp(&mc1), Ordering::Less);
648 assert_eq!(mc2.cmp(&mc3), Ordering::Less);
649 assert_eq!(mc2.cmp(&mc4), Ordering::Less);
650 assert_eq!(mc2.cmp(&mc5), Ordering::Less);
651
652 // mc3 should be less than mc4 because of its event ID.
653 assert_eq!(mc3.cmp(&mc1), Ordering::Less);
654 assert_eq!(mc3.cmp(&mc2), Ordering::Greater);
655 assert_eq!(mc3.cmp(&mc4), Ordering::Less);
656 assert_eq!(mc3.cmp(&mc5), Ordering::Less);
657
658 // mc4 should be greater than mc3 because of its event ID.
659 assert_eq!(mc4.cmp(&mc1), Ordering::Less);
660 assert_eq!(mc4.cmp(&mc2), Ordering::Greater);
661 assert_eq!(mc4.cmp(&mc3), Ordering::Greater);
662 assert_eq!(mc4.cmp(&mc5), Ordering::Less);
663
664 // mc5 is the greatest OriginServer timestamp.
665 assert_eq!(mc5.cmp(&mc1), Ordering::Less);
666 assert_eq!(mc5.cmp(&mc2), Ordering::Greater);
667 assert_eq!(mc5.cmp(&mc3), Ordering::Greater);
668 assert_eq!(mc5.cmp(&mc4), Ordering::Greater);
669 }
670
671 #[test]
672 fn test_mc_to_key() {
673 let info = mock_room();
674 let mc1 = MessageCursor::from(MSG1_KEY.clone());
675 let mc2 = MessageCursor::from(MSG2_KEY.clone());
676 let mc3 = MessageCursor::from(MSG3_KEY.clone());
677 let mc4 = MessageCursor::from(MSG4_KEY.clone());
678 let mc5 = MessageCursor::from(MSG5_KEY.clone());
679 let mc6 = MessageCursor::latest();
680
681 let k1 = mc1.to_key(&info).unwrap();
682 let k2 = mc2.to_key(&info).unwrap();
683 let k3 = mc3.to_key(&info).unwrap();
684 let k4 = mc4.to_key(&info).unwrap();
685 let k5 = mc5.to_key(&info).unwrap();
686 let k6 = mc6.to_key(&info).unwrap();
687
688 // These should all be equal to their MSGN_KEYs.
689 assert_eq!(k1, &MSG1_KEY.clone());
690 assert_eq!(k2, &MSG2_KEY.clone());
691 assert_eq!(k3, &MSG3_KEY.clone());
692 assert_eq!(k4, &MSG4_KEY.clone());
693 assert_eq!(k5, &MSG5_KEY.clone());
694
695 // MessageCursor::latest() turns into the largest key (our local echo message).
696 assert_eq!(k6, &MSG1_KEY.clone());
697
698 // MessageCursor::latest() fails to convert for a room w/o messages.
699 let info_empty = RoomInfo::default();
700 assert_eq!(mc6.to_key(&info_empty), None);
701 }
702
703 #[test]
704 fn test_mc_to_from_cursor() {
705 let info = mock_room();
706 let mc1 = MessageCursor::from(MSG1_KEY.clone());
707 let mc2 = MessageCursor::from(MSG2_KEY.clone());
708 let mc3 = MessageCursor::from(MSG3_KEY.clone());
709 let mc4 = MessageCursor::from(MSG4_KEY.clone());
710 let mc5 = MessageCursor::from(MSG5_KEY.clone());
711 let mc6 = MessageCursor::latest();
712
713 let identity = |mc: &MessageCursor| {
714 let c = mc.to_cursor(&info).unwrap();
715
716 MessageCursor::from_cursor(&c, &info).unwrap()
717 };
718
719 // These should all convert to a Cursor and back to the original value.
720 assert_eq!(identity(&mc1), mc1);
721 assert_eq!(identity(&mc2), mc2);
722 assert_eq!(identity(&mc3), mc3);
723 assert_eq!(identity(&mc4), mc4);
724 assert_eq!(identity(&mc5), mc5);
725
726 // MessageCursor::latest() should point at the most recent message after conversion.
727 assert_eq!(identity(&mc6), mc1);
728 }
729}