macroconf/tests/get_set.rs

66 lines
1.4 KiB
Rust

use std::{cell::Cell, str::from_utf8};
use macroconf::config;
use miniconf::JsonCoreSlash;
fn set_cell<const MIN: i32, const MAX: i32>(
cell: &Cell<i32>,
val: i32,
) -> Result<(), &'static str> {
if (MIN..=MAX).contains(&val) {
cell.set(val);
Ok(())
} else {
Err("value out of bounds")
}
}
#[config]
struct Config {
#[config(
min = "-128",
max = "128",
default,
typ = "i32",
get = "Cell::get",
set = "set_cell::<-128,128>"
)]
field: Cell<i32>,
}
#[config]
struct WithSetterAndDefault {
#[config(
default = "42",
typ = "i32",
get = "Cell::get",
set = "set_cell::<{i32::MIN}, {i32::MAX}>"
)]
field: Cell<i32>,
}
#[test]
fn get() {
let mut buffer = [0u8; 32];
let config = Config {
field: __ConfigField::new(Cell::new(42)),
};
let len = config.get_json("/field", &mut buffer).unwrap();
assert_eq!(from_utf8(&buffer[..len]), Ok("42"));
}
#[test]
fn set() {
let mut config = Config {
field: __ConfigField::new(Cell::new(42)),
};
config.set_json("/field", b"-32").unwrap();
assert_eq!(config.field.get(), -32);
config
.set_json("/field", b"256")
.expect_err("result not checked");
config
.set_json("/field", b"-256")
.expect_err("result not checked");
}