Skip to content

Commit

Permalink
Formatting schema additions according to rustfmt directives
Browse files Browse the repository at this point in the history
as per project policy.
  • Loading branch information
Leonhard Weber authored and dginev committed Jan 16, 2020
1 parent f4ee86a commit 27050bf
Show file tree
Hide file tree
Showing 7 changed files with 202 additions and 261 deletions.
40 changes: 18 additions & 22 deletions examples/schema_example.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,33 +6,29 @@ use libxml::schemas::SchemaValidationContext;

use libxml::parser::Parser;

fn main() {
let xml = Parser::default()
.parse_file("tests/resources/schema.xml")
.expect("Expected to be able to parse XML Document from file");

fn main()
{
let xml = Parser::default()
.parse_file("tests/resources/schema.xml")
.expect("Expected to be able to parse XML Document from file");
let mut xsdparser = SchemaParserContext::from_file("tests/resources/schema.xsd");
let xsd = SchemaValidationContext::from_parser(&mut xsdparser);

let mut xsdparser = SchemaParserContext::from_file("tests/resources/schema.xsd");
let xsd = SchemaValidationContext::from_parser(&mut xsdparser);

if let Err(errors) = xsd
{
for err in &errors {
println!("{}", err.message());
}

panic!("Failed to parse schema");
if let Err(errors) = xsd {
for err in &errors {
println!("{}", err.message());
}

let mut xsd = xsd.unwrap();
panic!("Failed to parse schema");
}

if let Err(errors) = xsd.validate_document(&xml)
{
for err in &errors {
println!("{}", err.message());
}
let mut xsd = xsd.unwrap();

panic!("Invalid XML accoding to XSD schema");
if let Err(errors) = xsd.validate_document(&xml) {
for err in &errors {
println!("{}", err.message());
}

panic!("Invalid XML accoding to XSD schema");
}
}
45 changes: 18 additions & 27 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,40 +5,31 @@ use super::bindings;

use std::ffi::CStr;


/// Wrapper around xmlErrorPtr
#[derive(Debug)]
pub struct StructuredError(*mut bindings::_xmlError);

impl StructuredError {
/// Wrap around and own a raw xmllib2 error structure
pub fn from_raw(error: *mut bindings::_xmlError) -> Self {
Self { 0: error }
}

impl StructuredError
{
/// Wrap around and own a raw xmllib2 error structure
pub fn from_raw(error: *mut bindings::_xmlError) -> Self
{
Self {0: error}
}

/// Human-readable informative error message
pub fn message(&self) -> &str
{
let msg = unsafe{ CStr::from_ptr((*self.0).message) };
/// Human-readable informative error message
pub fn message(&self) -> &str {
let msg = unsafe { CStr::from_ptr((*self.0).message) };

msg.to_str().unwrap()
}
msg.to_str().unwrap()
}

/// Return a raw pointer to the underlying xmlError structure
pub fn as_ptr(&self) -> *const bindings::_xmlError
{
self.0 // we loose the *mut since we own it
}
/// Return a raw pointer to the underlying xmlError structure
pub fn as_ptr(&self) -> *const bindings::_xmlError {
self.0 // we loose the *mut since we own it
}
}


impl Drop for StructuredError
{
fn drop(&mut self)
{
unsafe { bindings::xmlResetError(self.0) }
}
impl Drop for StructuredError {
fn drop(&mut self) {
unsafe { bindings::xmlResetError(self.0) }
}
}
28 changes: 11 additions & 17 deletions src/schemas/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,22 @@ use crate::bindings;

use crate::error::StructuredError;

use std::rc::Weak;
use std::ffi::c_void;
use std::cell::RefCell;

use std::ffi::c_void;
use std::rc::Weak;

/// Provides a callback to the C side of things to accumulate xmlErrors to be
/// handled back on the Rust side.
pub fn structured_error_handler(ctx: *mut c_void, error: bindings::xmlErrorPtr)
{
let errlog = unsafe {
Box::from_raw(ctx as *mut Weak<RefCell<Vec<StructuredError>>>)
};
pub fn structured_error_handler(ctx: *mut c_void, error: bindings::xmlErrorPtr) {
let errlog = unsafe { Box::from_raw(ctx as *mut Weak<RefCell<Vec<StructuredError>>>) };

let error = StructuredError::from_raw(error);
let error = StructuredError::from_raw(error);

if let Some(errors) = errlog.upgrade()
{
errors.borrow_mut()
.push(error);
} else {
panic!("Underlying error log should not have outlived callback registration");
}
if let Some(errors) = errlog.upgrade() {
errors.borrow_mut().push(error);
} else {
panic!("Underlying error log should not have outlived callback registration");
}

Box::leak(errlog);
Box::leak(errlog);
}
2 changes: 1 addition & 1 deletion src/schemas/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ mod parser;
mod schema;
mod validation;

use schema::Schema; // internally handled by SchemaValidationContext
use schema::Schema; // internally handled by SchemaValidationContext

pub use parser::SchemaParserContext;
pub use validation::SchemaValidationContext;
138 changes: 62 additions & 76 deletions src/schemas/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,108 +4,94 @@
use super::common;

use crate::bindings;
use crate::tree::document::Document;
use crate::error::StructuredError;
use crate::tree::document::Document;

use std::cell::RefCell;
use std::ffi::CString;
use std::os::raw::c_char;
use std::rc::Rc;
use std::ffi::CString;
use std::cell::RefCell;


/// Wrapper on xmlSchemaParserCtxt
pub struct SchemaParserContext
{
inner: *mut bindings::_xmlSchemaParserCtxt,
errlog: Rc<RefCell<Vec<StructuredError>>>,
pub struct SchemaParserContext {
inner: *mut bindings::_xmlSchemaParserCtxt,
errlog: Rc<RefCell<Vec<StructuredError>>>,
}

impl SchemaParserContext {
/// Create a schema parsing context from a Document object
pub fn from_document(doc: &Document) -> Self {
let parser = unsafe { bindings::xmlSchemaNewDocParserCtxt(doc.doc_ptr()) };

impl SchemaParserContext
{
/// Create a schema parsing context from a Document object
pub fn from_document(doc: &Document) -> Self
{
let parser = unsafe { bindings::xmlSchemaNewDocParserCtxt(doc.doc_ptr()) };

if parser.is_null() {
panic!("Failed to create schema parser context from XmlDocument"); // TODO error handling
}

Self::from_raw(parser)
if parser.is_null() {
panic!("Failed to create schema parser context from XmlDocument"); // TODO error handling
}

/// Create a schema parsing context from a buffer in memory
pub fn from_buffer<Bytes: AsRef<[u8]>>(buff: Bytes) -> Self
{
let buff_bytes = buff.as_ref();
let buff_ptr = buff_bytes.as_ptr() as *const c_char;
let buff_len = buff_bytes.len() as i32;
Self::from_raw(parser)
}

let parser = unsafe { bindings::xmlSchemaNewMemParserCtxt(buff_ptr, buff_len) };
/// Create a schema parsing context from a buffer in memory
pub fn from_buffer<Bytes: AsRef<[u8]>>(buff: Bytes) -> Self {
let buff_bytes = buff.as_ref();
let buff_ptr = buff_bytes.as_ptr() as *const c_char;
let buff_len = buff_bytes.len() as i32;

if parser.is_null() {
panic!("Failed to create schema parser context from buffer"); // TODO error handling
}
let parser = unsafe { bindings::xmlSchemaNewMemParserCtxt(buff_ptr, buff_len) };

Self::from_raw(parser)
if parser.is_null() {
panic!("Failed to create schema parser context from buffer"); // TODO error handling
}

/// Create a schema parsing context from an URL
pub fn from_file(path: &str) -> Self
{
let path = CString::new(path).unwrap(); // TODO error handling for \0 containing strings
let path_ptr = path.as_bytes_with_nul().as_ptr() as *const i8;
Self::from_raw(parser)
}

let parser = unsafe { bindings::xmlSchemaNewParserCtxt(path_ptr) };
/// Create a schema parsing context from an URL
pub fn from_file(path: &str) -> Self {
let path = CString::new(path).unwrap(); // TODO error handling for \0 containing strings
let path_ptr = path.as_bytes_with_nul().as_ptr() as *const i8;

if parser.is_null() {
panic!("Failed to create schema parser context from path"); // TODO error handling
}
let parser = unsafe { bindings::xmlSchemaNewParserCtxt(path_ptr) };

Self::from_raw(parser)
if parser.is_null() {
panic!("Failed to create schema parser context from path"); // TODO error handling
}

/// Drains error log from errors that might have accumulated while parsing schema
pub fn drain_errors(&mut self) -> Vec<StructuredError>
{
self.errlog.borrow_mut()
.drain(0..)
.collect()
}
Self::from_raw(parser)
}

/// Return a raw pointer to the underlying xmlSchemaParserCtxt structure
pub fn as_ptr(&self) -> *mut bindings::_xmlSchemaParserCtxt
{
self.inner
}
}
/// Drains error log from errors that might have accumulated while parsing schema
pub fn drain_errors(&mut self) -> Vec<StructuredError> {
self.errlog.borrow_mut().drain(0..).collect()
}

/// Return a raw pointer to the underlying xmlSchemaParserCtxt structure
pub fn as_ptr(&self) -> *mut bindings::_xmlSchemaParserCtxt {
self.inner
}
}

/// Private Interface
impl SchemaParserContext
{
fn from_raw(parser: *mut bindings::_xmlSchemaParserCtxt) -> Self
{
let errors = Rc::new(RefCell::new(Vec::new()));

unsafe {
bindings::xmlSchemaSetParserStructuredErrors(
parser,
Some(common::structured_error_handler),
Box::into_raw(Box::new(Rc::downgrade(&errors))) as *mut _
);
}

Self {inner: parser, errlog: errors}
impl SchemaParserContext {
fn from_raw(parser: *mut bindings::_xmlSchemaParserCtxt) -> Self {
let errors = Rc::new(RefCell::new(Vec::new()));

unsafe {
bindings::xmlSchemaSetParserStructuredErrors(
parser,
Some(common::structured_error_handler),
Box::into_raw(Box::new(Rc::downgrade(&errors))) as *mut _,
);
}
}


impl Drop for SchemaParserContext
{
fn drop(&mut self)
{
unsafe { bindings::xmlSchemaFreeParserCtxt(self.inner) }
Self {
inner: parser,
errlog: errors,
}
}
}

impl Drop for SchemaParserContext {
fn drop(&mut self) {
unsafe { bindings::xmlSchemaFreeParserCtxt(self.inner) }
}
}
42 changes: 17 additions & 25 deletions src/schemas/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,37 +7,29 @@ use crate::bindings;

use crate::error::StructuredError;


/// Wrapper on xmlSchema
pub struct Schema(*mut bindings::_xmlSchema);

impl Schema {
/// Create schema by having a SchemaParserContext do the actual parsing of the schema it was provided
pub fn from_parser(parser: &mut SchemaParserContext) -> Result<Self, Vec<StructuredError>> {
let raw = unsafe { bindings::xmlSchemaParse(parser.as_ptr()) };

impl Schema
{
/// Create schema by having a SchemaParserContext do the actual parsing of the schema it was provided
pub fn from_parser(parser: &mut SchemaParserContext) -> Result<Self, Vec<StructuredError>>
{
let raw = unsafe { bindings::xmlSchemaParse(parser.as_ptr()) };

if raw.is_null() {
Err(parser.drain_errors())
} else {
Ok(Self {0: raw})
}
if raw.is_null() {
Err(parser.drain_errors())
} else {
Ok(Self { 0: raw })
}
}

/// Return a raw pointer to the underlying xmlSchema structure
pub fn as_ptr(&self) -> *mut bindings::_xmlSchema
{
self.0
}
/// Return a raw pointer to the underlying xmlSchema structure
pub fn as_ptr(&self) -> *mut bindings::_xmlSchema {
self.0
}
}


impl Drop for Schema
{
fn drop(&mut self)
{
unsafe { bindings::xmlSchemaFree(self.0) }
}
impl Drop for Schema {
fn drop(&mut self) {
unsafe { bindings::xmlSchemaFree(self.0) }
}
}
Loading

0 comments on commit 27050bf

Please sign in to comment.