serde_value_utils/
detect.rs

1// Copyright 2019-present, OVH SAS
2// All rights reserved.
3//
4// This OVH Software is licensed to you under the MIT license <LICENSE-MIT
5// https://opensource.org/licenses/MIT> or the Modified BSD license <LICENSE-BSD
6// https://opensource.org/licenses/BSD-3-Clause>, at your option. This file may not be copied,
7// modified, or distributed except according to those terms. Please review the Licences for the
8// specific language governing permissions and limitations relating to use of the SAFE Network
9// Software.
10//
11
12use serde_value::Value;
13
14/// Function to try to detect value type from String
15///
16/// Only the following types are recognized :
17/// * `bool`
18/// * `u64`
19/// * `i64`
20/// * `f64`
21/// * `String` (as fallback)
22/// 
23/// ```rust
24/// extern crate serde_value_utils;
25///
26/// use serde_value_utils::try_detect_type;
27///
28/// fn main() {
29///     println!("{:?}", try_detect_type("6.5"));
30/// }
31/// ```
32/// **Output**:
33/// ```
34/// F64(6.5)
35/// ```
36pub fn try_detect_type(raw: &str) -> Value {
37    if let Ok(data) = raw.parse::<bool>() {
38        return Value::Bool(data);
39    }
40    if let Ok(data) = raw.parse::<u64>() {
41        return Value::U64(data);
42    }
43    if let Ok(data) = raw.parse::<i64>() {
44        return Value::I64(data);
45    }
46    if let Ok(data) = raw.parse::<f64>() {
47        return Value::F64(data);
48    }
49    Value::String(raw.to_string())
50}