rustrade_integration/subscription.rs
1use serde::{Deserialize, Serialize};
2use smol_str::SmolStr;
3use std::borrow::Borrow;
4use std::fmt::{Display, Formatter};
5
6/// New type representing a unique `String` identifier for a stream that has been subscribed to.
7/// This is used to identify data structures received over the socket.
8///
9/// For example, `Barter-Data` uses this identifier to associate received data structures from the
10/// execution with the original `Barter-Data` `Subscription` that was actioned over the socket.
11///
12/// Note: Each execution will require the use of different `String` identifiers depending on the
13/// data structures they send.
14///
15/// eg/ [`SubscriptionId`] of an `FtxTrade` is "{BASE}/{QUOTE}" (ie/ market).
16/// eg/ [`SubscriptionId`] of a `BinanceTrade` is `"@trade|BTCUSDT"` (ie/ channel|MARKET).
17#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
18pub struct SubscriptionId(pub SmolStr);
19
20impl Display for SubscriptionId {
21 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
22 write!(f, "{}", self.0)
23 }
24}
25
26impl AsRef<str> for SubscriptionId {
27 fn as_ref(&self) -> &str {
28 &self.0
29 }
30}
31
32/// Borrow a [`SubscriptionId`] as a `&str` so an instrument map keyed on [`SubscriptionId`]
33/// can be queried with a borrowed key (e.g. `Map::find("@kline_1m|BTCUSDT")`) without
34/// allocating an owned [`SubscriptionId`] per lookup.
35///
36/// Soundness: the `Hash`, `Eq`, and `Ord` impls of [`SubscriptionId`] must agree with those of
37/// `str` for `Borrow` to be valid. [`SubscriptionId`] derives all three over its single inner
38/// [`SmolStr`] field, and `SmolStr`'s `Hash`/`Eq`/`Ord` delegate to its string contents — so a
39/// `SubscriptionId` hashes, compares, and orders identically to the `str` it borrows.
40impl Borrow<str> for SubscriptionId {
41 fn borrow(&self) -> &str {
42 &self.0
43 }
44}
45
46impl<S> From<S> for SubscriptionId
47where
48 S: Into<SmolStr>,
49{
50 fn from(input: S) -> Self {
51 Self(input.into())
52 }
53}