use crate::core::util::CoreHelper;
use crate::core::util::SliceCopyOps;
use crate::core::util::access::{SharedAccessVec, WritableVec};
use crate::core::util::array_util::ArrayUtil;
use crate::core::util::error::lucene_error::Result;
use crate::core::util::ints_ref::IntsRef;
#[derive(Debug)]
pub struct IntsRefBuilder<AV> {
ints_ref: IntsRef<AV>,
}
impl<AV> Clone for IntsRefBuilder<AV>
where
AV: Clone,
{
fn clone(&self) -> Self {
Self {
ints_ref: self.ints_ref.clone(),
}
}
}
impl<AV> Default for IntsRefBuilder<AV>
where
AV: WritableVec<i32>,
{
fn default() -> Self {
Self::new()
}
}
impl<AV> IntsRefBuilder<AV>
where
AV: SharedAccessVec<i32>,
{
pub fn new() -> Self
where
AV: WritableVec<i32>,
{
Self {
ints_ref: IntsRef::default(),
}
}
pub fn ints(&mut self) -> &mut AV {
&mut self.ints_ref.ints
}
pub fn length(&self) -> usize {
self.ints_ref.length
}
pub fn set_length(&mut self, length: usize) {
self.ints_ref.length = length;
}
pub fn clear(&mut self) {
self.set_length(0);
}
pub fn int_at(&self, offset: usize) -> i32 {
self.ints_ref.ints.access(|ints_bytes| ints_bytes[offset])
}
pub fn set_int_at(&mut self, offset: usize, value: i32)
where
AV: WritableVec<i32>,
{
self.ints_ref.ints.access_mut(|ints_bytes| {
ints_bytes[offset] = value;
})
}
pub fn append(&mut self, i: i32) -> Result<()>
where
AV: WritableVec<i32>,
{
let mut len = self.ints_ref.length;
self.grow(len + 1)?;
len = self.ints_ref.length;
self.ints_ref.ints.access_mut(|ints_bytes| {
ints_bytes[len] = i;
});
self.ints_ref.length += 1;
Ok(())
}
pub fn grow(&mut self, new_length: usize) -> Result<()>
where
AV: WritableVec<i32>,
{
self
.ints_ref
.ints
.access_mut(|ints_bytes| ArrayUtil::grow_with(ints_bytes, new_length, || 0))
}
pub fn grow_no_copy(&mut self, new_length: usize) -> Result<()>
where
AV: WritableVec<i32>,
{
self
.ints_ref
.ints
.access_mut(|ints_bytes| ArrayUtil::grow_no_copy(ints_bytes, new_length, || 0))
}
pub fn copy_ints(&mut self, other: &[i32], other_offset: usize, other_length: usize) -> Result<()>
where
AV: WritableVec<i32>,
{
self.ints_ref.ints.access_mut(|ints_bytes| {
ArrayUtil::grow_no_copy(ints_bytes, other_length, || 0)?;
CoreHelper::check_from_index_size(other_offset, other_length, other.len())?;
ints_bytes.copy_from(&other[other_offset..(other_offset + other_length)], 0);
self.ints_ref.length = other_length;
Ok(())
})
}
pub fn copy_ints_ref(&mut self, ints: &IntsRef<AV>) -> Result<()>
where
AV: WritableVec<i32>,
{
ints
.ints
.access(|ints_bytes| self.copy_ints(ints_bytes, ints.offset, ints.length))
}
pub fn get(&self) -> &IntsRef<AV> {
debug_assert_eq!(
self.ints_ref.offset, 0,
"Modifying the offset of the returned ref is illegal"
);
&self.ints_ref
}
pub fn get_owner(&mut self) -> IntsRef<AV>
where
AV: WritableVec<i32>,
{
std::mem::take(&mut self.ints_ref)
}
pub fn to_ints_ref(&self) -> IntsRef<AV> {
IntsRef::deep_copy_of(&self.ints_ref)
}
}