Skip to main content

switchyard_protocol/
format.rs

1// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Wire-format identifiers carried by the shared protocol types.
5
6use std::borrow::Cow;
7use std::fmt;
8
9use serde::{Deserialize, Serialize};
10
11/// Built-in provider API formats.
12#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
13pub enum WireFormat {
14    #[serde(rename = "openai_chat")]
15    OpenAiChat,
16    #[serde(rename = "anthropic_messages")]
17    AnthropicMessages,
18    #[serde(rename = "openai_responses")]
19    OpenAiResponses,
20}
21
22impl WireFormat {
23    /// Returns the stable string identifier for a built-in format.
24    pub const fn as_str(self) -> &'static str {
25        match self {
26            Self::OpenAiChat => "openai_chat",
27            Self::AnthropicMessages => "anthropic_messages",
28            Self::OpenAiResponses => "openai_responses",
29        }
30    }
31}
32
33impl fmt::Display for WireFormat {
34    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
35        formatter.write_str(self.as_str())
36    }
37}
38
39/// Extensible wire-format identifier used by codec registries.
40#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
41#[serde(transparent)]
42pub struct FormatId(String);
43
44impl FormatId {
45    /// Creates a format identifier from an arbitrary string.
46    pub fn new(id: impl Into<String>) -> Self {
47        Self(id.into())
48    }
49
50    /// Creates a format identifier for a built-in format.
51    pub fn known(format: WireFormat) -> Self {
52        Self(format.as_str().to_string())
53    }
54
55    /// Returns the format identifier as a borrowed string.
56    pub fn as_str(&self) -> &str {
57        &self.0
58    }
59}
60
61impl fmt::Display for FormatId {
62    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
63        formatter.write_str(self.as_str())
64    }
65}
66
67impl From<WireFormat> for FormatId {
68    fn from(format: WireFormat) -> Self {
69        Self::known(format)
70    }
71}
72
73impl From<&WireFormat> for FormatId {
74    fn from(format: &WireFormat) -> Self {
75        Self::known(*format)
76    }
77}
78
79impl From<&str> for FormatId {
80    fn from(id: &str) -> Self {
81        Self::new(id)
82    }
83}
84
85impl From<String> for FormatId {
86    fn from(id: String) -> Self {
87        Self::new(id)
88    }
89}
90
91impl From<&String> for FormatId {
92    fn from(id: &String) -> Self {
93        Self::new(id.clone())
94    }
95}
96
97impl From<Cow<'_, str>> for FormatId {
98    fn from(id: Cow<'_, str>) -> Self {
99        Self::new(id.into_owned())
100    }
101}