1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::hash::BuildHasher;
/// A dynamic data type that the solver can reason on.
#[derive(Clone)]
pub enum Value<'a> {
/// Represents an empty type.
Null,
/// Represents a boolean.
Bool(bool),
/// Represents a float.
Float(f64),
/// Represents an integer.
Int(i64),
/// Represents an unsigned integer.
UInt(u64),
/// Represents a string.
String(Cow<'a, str>),
/// Represents an array.
Array(&'a dyn Array),
/// Represents an object.
Object(&'a dyn Object),
}
impl<'a> Value<'a> {
/// Returns true if the `Value` is an Array.
#[inline]
pub fn is_array(&self) -> bool {
matches!(self, Self::Array(_))
}
/// Returns true if the `Value` is a Bool.
#[inline]
pub fn is_bool(&self) -> bool {
matches!(self, Self::Bool(_))
}
/// Returns true if the `Value` is a Float.
#[inline]
pub fn is_f64(&self) -> bool {
matches!(self, Self::Float(_))
}
/// Returns true if the `Value` is an Int.
#[inline]
pub fn is_i64(&self) -> bool {
matches!(self, Self::Int(_))
}
/// Returns true if the `Value` is a Null.
#[inline]
pub fn is_null(&self) -> bool {
matches!(self, Self::Null)
}
/// Returns true if the `Value` is an Object.
#[inline]
pub fn is_object(&self) -> bool {
matches!(self, Self::Object(_))
}
/// Returns true if the `Value` is a String.
#[inline]
pub fn is_string(&self) -> bool {
matches!(self, Self::String(_))
}
/// Returns true if the `Value` is a UInt.
#[inline]
pub fn is_u64(&self) -> bool {
matches!(self, Self::UInt(_))
}
/// Return the associated array if the `Value` is an Array.
#[inline]
pub fn as_array(&self) -> Option<&dyn Array> {
match self {
Self::Array(a) => Some(*a),
_ => None,
}
}
/// Return the associated boolean if the `Value` is a Bool.
#[inline]
pub fn as_bool(&self) -> Option<bool> {
match self {
Self::Bool(b) => Some(*b),
_ => None,
}
}
/// Return the associated f64 if the `Value` is a Float.
#[inline]
pub fn as_f64(&self) -> Option<f64> {
match self {
Self::Float(n) => Some(*n),
_ => None,
}
}
/// Return the associated i64 if the `Value` is a Int.
#[inline]
pub fn as_i64(&self) -> Option<i64> {
match self {
Self::Int(n) => Some(*n),
_ => None,
}
}
/// Return the associated () if the `Value` is a Null.
#[inline]
pub fn as_null(&self) -> Option<()> {
match self {
Self::Null => Some(()),
_ => None,
}
}
/// Return the associated object if the `Value` is an Object.
#[inline]
pub fn as_object(&self) -> Option<&dyn Object> {
match self {
Self::Object(o) => Some(*o),
_ => None,
}
}
/// Return the associated str if the `Value` is a String.
#[inline]
pub fn as_str(&self) -> Option<&str> {
match self {
Self::String(s) => Some(s),
_ => None,
}
}
/// Return the associated u64 if the `Value` is a UInt.
#[inline]
pub fn as_u64(&self) -> Option<u64> {
match self {
Self::UInt(n) => Some(*n),
_ => None,
}
}
/// Returns the `Value` as an i64 if possible.
///
/// Currently supports: Int & UInt.
#[inline]
pub fn to_i64(&self) -> Option<i64> {
match self {
Self::Int(n) => Some(*n),
Self::UInt(n) => {
if *n <= i64::MAX as u64 {
Some(*n as i64)
} else {
None
}
}
_ => None,
}
}
/// Returns the `Value` as a String if possible.
///
/// Currently supports: Bool, Float, Int, String & UInt.
#[inline]
pub fn to_string(&self) -> Option<String> {
match self {
Self::Bool(b) => Some(b.to_string()),
Self::Int(i) => Some(i.to_string()),
Self::UInt(u) => Some(u.to_string()),
Self::Float(f) => Some(f.to_string()),
Self::String(s) => Some(s.to_string()),
_ => None,
}
}
}
/// A **data type** that can be represented as a `Value`.
///
/// # Implementations
///
/// As long as the **data type** can be coerced into one of the values provided by `Value` then
/// `AsValue` can be implemented on that type. Below is a contrived example:
///
/// ```
/// use std::borrow::Cow;
///
/// use tau_engine::{AsValue, Value};
///
/// enum Foo {
/// Bar,
/// Baz
/// }
///
/// impl AsValue for Foo {
/// fn as_value(&self) -> Value<'_> {
/// match self {
/// Self::Bar => Value::String(Cow::Borrowed("bar")),
/// Self::Baz => Value::String(Cow::Borrowed("baz")),
/// }
/// }
/// }
/// ```
#[cfg(not(feature = "sync"))]
pub trait AsValue {
/// Returns the implemented type as a `Value`
///
/// # Example
///
/// ```
/// use tau_engine::AsValue;
///
/// let value = "foobar".as_value();
/// ```
fn as_value(&self) -> Value<'_>;
}
#[cfg(feature = "sync")]
pub trait AsValue: Send + Sync {
fn as_value(&self) -> Value<'_>;
}
impl AsValue for () {
#[inline]
fn as_value(&self) -> Value<'_> {
Value::Null
}
}
impl AsValue for bool {
#[inline]
fn as_value(&self) -> Value<'_> {
Value::Bool(*self)
}
}
impl AsValue for str {
#[inline]
fn as_value(&self) -> Value<'_> {
Value::String(Cow::Borrowed(self))
}
}
impl AsValue for String {
#[inline]
fn as_value(&self) -> Value<'_> {
Value::String(Cow::Borrowed(self))
}
}
impl<V> AsValue for HashSet<V>
where
V: AsValue,
{
#[inline]
fn as_value(&self) -> Value<'_> {
Value::Array(self)
}
}
impl<V> AsValue for Option<V>
where
V: AsValue,
{
#[inline]
fn as_value(&self) -> Value<'_> {
self.as_ref().map(|v| v.as_value()).unwrap_or(Value::Null)
}
}
impl<V> AsValue for Vec<V>
where
V: AsValue,
{
#[inline]
fn as_value(&self) -> Value<'_> {
Value::Array(self)
}
}
macro_rules! impl_as_value_float {
($ty:ty) => {
impl AsValue for $ty {
#[inline]
fn as_value(&self) -> Value<'_> {
Value::Float(*self as f64)
}
}
};
}
impl_as_value_float!(f32);
impl_as_value_float!(f64);
macro_rules! impl_as_value_int {
($ty:ty) => {
impl AsValue for $ty {
#[inline]
fn as_value(&self) -> Value<'_> {
Value::Int(*self as i64)
}
}
};
}
impl_as_value_int!(i8);
impl_as_value_int!(i16);
impl_as_value_int!(i32);
impl_as_value_int!(i64);
impl_as_value_int!(isize);
macro_rules! impl_as_value_uint {
($ty:ty) => {
impl AsValue for $ty {
#[inline]
fn as_value(&self) -> Value<'_> {
Value::UInt(*self as u64)
}
}
};
}
impl_as_value_uint!(u8);
impl_as_value_uint!(u16);
impl_as_value_uint!(u32);
impl_as_value_uint!(u64);
impl_as_value_uint!(usize);
/// A **data type** that can be represented as an `Array`.
///
/// This allows more complex array-like data types to be represented in a generic way for use as a
/// `Value`.
///
/// # Implementations
///
/// As long as the **data type** is considered array-like then `Array` can be implemented on that
/// type. Below is a contrived example:
///
/// ```
/// use tau_engine::{Array, Value};
///
/// // NOTE: Implements Iterator
/// #[derive(Clone)]
/// struct Counter {
/// count: usize,
/// }
/// # impl Iterator for Counter {
/// # // we will be counting with usize
/// # type Item = usize;
///
/// # // next() is the only required method
/// # fn next(&mut self) -> Option<Self::Item> {
/// # // Increment our count. This is why we started at zero.
/// # self.count += 1;
///
/// # // Check to see if we've finished counting or not.
/// # if self.count < 6 {
/// # Some(self.count)
/// # } else {
/// # None
/// # }
/// # }
/// # }
/// impl Array for Counter {
/// fn iter(&self) -> Box<dyn Iterator<Item = Value<'_>> + '_> {
/// Box::new(self.clone().map(|v| Value::UInt(v as u64)))
/// }
///
/// fn len(&self) -> usize {
/// self.clone().count()
/// }
/// }
/// ```
#[allow(clippy::len_without_is_empty)]
#[cfg(not(feature = "sync"))]
pub trait Array {
/// Returns a boxed iterator of `Value` items.
///
/// # Example
///
/// ```
/// use std::collections::HashSet;
/// use tau_engine::{Array, Value};
///
/// let mut set = HashSet::new();
/// set.insert(1);
///
/// let mut value = Array::iter(&set);
///
/// assert_eq!(value.next().is_some(), true);
/// ```
fn iter(&self) -> Box<dyn Iterator<Item = Value<'_>> + '_>;
/// Returns the length of the array.
///
/// # Example
///
///```
/// use std::collections::HashSet;
/// use tau_engine::{Array, Value};
///
/// let mut set = HashSet::new();
/// set.insert(1);
///
/// let len = Array::len(&set);
///
/// assert_eq!(len, 1);
/// ```
fn len(&self) -> usize;
}
#[cfg(feature = "sync")]
pub trait Array: Send + Sync {
fn iter(&self) -> Box<dyn Iterator<Item = Value<'_>> + '_>;
fn len(&self) -> usize;
}
impl<V> Array for HashSet<V>
where
V: AsValue,
{
#[inline]
fn iter(&self) -> Box<dyn Iterator<Item = Value<'_>> + '_> {
Box::new(self.iter().map(|v| v.as_value()))
}
#[inline]
fn len(&self) -> usize {
self.len()
}
}
impl<V> Array for Vec<V>
where
V: AsValue,
{
#[inline]
fn iter(&self) -> Box<dyn Iterator<Item = Value<'_>> + '_> {
Box::new(self.as_slice().iter().map(|v| v.as_value()))
}
#[inline]
fn len(&self) -> usize {
self.len()
}
}
/// A **data type** that can be represented as an `Object`.
///
/// This allows more complex object-like data types to be represented in a generic way for use as a
/// `Value`.
///
/// # Implementations
///
/// As long as the **data type** is considered object-like then `Object` can be implemented on that
/// type. Below is a contrived example:
///j
/// ```
/// use std::borrow::Cow;
///
/// use tau_engine::{Object, Value};
///
/// struct Foo {
/// pub bar: String,
/// pub baz: String,
/// }
///
/// impl Object for Foo {
/// fn get(&self, key: &str) -> Option<Value<'_>> {
/// match key {
/// "bar" => Some(Value::String(Cow::Borrowed(&self.bar))),
/// "baz" => Some(Value::String(Cow::Borrowed(&self.baz))),
/// _ => None,
/// }
/// }
///
/// fn keys(&self) -> Vec<Cow<'_, str>> {
/// ["bar", "baz"].iter().map(|s| Cow::Borrowed(*s)).collect()
/// }
///
/// fn len(&self) -> usize {
/// 2
/// }
/// }
/// ```
///
/// # Find
///
/// The `find` function allows for nested access from an `Object`. A default implementation is
/// provided by the trait which assumes the key will split on the `.` character. This can be overriden if
/// required. Below is an example of how find works for a complex data structure.
///
/// ```
/// # use std::borrow::Cow;
/// # use tau_engine::Value;
/// use tau_engine::Object;
///
/// struct Foo {
/// pub bar: String,
/// }
/// # impl Object for Foo {
/// # fn get(&self, key: &str) -> Option<Value<'_>> {
/// # match key {
/// # "bar" => Some(Value::String(Cow::Borrowed(&self.bar))),
/// # _ => None,
/// # }
/// # }
/// #
/// # fn keys(&self) -> Vec<Cow<'_, str>> {
/// # ["bar"].iter().map(|s| Cow::Borrowed(*s)).collect()
/// # }
/// #
/// # fn len(&self) -> usize {
/// # 1
/// # }
/// # }
/// struct Baz {
/// pub foo: Foo,
/// }
/// # impl Object for Baz {
/// # fn get(&self, key: &str) -> Option<Value<'_>> {
/// # match key {
/// # "foo" => Some(Value::Object(&self.foo)),
/// # _ => None,
/// # }
/// # }
/// #
/// # fn keys(&self) -> Vec<Cow<'_, str>> {
/// # ["foo"].iter().map(|s| Cow::Borrowed(*s)).collect()
/// # }
/// #
/// # fn len(&self) -> usize {
/// # 1
/// # }
/// # }
/// let complex = Baz {
/// foo: Foo {
/// bar: "foobar".to_owned(),
/// }
/// };
///
/// let value = complex.find("foo.bar").unwrap();
///
/// assert_eq!(value.as_str(), Some("foobar"));
/// ```
#[allow(clippy::len_without_is_empty)]
#[cfg(not(feature = "sync"))]
pub trait Object {
/// Looks for a `Value` by key and returns it if found. The provided implementation will split
/// the key on `.` to handle nesting.
fn find(&self, key: &str) -> Option<Value<'_>> {
let mut v: Option<Value<'_>> = None;
for k in key.split('.') {
if k.ends_with(']') && k.contains('[') {
let mut parts = k.split('[');
let k = parts.next().expect("missing key");
let i: usize = match parts
.next()
.and_then(|i| i.strip_suffix("]"))
.and_then(|i| i.parse::<usize>().ok())
{
Some(i) => i,
None => return None,
};
match v {
Some(Value::Object(value)) => match value.get(k) {
Some(Value::Array(a)) => v = a.iter().nth(i),
_ => return None,
},
Some(_) => return None,
None => match <Self as Object>::get(self, k) {
Some(Value::Array(a)) => v = a.iter().nth(i),
_ => return None,
},
}
} else {
match v {
Some(Value::Object(value)) => v = value.get(k),
Some(_) => return None,
None => match <Self as Object>::get(self, k) {
Some(value) => v = Some(value),
None => return None,
},
}
}
}
v
}
/// Get the `Value` corresponding to the key.
fn get(&self, key: &str) -> Option<Value<'_>>;
/// Returns the keys for the object.
fn keys(&self) -> Vec<Cow<'_, str>>;
/// Returns the number of elements in the object.
fn len(&self) -> usize;
}
#[cfg(feature = "sync")]
pub trait Object: Send + Sync {
fn find(&self, key: &str) -> Option<Value<'_>> {
let mut v: Option<Value<'_>> = None;
for k in key.split('.') {
if k.ends_with(']') && k.contains('[') {
let mut parts = k.split('[');
let k = parts.next().expect("missing key");
let i: usize = match parts
.next()
.and_then(|i| i.strip_suffix("]"))
.and_then(|i| i.parse::<usize>().ok())
{
Some(i) => i,
None => return None,
};
match v {
Some(Value::Object(value)) => match value.get(k) {
Some(Value::Array(a)) => v = a.iter().nth(i),
_ => return None,
},
Some(_) => return None,
None => match <Self as Object>::get(self, k) {
Some(Value::Array(a)) => v = a.iter().nth(i),
_ => return None,
},
}
} else {
match v {
Some(Value::Object(value)) => v = value.get(k),
Some(_) => return None,
None => match <Self as Object>::get(self, k) {
Some(value) => v = Some(value),
None => return None,
},
}
}
}
v
}
fn get(&self, key: &str) -> Option<Value<'_>>;
fn keys(&self) -> Vec<Cow<'_, str>>;
fn len(&self) -> usize;
}
#[cfg(not(feature = "sync"))]
impl<V, S> Object for HashMap<String, V, S>
where
V: AsValue,
S: BuildHasher,
{
#[inline]
fn get(&self, key: &str) -> Option<Value<'_>> {
self.get(key).map(|v| v.as_value())
}
#[inline]
fn keys(&self) -> Vec<Cow<'_, str>> {
self.keys().map(|s| Cow::Borrowed(s.as_str())).collect()
}
#[inline]
fn len(&self) -> usize {
self.len()
}
}
#[cfg(feature = "sync")]
impl<V, S> Object for HashMap<String, V, S>
where
V: AsValue,
S: BuildHasher + Send + Sync,
{
#[inline]
fn get(&self, key: &str) -> Option<Value<'_>> {
self.get(key).map(|v| v.as_value())
}
#[inline]
fn keys(&self) -> Vec<Cow<'_, str>> {
self.keys().map(|s| Cow::Borrowed(s.as_str())).collect()
}
#[inline]
fn len(&self) -> usize {
self.len()
}
}
impl<O: Object> AsValue for O {
#[inline]
fn as_value(&self) -> Value<'_> {
Value::Object(self)
}
}