wreq 1.3.2.3 → 1.3.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. checksums.yaml +4 -4
  2. data/Cargo.lock +24 -3
  3. data/Cargo.toml +5 -3
  4. data/Rakefile +9 -3
  5. data/VERSION +1 -1
  6. data/crates/README.md +1 -0
  7. data/crates/serde-magnus/Cargo.toml +29 -0
  8. data/crates/serde-magnus/LICENSE +19 -0
  9. data/crates/serde-magnus/README.md +147 -0
  10. data/{src/serde → crates/serde-magnus/src}/de/array_deserializer.rs +2 -2
  11. data/{src/serde → crates/serde-magnus/src}/de/array_enumerator.rs +1 -1
  12. data/{src/serde → crates/serde-magnus/src}/de/deserializer.rs +25 -31
  13. data/{src/serde → crates/serde-magnus/src}/de/enum_deserializer.rs +3 -3
  14. data/{src/serde → crates/serde-magnus/src}/de/hash_deserializer.rs +2 -2
  15. data/crates/serde-magnus/src/de/mod.rs +554 -0
  16. data/{src/serde → crates/serde-magnus/src}/de/number_deserializer.rs +2 -2
  17. data/{src/serde → crates/serde-magnus/src}/de/variant_deserializer.rs +11 -20
  18. data/crates/serde-magnus/src/error.rs +84 -0
  19. data/crates/serde-magnus/src/lib.rs +137 -0
  20. data/crates/serde-magnus/src/options.rs +151 -0
  21. data/crates/serde-magnus/src/ser/enums.rs +11 -0
  22. data/{src/serde → crates/serde-magnus/src}/ser/map_serializer.rs +2 -2
  23. data/crates/serde-magnus/src/ser/mod.rs +428 -0
  24. data/crates/serde-magnus/src/ser/seq_serializer.rs +68 -0
  25. data/crates/serde-magnus/src/ser/serializer.rs +220 -0
  26. data/{src/serde → crates/serde-magnus/src}/ser/struct_serializer.rs +4 -4
  27. data/crates/serde-magnus/src/ser/struct_variant_serializer.rs +45 -0
  28. data/crates/serde-magnus/src/ser/tuple_variant_serializer.rs +38 -0
  29. data/{src/serde → crates/serde-magnus/src}/tests.rs +19 -68
  30. data/src/client/body/json.rs +2 -1
  31. data/src/client/resp.rs +1 -1
  32. data/src/error.rs +3 -23
  33. data/src/lib.rs +0 -1
  34. data/src/options.rs +19 -17
  35. metadata +24 -20
  36. data/src/serde/de.rs +0 -33
  37. data/src/serde/error.rs +0 -146
  38. data/src/serde/ser/enums.rs +0 -14
  39. data/src/serde/ser/seq_serializer.rs +0 -71
  40. data/src/serde/ser/serializer.rs +0 -194
  41. data/src/serde/ser/struct_variant_serializer.rs +0 -44
  42. data/src/serde/ser/tuple_variant_serializer.rs +0 -41
  43. data/src/serde/ser.rs +0 -18
  44. data/src/serde.rs +0 -202
@@ -0,0 +1,84 @@
1
+ use std::fmt;
2
+
3
+ /// Error produced by the local Ruby and Serde bridge.
4
+ #[derive(Debug)]
5
+ pub(crate) enum Error {
6
+ Runtime(String),
7
+ Type(String),
8
+ DuplicateField(&'static str),
9
+ Ruby(magnus::Error),
10
+ }
11
+
12
+ impl Error {
13
+ /// Create a bridge error from a human-readable message.
14
+ pub(super) fn message(message: impl Into<String>) -> Self {
15
+ Self::Runtime(message.into())
16
+ }
17
+
18
+ /// Create a type mismatch error.
19
+ pub(super) fn type_error(message: impl Into<String>) -> Self {
20
+ Self::Type(message.into())
21
+ }
22
+
23
+ /// Convert this bridge error into the matching Ruby exception.
24
+ pub(super) fn into_magnus(self, ruby: &magnus::Ruby) -> magnus::Error {
25
+ match self {
26
+ Self::Runtime(message) => magnus::Error::new(ruby.exception_runtime_error(), message),
27
+ Self::Type(message) => magnus::Error::new(ruby.exception_type_error(), message),
28
+ Self::DuplicateField(field) => magnus::Error::new(
29
+ ruby.exception_runtime_error(),
30
+ format!("duplicate field `{field}`"),
31
+ ),
32
+ Self::Ruby(error) => error,
33
+ }
34
+ }
35
+ }
36
+
37
+ impl fmt::Display for Error {
38
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
39
+ match self {
40
+ Self::Runtime(message) | Self::Type(message) => formatter.write_str(message),
41
+ Self::DuplicateField(field) => write!(formatter, "duplicate field `{field}`"),
42
+ Self::Ruby(error) => error.fmt(formatter),
43
+ }
44
+ }
45
+ }
46
+
47
+ impl std::error::Error for Error {}
48
+
49
+ impl serde::ser::Error for Error {
50
+ fn custom<T>(message: T) -> Self
51
+ where
52
+ T: fmt::Display,
53
+ {
54
+ Self::message(message.to_string())
55
+ }
56
+ }
57
+
58
+ impl serde::de::Error for Error {
59
+ fn custom<T>(message: T) -> Self
60
+ where
61
+ T: fmt::Display,
62
+ {
63
+ Self::message(message.to_string())
64
+ }
65
+
66
+ fn invalid_type(
67
+ unexpected: serde::de::Unexpected<'_>,
68
+ expected: &dyn serde::de::Expected,
69
+ ) -> Self {
70
+ Self::type_error(format!(
71
+ "invalid type: expected {expected}, got {unexpected}"
72
+ ))
73
+ }
74
+
75
+ fn duplicate_field(field: &'static str) -> Self {
76
+ Self::DuplicateField(field)
77
+ }
78
+ }
79
+
80
+ impl From<magnus::Error> for Error {
81
+ fn from(error: magnus::Error) -> Self {
82
+ Self::Ruby(error)
83
+ }
84
+ }
@@ -0,0 +1,137 @@
1
+ #![deny(unsafe_code)]
2
+ #![doc(test(attr(warn(unused))))]
3
+
4
+ //! `serde_magnus` converts between Rust and Ruby data structures using [Serde] and [Magnus].
5
+ //!
6
+ //! [Serde]: https://github.com/serde-rs/serde
7
+ //! [Magnus]: https://github.com/matsadler/magnus
8
+ //!
9
+ //! The [`serialize`] function converts from a Rust type implementing the [`serde::Serialize`]
10
+ //! trait into a Ruby equivalent.
11
+ //!
12
+ //! ```
13
+ //! # // SAFETY: this doctest initializes Ruby once on its current thread.
14
+ //! # let ruby = unsafe { magnus::embed::init() };
15
+ //! #
16
+ //! use serde::{Serialize, Deserialize};
17
+ //! use magnus::{eval, Value};
18
+ //! use serde_magnus::serialize;
19
+ //!
20
+ //! #[derive(Serialize, Deserialize, PartialEq, Debug)]
21
+ //! struct Post {
22
+ //! title: String,
23
+ //! content: String,
24
+ //! author: Author,
25
+ //! tags: Vec<String>
26
+ //! }
27
+ //!
28
+ //! #[derive(Serialize, Deserialize, PartialEq, Debug)]
29
+ //! struct Author {
30
+ //! name: String,
31
+ //! email_address: String
32
+ //! }
33
+ //!
34
+ //! let post = Post {
35
+ //! title: "Spring carnival planning update".into(),
36
+ //! content: "Here's what's new.".into(),
37
+ //! author: Author {
38
+ //! name: "Martha".into(),
39
+ //! email_address: "martha@example.com".into()
40
+ //! },
41
+ //! tags: vec![
42
+ //! "carnival".into(),
43
+ //! "update".into()
44
+ //! ]
45
+ //! };
46
+ //!
47
+ //! let post: Value = serialize(&ruby, &post)?;
48
+ //!
49
+ //! assert!(eval!(
50
+ //! &ruby,
51
+ //! r#"
52
+ //! post == {
53
+ //! title: "Spring carnival planning update",
54
+ //! content: "Here's what's new.",
55
+ //! author: {
56
+ //! name: "Martha",
57
+ //! email_address: "martha@example.com"
58
+ //! },
59
+ //! tags: ["carnival", "update"]
60
+ //! }
61
+ //! "#,
62
+ //! post
63
+ //! )?);
64
+ //! #
65
+ //! # Ok::<(), magnus::Error>(())
66
+ //! ```
67
+ //!
68
+ //! [`deserialize`] converts from a Ruby value to a Rust type implementing [`serde::Deserialize`].
69
+ //!
70
+ //! ```
71
+ //! # use serde::Deserialize;
72
+ //! # use magnus::{eval, RHash};
73
+ //! #
74
+ //! # // SAFETY: this doctest initializes Ruby once on its current thread.
75
+ //! # let ruby = unsafe { magnus::embed::init() };
76
+ //! #
77
+ //! # #[derive(Deserialize, PartialEq, Debug)]
78
+ //! # struct Post {
79
+ //! # title: String,
80
+ //! # content: String,
81
+ //! # author: Author,
82
+ //! # tags: Vec<String>
83
+ //! # }
84
+ //! #
85
+ //! # #[derive(Deserialize, PartialEq, Debug)]
86
+ //! # struct Author {
87
+ //! # name: String,
88
+ //! # email_address: String
89
+ //! # }
90
+ //! #
91
+ //! use serde_magnus::deserialize;
92
+ //!
93
+ //! let post: RHash = eval!(&ruby, r#"
94
+ //! {
95
+ //! title: "Spring carnival planning update",
96
+ //! content: "Here's what's new.",
97
+ //! author: {
98
+ //! name: "Martha",
99
+ //! email_address: "martha@example.com"
100
+ //! },
101
+ //! tags: ["carnival", "update"]
102
+ //! }
103
+ //! "#)?;
104
+ //!
105
+ //! let post: Post = deserialize(&ruby, post)?;
106
+ //!
107
+ //! assert_eq!(
108
+ //! Post {
109
+ //! title: "Spring carnival planning update".into(),
110
+ //! content: "Here's what's new.".into(),
111
+ //! author: Author {
112
+ //! name: "Martha".into(),
113
+ //! email_address: "martha@example.com".into()
114
+ //! },
115
+ //! tags: vec![
116
+ //! "carnival".into(),
117
+ //! "update".into()
118
+ //! ]
119
+ //! },
120
+ //! post
121
+ //! );
122
+ //! #
123
+ //! # Ok::<(), magnus::Error>(())
124
+ //! ```
125
+
126
+ mod de;
127
+ mod error;
128
+ pub mod options;
129
+ mod ser;
130
+ #[cfg(test)]
131
+ mod tests;
132
+
133
+ pub use de::{deserialize, deserialize_json};
134
+ pub use ser::serialize;
135
+
136
+ /// Private map key used by `serde_json` for arbitrary-precision numbers.
137
+ const JSON_NUMBER_TOKEN: &str = "$serde_json::private::Number";
@@ -0,0 +1,151 @@
1
+ //! Serde-based validation and conversion of Ruby option hashes.
2
+
3
+ use std::fmt;
4
+
5
+ use indexmap::IndexSet;
6
+ use magnus::{Error, IntoValue, Ruby, error::ErrorType};
7
+ use serde::de::DeserializeOwned;
8
+ use serde_ignored::Path;
9
+ use serde_path_to_error::{Deserializer as PathDeserializer, Path as ErrorPath, Track};
10
+
11
+ use crate::{de::Deserializer, error::Error as SerdeError};
12
+
13
+ /// Validate Ruby option keys without inspecting their values.
14
+ ///
15
+ /// The derived struct is the only list of accepted keys. Every option field is
16
+ /// optional, so this pass can collect unknown keys and duplicates without
17
+ /// converting or retaining any Ruby value.
18
+ ///
19
+ /// # Errors
20
+ ///
21
+ /// Returns `ArgumentError` for unknown or duplicate keys and `TypeError` for
22
+ /// keys that are neither Ruby Symbols nor Strings.
23
+ pub fn validate_option_keys<Input, Output>(ruby: &Ruby, input: Input) -> Result<(), Error>
24
+ where
25
+ Input: IntoValue,
26
+ Output: DeserializeOwned,
27
+ {
28
+ let value: magnus::Value = input.into_value_with(ruby);
29
+ let mut unknown = IndexSet::new();
30
+ {
31
+ let mut callback = |path: Path<'_>| {
32
+ if let Path::Map { key, .. } = path {
33
+ unknown.insert(key);
34
+ }
35
+ };
36
+ serde_ignored::deserialize::<_, _, Output>(
37
+ Deserializer::new_option_keys(ruby, value),
38
+ &mut callback,
39
+ )
40
+ .map_err(|error| option_error(ruby, error, None))?;
41
+ }
42
+
43
+ if unknown.is_empty() {
44
+ return Ok(());
45
+ }
46
+
47
+ let label = if unknown.len() == 1 {
48
+ "unknown option"
49
+ } else {
50
+ "unknown options"
51
+ };
52
+ let mut message = String::from(label);
53
+ message.push(':');
54
+ for (index, name) in unknown.into_iter().enumerate() {
55
+ if index > 0 {
56
+ message.push(',');
57
+ }
58
+ message.push(' ');
59
+ message.push(':');
60
+ message.push_str(&name);
61
+ }
62
+
63
+ Err(Error::new(ruby.exception_arg_error(), message))
64
+ }
65
+
66
+ /// Deserialize validated Ruby options and retain the failing field path.
67
+ ///
68
+ /// # Errors
69
+ ///
70
+ /// Returns the Ruby conversion error with the failing option path attached.
71
+ pub fn deserialize_options<Input, Output>(ruby: &Ruby, input: Input) -> Result<Output, Error>
72
+ where
73
+ Input: IntoValue,
74
+ Output: DeserializeOwned,
75
+ {
76
+ let value = input.into_value_with(ruby);
77
+ let mut track = Track::new();
78
+ let result = Output::deserialize(PathDeserializer::new(
79
+ Deserializer::new(ruby, value),
80
+ &mut track,
81
+ ));
82
+
83
+ result.map_err(|error| {
84
+ let path = track.path();
85
+ let path = path.iter().next().is_some().then_some(&path);
86
+ option_error(ruby, error, path)
87
+ })
88
+ }
89
+
90
+ /// Prefix a Magnus error while preserving its original Ruby exception class.
91
+ pub fn contextualize_magnus_error(err: Error, context: fmt::Arguments<'_>) -> Error {
92
+ match err.error_type() {
93
+ ErrorType::Error(class, message) => Error::new(*class, format!("{context}: {message}")),
94
+ ErrorType::Exception(exception) => Error::new(
95
+ exception.exception_class(),
96
+ format!("{context}: {exception}"),
97
+ ),
98
+ ErrorType::Jump(_) => err,
99
+ }
100
+ }
101
+
102
+ /// Convert a Serde error into the Ruby exception expected for an option.
103
+ fn option_error(ruby: &Ruby, error: SerdeError, path: Option<&ErrorPath>) -> Error {
104
+ match error {
105
+ SerdeError::Runtime(message) => Error::new(
106
+ ruby.exception_arg_error(),
107
+ contextualize_message(path, message),
108
+ ),
109
+ SerdeError::Type(message) => Error::new(
110
+ ruby.exception_type_error(),
111
+ contextualize_message(path, message),
112
+ ),
113
+ SerdeError::DuplicateField(field) => Error::new(
114
+ ruby.exception_arg_error(),
115
+ format!("duplicate option: :{field}"),
116
+ ),
117
+ SerdeError::Ruby(error) if error.is_kind_of(ruby.exception_range_error()) => Error::new(
118
+ ruby.exception_arg_error(),
119
+ magnus_error_message(&error, path),
120
+ ),
121
+ SerdeError::Ruby(error) => match path {
122
+ Some(path) => {
123
+ contextualize_magnus_error(error, format_args!("invalid value for :{path}"))
124
+ }
125
+ None => error,
126
+ },
127
+ }
128
+ }
129
+
130
+ /// Prefix an error message when Serde identified the failing option path.
131
+ fn contextualize_message(path: Option<&ErrorPath>, message: String) -> String {
132
+ match path {
133
+ Some(path) => format!("invalid value for :{path}: {message}"),
134
+ None => message,
135
+ }
136
+ }
137
+
138
+ /// Build the final Ruby error message without an intermediate context String.
139
+ fn magnus_error_message(error: &Error, path: Option<&ErrorPath>) -> String {
140
+ match (path, error.error_type()) {
141
+ (Some(path), ErrorType::Error(_, message)) => {
142
+ format!("invalid value for :{path}: {message}")
143
+ }
144
+ (Some(path), ErrorType::Exception(exception)) => {
145
+ format!("invalid value for :{path}: {exception}")
146
+ }
147
+ (Some(path), ErrorType::Jump(_)) => format!("invalid value for :{path}: {error}"),
148
+ (None, ErrorType::Error(_, message)) => message.as_ref().to_owned(),
149
+ (None, _) => error.to_string(),
150
+ }
151
+ }
@@ -0,0 +1,11 @@
1
+ use crate::error::Error;
2
+ use magnus::{IntoValue, Ruby, Value};
3
+
4
+ pub fn nest<Data>(ruby: &Ruby, variant: &'static str, data: Data) -> Result<Value, Error>
5
+ where
6
+ Data: IntoValue,
7
+ {
8
+ let hash = ruby.hash_new();
9
+ hash.aset(variant, data)?;
10
+ Ok(hash.into_value_with(ruby))
11
+ }
@@ -1,8 +1,8 @@
1
- use ::serde::{Serialize, ser::SerializeMap};
2
1
  use magnus::{IntoValue, RHash, Ruby, Value};
2
+ use serde::{Serialize, ser::SerializeMap};
3
3
 
4
4
  use super::Serializer;
5
- use crate::serde::Error;
5
+ use crate::error::Error;
6
6
 
7
7
  /// Serde map serializer backed by a Ruby hash.
8
8
  pub(super) struct MapSerializer<'ruby> {