buttplug_core 10.0.1

Buttplug Intimate Hardware Control Library - Core Library
// Buttplug Rust Source Code File - See https://buttplug.io for more info.
//
// Copyright 2016-2026 Nonpolynomial Labs LLC. All rights reserved.
//
// Licensed under the BSD 3-Clause license. See LICENSE file in the project root
// for full license information.

//! JSON Schema validator structure, used by the
//! [DeviceConfigurationManager][crate::server::device::configuration::DeviceConfigurationManager] and
//! buttplug message de/serializers in both the client and server. Uses the
//! jsonschema library.

use crate::message::serializer::ButtplugSerializerError;
use jsonschema::Validator;

pub struct JSONValidator {
  schema: Validator,
}

impl JSONValidator {
  /// Create a new validator.
  ///
  /// # Parameters
  ///
  /// - `schema`: JSON Schema that the validator should use.
  pub fn new(schema: &str) -> Self {
    // SAFETY: Schemas are embedded at compile time via include_str!() and validated by build.rs.
    // These expects can only fail if there's a build/packaging error, not at runtime.
    let schema_json: serde_json::Value =
      serde_json::from_str(schema).expect("schema must be valid JSON (validated by build.rs)");
    let schema = Validator::new(&schema_json)
      .expect("schema must be valid JSON Schema (validated by build.rs)");
    Self { schema }
  }

  /// Validates a json string, based on the schema the validator was created
  /// with.
  ///
  /// # Parameters
  ///
  /// - `json_str`: JSON string to validate.
  pub fn validate(&self, json_str: &str) -> Result<(), ButtplugSerializerError> {
    let check_value = serde_json::from_str(json_str).map_err(|err| {
      ButtplugSerializerError::JsonSerializerError(format!("Message: {json_str} - Error: {err:?}"))
    })?;
    self.schema.validate(&check_value).map_err(|err| {
      ButtplugSerializerError::JsonSerializerError(format!(
        "Error during JSON Schema Validation: {err:?}"
      ))
    })
  }
}