#error #serde-json #serde #json-error #error-value #result #json-format

cdumay_result

A library to serialize and deserialize result using serde

5 releases (3 stable)

new 1.0.3 Feb 11, 2025
1.0.2 Feb 7, 2025
0.3.0 Jul 5, 2024
0.2.0 Jun 21, 2024

#457 in Encoding

Download history 9/week @ 2024-11-03 1/week @ 2024-11-10 3/week @ 2024-11-17 1/week @ 2024-11-24 6/week @ 2024-12-08 1/week @ 2024-12-15 219/week @ 2025-02-02 130/week @ 2025-02-09

349 downloads per month
Used in 2 crates (via cdumay_http_client)

BSD-3-Clause

26KB
222 lines

cdumay_result

License: BSD-3-Clause cdumay_result on crates.io cdumay_result on docs.rs Source Code Repository

A Rust library for standardizing operation results and their serialization using serde. This crate provides a flexible and consistent way to handle operation results, including success and error cases, with support for structured data, stdout/stderr outputs, and serialization.

Features

  • Structured result type with support for return values and output streams
  • UUID generation for result tracking
  • Integration with error handling systems
  • Builder pattern for easy result construction

Installation

Add this to your Cargo.toml:

[dependencies]
cdumay_result = "1.0"
serde_json = "1.0"  # For JSON serialization
cdumay_error = "1.0"  # For error handling
cdumay_error_standard = "1.0"  # For error example
cdumay_context = "1.1" # For context use

Basic Usage

Here's a simple example of creating and using a successful result:

use cdumay_result::{ResultBuilder, Result};
use std::collections::BTreeMap;
use serde_value::Value;

// Creating a successful result with data
let result = ResultBuilder::default()
    .stdout("Operation completed successfully".into())
    .retval({
        let mut values = BTreeMap::new();
        values.insert("status".into(), Value::String("completed".into()));
        values.insert("count".into(), Value::U8(42.into()));
        values
    })
    .build();

// Serialize to JSON
println!("{}", serde_json::to_string_pretty(&result).unwrap());

Context Usage

Here's a simple example of creating and using a successful result using cdumay_context:

use cdumay_result::{ResultBuilder, Result};
use cdumay_context::Context;
use std::collections::BTreeMap;
use serde::Serialize;
use serde_value::Value;

#[derive(Default, Serialize)]
struct MyContext {
    data: BTreeMap<String, Value>
}

impl Context for MyContext {
    fn new() -> Self {
        Self::default()
    }

    fn insert(&mut self, k: String, v: Value) {
        self.data.insert(k, v);
    }

    fn get(&self, k: &str) -> Option<&Value> {
        self.data.get(k)
    }

    fn extend(&mut self, data: BTreeMap<String, Value>) {
        self.data.extend(data);
    }

    fn inner(&self) -> BTreeMap<String, Value> {
        self.data.clone()
    }
}

// Creating a context
let mut context = MyContext::new();
context.insert("status".into(), Value::String("completed".into()));
context.insert("count".into(), Value::U8(42.into()));

// Creating a successful result with data
let result = ResultBuilder::default()
    .stdout("Operation completed successfully".into())
    .retval(context.inner())
    .build();

// Serialize to JSON
println!("{}", serde_json::to_string_pretty(&result).unwrap());

Error Handling

Example using error handling with cdumay_error_standard:

use cdumay_result::Result;
use cdumay_error_standard::Unexpected;
use cdumay_error::{AsError, Error};
use serde_value::Value;

fn process_data() -> Result {
    // Simulate an error condition
    let error = Unexpected::new()
        .set_message("Failed to process data".into())
        .set_details({
            let mut details = std::collections::BTreeMap::new();
            details.insert(
                "error_type".into(),
                Value::String("processing_error".into())
            );
            details
        });

    // Convert error into Result
    Result::from(Error::from(error))
}

Custom Result Builder

Example of using the builder pattern with custom data:

use cdumay_result::ResultBuilder;
use std::collections::BTreeMap;
use std::fmt::format;
use serde_value::Value;
use uuid::Uuid;

// Create a custom result with specific UUID
let result = ResultBuilder::default()
    .uuid( Uuid::parse_str("da1c7a76-33a8-448e-9ada-3a1b17c12279").unwrap())
    .stdout("Custom operation result".into())
    .retval({
        let mut data = BTreeMap::new();
        data.insert("custom_field".into(), Value::String("custom_value".into()));
        data
    })
    .build();

assert_eq!(format!("{}", result.uuid), "da1c7a76-33a8-448e-9ada-3a1b17c12279".to_string());

JSON Output Format

The JSON output format for successful results looks like this:

{
  "uuid": "550e8400-e29b-41d4-a716-446655440000",
  "retcode": 0,
  "stdout": "Operation completed successfully",
  "stderr": null,
  "retval": {
    "status": "completed",
    "count": 42
  }
}

For error results:

{
  "uuid": "550e8400-e29b-41d4-a716-446655440000",
  "retcode": 1,
  "stdout": null,
  "stderr": "Failed to process data",
  "retval": {
    "error_type": "processing_error"
  }
}

License: BSD-3-Clause

Dependencies

~0.8–1.4MB
~31K SLoC