Buttplug sex toy control library
at dev 1.7 kB view raw
1// Buttplug Rust Source Code File - See https://buttplug.io for more info. 2// 3// Copyright 2016-2024 Nonpolynomial Labs LLC. All rights reserved. 4// 5// Licensed under the BSD 3-Clause license. See LICENSE file in the project root 6// for full license information. 7 8//! JSON Schema validator structure, used by the 9//! [DeviceConfigurationManager][crate::server::device::configuration::DeviceConfigurationManager] and 10//! buttplug message de/serializers in both the client and server. Uses the 11//! jsonschema library. 12 13use crate::message::serializer::ButtplugSerializerError; 14use jsonschema::Validator; 15 16pub struct JSONValidator { 17 schema: Validator, 18} 19 20impl JSONValidator { 21 /// Create a new validator. 22 /// 23 /// # Parameters 24 /// 25 /// - `schema`: JSON Schema that the validator should use. 26 pub fn new(schema: &str) -> Self { 27 let schema_json: serde_json::Value = 28 serde_json::from_str(schema).expect("Built in schema better be valid"); 29 let schema = Validator::new(&schema_json).expect("Built in schema better be valid"); 30 Self { schema } 31 } 32 33 /// Validates a json string, based on the schema the validator was created 34 /// with. 35 /// 36 /// # Parameters 37 /// 38 /// - `json_str`: JSON string to validate. 39 pub fn validate(&self, json_str: &str) -> Result<(), ButtplugSerializerError> { 40 let check_value = serde_json::from_str(json_str).map_err(|err| { 41 ButtplugSerializerError::JsonSerializerError(format!("Message: {json_str} - Error: {err:?}")) 42 })?; 43 self.schema.validate(&check_value).map_err(|err| { 44 ButtplugSerializerError::JsonSerializerError(format!( 45 "Error during JSON Schema Validation: {err:?}" 46 )) 47 }) 48 } 49}