use std::ops::Bound;
use js::JsLifetime;
use js::class::Trace;
use js::function::Opt;
use surrealdb_types::ToSql;
use crate::val::{self, Value};
#[derive(Clone, Trace, JsLifetime)]
#[js::class]
pub(crate) struct Range {
#[qjs(skip_trace)]
pub(crate) value: val::Range,
}
fn bound_value(bound: &Bound<Value>) -> Value {
match bound {
Bound::Included(v) | Bound::Excluded(v) => v.clone(),
Bound::Unbounded => Value::None,
}
}
#[js::methods]
impl Range {
#[allow(clippy::needless_pass_by_value)]
#[qjs(constructor)]
pub fn new(
start: Value,
end: Value,
start_inclusive: Opt<bool>,
end_inclusive: Opt<bool>,
) -> Self {
let bound = |v: Value, inclusive: bool| {
if let Value::None = v {
Bound::Unbounded
} else if inclusive {
Bound::Included(v)
} else {
Bound::Excluded(v)
}
};
Self {
value: val::Range {
start: bound(start, start_inclusive.0.unwrap_or(true)),
end: bound(end, end_inclusive.0.unwrap_or(false)),
},
}
}
#[qjs(get)]
pub fn start(&self) -> Value {
bound_value(&self.value.start)
}
#[qjs(get)]
pub fn end(&self) -> Value {
bound_value(&self.value.end)
}
#[qjs(get, rename = "startInclusive")]
pub fn start_inclusive(&self) -> bool {
matches!(self.value.start, Bound::Included(_))
}
#[qjs(get, rename = "endInclusive")]
pub fn end_inclusive(&self) -> bool {
matches!(self.value.end, Bound::Included(_))
}
pub fn is(a: &Range, b: &Range) -> bool {
a.value == b.value
}
#[qjs(rename = "toString")]
pub fn js_to_string(&self) -> String {
self.value.to_sql()
}
#[qjs(rename = "toJSON")]
pub fn to_json(&self) -> String {
self.value.to_sql()
}
}