easy_callback 1.3.0

Automatic callback data encoding for teloxide
Documentation

easy_callback

Crates.io Documentation Tests License

Automatic callback data encoding for teloxide.

This crate provides a derive macro for quickly converting a custom user-defined type to a callback data string and converting a CallbackQuery back into the corresponding user-defined type, with support for different serialization implementations.

When encoding, the data is first serialized using the selected implementation and then encoded as a URL-safe, unpadded Base64 string. During decoding, the process is reversed.


Example

This example demonstrates the library's functionality using the count_bot example.

// ...

// Callback enum encoded using postcard
#[derive(Default, Serialize, Deserialize, PostcardCallback)]
enum Callback {
  Increment(i64),
  Decrement(i64),
  #[default]
  Fallback,
}

// ...

fn keyboard(value: i64) -> InlineKeyboardMarkup {
  // The callback is automatically encoded using postcard
  InlineKeyboardMarkup::new([[
    InlineKeyboardButton::callback(
      "+1",
      Callback::Increment(value),
    ),
    InlineKeyboardButton::callback(
      "-1",
      Callback::Decrement(value),
    ),
  ]])
}

// ...

async fn on_callback(
  bot: Bot,
  callback_query: CallbackQuery,
) -> ResponseResult<()> {
  // ...

  // Decode the callback query into the Callback enum
  let callback = Callback::from(callback_query);

  // ...
}

// ...

Usage

Add the following to your Cargo.toml, choosing one or more features corresponding to the implementations you want to use:

[dependencies]

easy_callback = { version = "1.3.0", features = ["postcard"] }

Available implementations:

Multiple implementations can be enabled simultaneously if required.


Implementation Size Comparison

Since Telegram limits callback data to 64 bytes, keeping the serialized representation compact is important.

A comparison of serialized sizes is available in the comparison example.

The following enum was used for benchmarking:

#[repr(u8)]
enum Callback {
  Action {
    id: i64, // 1234
    value: f32, // 1.234
  },
  #[default]
  Fallback,
}

The results below are measured in bytes after Base64 encoding:

Implementation Action Size Fallback Size
rkyv 32 32
wincode 22 6
postcard 10 2
bitcode 11 2
rmp 23 12
ciborium 35 12
borsh 18 2
speedy 22 6
oxicode 11 2

License

This project is licensed under either of

at your option.