kyori_component_json/parsing.rs
1//! Provides traits for parsing and serializing Minecraft text [`Component`]s.
2//!
3//! This module defines two core traits, [`ComponentParser`] and [`ComponentSerializer`],
4//! which abstract the conversion between string representations and the internal
5//! `Component` data structure.
6//!
7//! # Overview
8//!
9//! - [`ComponentParser`] allows parsing a string into a [`Component`].
10//! - [`ComponentSerializer`] allows serializing a [`Component`] back into a string.
11//!
12//! These traits are intended to empower developers to implement conversions from and to other formats
13//! without tying your code to a specific serialization or parsing library.
14//!
15//! # Use cases
16//!
17//! - Implement `ComponentParser` to convert from a user-provided formatted string (e.g., Discord Markdown)
18//! into a `Component`.
19//! - Implement `ComponentSerializer` to convert your `Component` back into a string format
20//! (like a binary representation or custom formats) for storage, transmission, or display.
21//!
22use crate::Component;
23
24/// A trait for parsing a string into a [`Component`].
25pub trait ComponentParser {
26 /// Error type returned when parsing fails.
27 type Err;
28
29 /// Parses a string input into a [`Component`].
30 ///
31 /// # Parameters
32 ///
33 /// - `input`: A string slice or any type that can be referenced as a string.
34 ///
35 /// # Returns
36 ///
37 /// Returns a `Result` containing a parsed [`Component`] on success,
38 /// or an error of type [`Self::Err`] on failure.
39 fn from_string(input: impl AsRef<str>) -> Result<Component, Self::Err>;
40}
41
42/// A trait for serializing a [`Component`] into a string representation.
43pub trait ComponentSerializer {
44 /// Error type returned when serialization fails.
45 type Err;
46
47 /// Serializes a [`Component`] into a string representation.
48 ///
49 /// # Parameters
50 ///
51 /// - `component`: A reference to the [`Component`] to serialize.
52 ///
53 /// # Returns
54 ///
55 /// Returns a `Result` containing the serialized string on success,
56 /// or an error of type [`Self::Err`] on failure.
57 fn to_string(component: &Component) -> Result<String, Self::Err>;
58}