|
| 1 | +/* |
| 2 | + * Copyright (c) 2006-Present, Redis Ltd. |
| 3 | + * All rights reserved. |
| 4 | + * |
| 5 | + * Licensed under your choice of the Redis Source Available License 2.0 |
| 6 | + * (RSALv2); or (b) the Server Side Public License v1 (SSPLv1); or (c) the |
| 7 | + * GNU Affero General Public License v3 (AGPLv3). |
| 8 | +*/ |
| 9 | + |
| 10 | +/// The various document types supported by RediSearch. |
| 11 | +/// |
| 12 | +/// cbindgen:prefix-with-name |
| 13 | +#[repr(C)] |
| 14 | +#[derive( |
| 15 | + Clone, |
| 16 | + Copy, |
| 17 | + Debug, |
| 18 | + PartialEq, |
| 19 | + Eq, |
| 20 | + strum::EnumString, |
| 21 | + strum::Display, |
| 22 | + strum::AsRefStr, |
| 23 | + strum::FromRepr, |
| 24 | +)] |
| 25 | +pub enum DocumentType { |
| 26 | + /// Hash document type |
| 27 | + #[strum(serialize = "hash")] |
| 28 | + Hash = 0, |
| 29 | + /// JSON document type |
| 30 | + #[strum(serialize = "json")] |
| 31 | + Json = 1, |
| 32 | + /// Unsupported document type |
| 33 | + #[strum(serialize = "unsupported")] |
| 34 | + Unsupported = 2, |
| 35 | +} |
| 36 | + |
| 37 | +impl From<u32> for DocumentType { |
| 38 | + fn from(value: u32) -> Self { |
| 39 | + let Ok(value_usize) = value.try_into() else { |
| 40 | + return Self::Unsupported; |
| 41 | + }; |
| 42 | + |
| 43 | + Self::from_repr(value_usize).unwrap_or(Self::Unsupported) |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +#[cfg(test)] |
| 48 | +mod test { |
| 49 | + use std::str::FromStr; |
| 50 | + |
| 51 | + use crate::DocumentType; |
| 52 | + |
| 53 | + #[test] |
| 54 | + fn test_serialize_deserialize_from_ffi() { |
| 55 | + #[rustfmt::skip] |
| 56 | + let doc_types = [ |
| 57 | + (DocumentType::Hash, "hash", 0), |
| 58 | + (DocumentType::Json, "json", 1), |
| 59 | + (DocumentType::Unsupported, "unsupported", 2), |
| 60 | + ]; |
| 61 | + for (doc_type, expected_str, expected_ffi) in doc_types { |
| 62 | + let serialized = doc_type.to_string(); |
| 63 | + assert_eq!(serialized, expected_str); |
| 64 | + |
| 65 | + let deserialized = DocumentType::from_str(expected_str).unwrap(); |
| 66 | + assert_eq!(deserialized, doc_type); |
| 67 | + |
| 68 | + let from_num = DocumentType::from(expected_ffi as u32); |
| 69 | + assert_eq!(from_num, doc_type); |
| 70 | + |
| 71 | + let from_repr = DocumentType::from_repr(expected_ffi).unwrap(); |
| 72 | + assert_eq!(from_repr, doc_type); |
| 73 | + } |
| 74 | + |
| 75 | + assert_eq!(DocumentType::from(u32::MAX), DocumentType::Unsupported); |
| 76 | + |
| 77 | + assert_eq!( |
| 78 | + DocumentType::from_str("Je n'existe"), |
| 79 | + Err(strum::ParseError::VariantNotFound) |
| 80 | + ); |
| 81 | + |
| 82 | + assert_eq!(DocumentType::from_repr(usize::MAX), None); |
| 83 | + } |
| 84 | +} |
0 commit comments