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    /// OpenAI Chat Completions API.
15    #[serde(rename = "openai_chat")]
16    OpenAiChat,
17    /// Anthropic Messages API.
18    #[serde(rename = "anthropic_messages")]
19    AnthropicMessages,
20    /// OpenAI Responses API.
21    #[serde(rename = "openai_responses")]
22    OpenAiResponses,
23}
24
25impl WireFormat {
26    /// Returns the stable string identifier for a built-in format.
27    pub const fn as_str(self) -> &'static str {
28        match self {
29            Self::OpenAiChat => "openai_chat",
30            Self::AnthropicMessages => "anthropic_messages",
31            Self::OpenAiResponses => "openai_responses",
32        }
33    }
34}
35
36impl fmt::Display for WireFormat {
37    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
38        formatter.write_str(self.as_str())
39    }
40}
41
42/// Extensible wire-format identifier used by codec registries.
43#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
44#[serde(transparent)]
45pub struct FormatId(String);
46
47impl FormatId {
48    /// Creates a format identifier from an arbitrary string.
49    pub fn new(id: impl Into<String>) -> Self {
50        Self(id.into())
51    }
52
53    /// Creates a format identifier for a built-in format.
54    pub fn known(format: WireFormat) -> Self {
55        Self(format.as_str().to_string())
56    }
57
58    /// Returns the format identifier as a borrowed string.
59    pub fn as_str(&self) -> &str {
60        &self.0
61    }
62}
63
64impl fmt::Display for FormatId {
65    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
66        formatter.write_str(self.as_str())
67    }
68}
69
70impl From<WireFormat> for FormatId {
71    fn from(format: WireFormat) -> Self {
72        Self::known(format)
73    }
74}
75
76impl From<&WireFormat> for FormatId {
77    fn from(format: &WireFormat) -> Self {
78        Self::known(*format)
79    }
80}
81
82impl From<&str> for FormatId {
83    fn from(id: &str) -> Self {
84        Self::new(id)
85    }
86}
87
88impl From<String> for FormatId {
89    fn from(id: String) -> Self {
90        Self::new(id)
91    }
92}
93
94impl From<&String> for FormatId {
95    fn from(id: &String) -> Self {
96        Self::new(id.clone())
97    }
98}
99
100impl From<Cow<'_, str>> for FormatId {
101    fn from(id: Cow<'_, str>) -> Self {
102        Self::new(id.into_owned())
103    }
104}