Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add Result for Encode trait #286

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
feat: reduce error handle
  • Loading branch information
darkskygit committed Mar 29, 2023
commit 451aa63077ebddac8842cacb95829bfd169d81ec
25 changes: 20 additions & 5 deletions yffi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -850,7 +850,10 @@ pub unsafe extern "C" fn ytransaction_state_vector_v1(

let txn = txn.as_ref().unwrap();
let state_vector = txn.state_vector();
let binary = state_vector.encode_v1().into_boxed_slice();
let binary = state_vector
.encode_v1()
.expect("failed to encode state vector using lib0 v1 encoding")
.into_boxed_slice();

*len = binary.len() as u32;
Box::into_raw(binary) as *mut c_char
Expand Down Expand Up @@ -894,7 +897,8 @@ pub unsafe extern "C" fn ytransaction_state_diff_v1(
};

let mut encoder = EncoderV1::new();
txn.encode_diff(&sv, &mut encoder);
txn.encode_diff(&sv, &mut encoder)
.expect("failed to encode transaction diff using lib0 v1 encoding");
let binary = encoder.to_vec().into_boxed_slice();
*len = binary.len() as u32;
Box::into_raw(binary) as *mut c_char
Expand Down Expand Up @@ -938,7 +942,8 @@ pub unsafe extern "C" fn ytransaction_state_diff_v2(
};

let mut encoder = EncoderV2::new();
txn.encode_diff(&sv, &mut encoder);
txn.encode_diff(&sv, &mut encoder)
.expect("failed to encode diff using lib0 v2 encoding");
let binary = encoder.to_vec().into_boxed_slice();
*len = binary.len() as u32;
Box::into_raw(binary) as *mut c_char
Expand All @@ -954,7 +959,11 @@ pub unsafe extern "C" fn ytransaction_snapshot(
) -> *mut c_char {
assert!(!txn.is_null());
let txn = txn.as_ref().unwrap();
let binary = txn.snapshot().encode_v1().into_boxed_slice();
let binary = txn
.snapshot()
.encode_v1()
.expect("failed to encode snapshot using lib0 v1 encoding")
.into_boxed_slice();

*len = binary.len() as u32;
Box::into_raw(binary) as *mut c_char
Expand Down Expand Up @@ -4949,7 +4958,13 @@ pub unsafe extern "C" fn ysticky_index_encode(
len: *mut u32,
) -> *mut c_char {
let pos = pos.as_ref().unwrap();
let binary = pos.0.encode_v1().into_boxed_slice();
let binary = pos
.0
.encode_v1()
.expect(
"YStickyIndex::encode_v1 failed. This is a bug, please report it to the developers.",
)
.into_boxed_slice();
*len = binary.len() as u32;
Box::into_raw(binary) as *mut c_char
}
Expand Down
12 changes: 6 additions & 6 deletions yrs/src/alt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ pub fn merge_updates_v1(updates: &[&[u8]]) -> Result<Vec<u8>, Error> {
let parsed = Update::decode_v1(buf)?;
merge.push(parsed);
}
Ok(Update::merge_updates(merge).encode_v1())
Ok(Update::merge_updates(merge).encode_v1()?)
}

/// Merges a sequence of updates (encoded using lib0 v2 encoding) together, producing another
Expand All @@ -33,7 +33,7 @@ pub fn merge_updates_v2(updates: &[&[u8]]) -> Result<Vec<u8>, Error> {
let update = Update::decode_v2(buf)?;
merge.push(update);
}
Ok(Update::merge_updates(merge).encode_v2())
Ok(Update::merge_updates(merge).encode_v2()?)
}

/// Decodes a input `update` (encoded using lib0 v1 encoding) and returns an encoded [StateVector]
Expand All @@ -42,7 +42,7 @@ pub fn merge_updates_v2(updates: &[&[u8]]) -> Result<Vec<u8>, Error> {
/// Returns an error whenever any of the input update couldn't be decoded.
pub fn encode_state_vector_from_update_v1(update: &[u8]) -> Result<Vec<u8>, Error> {
let update = Update::decode_v1(update)?;
Ok(update.state_vector().encode_v1())
Ok(update.state_vector().encode_v1()?)
}

/// Decodes a input `update` (encoded using lib0 v2 encoding) and returns an encoded [StateVector]
Expand All @@ -51,7 +51,7 @@ pub fn encode_state_vector_from_update_v1(update: &[u8]) -> Result<Vec<u8>, Erro
/// Returns an error whenever any of the input update couldn't be decoded.
pub fn encode_state_vector_from_update_v2(update: &[u8]) -> Result<Vec<u8>, Error> {
let update = Update::decode_v2(update)?;
Ok(update.state_vector().encode_v2())
Ok(update.state_vector().encode_v2()?)
}

/// Givens an input `update` (encoded using lib0 v1 encoding) of document **A** and an encoded
Expand All @@ -63,7 +63,7 @@ pub fn diff_updates_v1(update: &[u8], state_vector: &[u8]) -> Result<Vec<u8>, Er
let sv = StateVector::decode_v1(state_vector)?;
let update = Update::decode_v1(update)?;
let mut encoder = EncoderV1::new();
update.encode_diff(&sv, &mut encoder);
update.encode_diff(&sv, &mut encoder)?;
// for delete set, don't decode/encode it - just copy the remaining part from the decoder
let result = encoder.to_vec();
Ok(result)
Expand All @@ -80,7 +80,7 @@ pub fn diff_updates_v2(update: &[u8], state_vector: &[u8]) -> Result<Vec<u8>, Er
let mut decoder = DecoderV2::new(cursor)?;
let update = Update::decode(&mut decoder)?;
let mut encoder = EncoderV2::new();
update.encode_diff(&sv, &mut encoder);
update.encode_diff(&sv, &mut encoder)?;
// for delete set, don't decode/encode it - just copy the remaining part from the decoder
Ok(encoder.to_vec())
}
Expand Down
35 changes: 22 additions & 13 deletions yrs/src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ use std::collections::HashSet;
use std::convert::TryFrom;
use std::hash::Hash;
use std::ops::{Deref, DerefMut};
use std::panic;
use std::ptr::NonNull;
use std::rc::Rc;

Expand Down Expand Up @@ -836,7 +835,7 @@ impl BlockSlice {
&& id.clock <= myself.clock + self.end
}

pub fn encode<E: Encoder>(&self, encoder: &mut E, store: Option<&Store>) {
pub fn encode<E: Encoder>(&self, encoder: &mut E, store: Option<&Store>) -> Result<(), Error> {
match self.ptr.deref() {
Block::Item(item) => {
let mut info = item.info();
Expand Down Expand Up @@ -879,21 +878,22 @@ impl BlockSlice {
encoder.write_left_id(id);
}
TypePtr::Unknown => {
panic!("Couldn't get item's parent")
return Err(Error::Other("Couldn't get item's parent".into()));
}
}

if let Some(parent_sub) = item.parent_sub.as_ref() {
encoder.write_string(parent_sub.as_ref());
}
}
item.content.encode_slice(encoder, self.start, self.end);
item.content.encode_slice(encoder, self.start, self.end)?;
}
Block::GC(_) => {
encoder.write_info(BLOCK_GC_REF_NUMBER);
encoder.write_len(self.len());
}
}
Ok(())
}

/// Returns a [BlockSlice] wrapper for a [Block] identified as a right neighbor of this slice.
Expand Down Expand Up @@ -1002,7 +1002,7 @@ impl Block {
}
}

pub fn encode<E: Encoder>(&self, store: Option<&Store>, encoder: &mut E) {
pub fn encode<E: Encoder>(&self, store: Option<&Store>, encoder: &mut E) -> Result<(), Error> {
match self {
Block::Item(item) => {
let info = item.info();
Expand Down Expand Up @@ -1035,20 +1035,21 @@ impl Block {
encoder.write_left_id(id);
}
TypePtr::Unknown => {
panic!("Couldn't get item's parent")
return Err(Error::Other("Couldn't get item's parent".into()));
}
}
if let Some(parent_sub) = item.parent_sub.as_ref() {
encoder.write_string(parent_sub.as_ref());
}
}
item.content.encode(encoder);
item.content.encode(encoder)?;
}
Block::GC(gc) => {
encoder.write_info(BLOCK_GC_REF_NUMBER);
encoder.write_len(gc.len);
}
}
Ok(())
}

/// Returns a unique identifier of a first update contained by a current [Block].
Expand Down Expand Up @@ -1883,7 +1884,12 @@ impl ItemContent {

/// Encodes a slice of a current [ItemContent] within an index bounds of (start..=end) - both
/// sides inclusive.
pub fn encode_slice<E: Encoder>(&self, encoder: &mut E, start: u32, end: u32) {
pub fn encode_slice<E: Encoder>(
&self,
encoder: &mut E,
start: u32,
end: u32,
) -> Result<(), Error> {
match self {
ItemContent::Deleted(_) => encoder.write_len(end - start + 1),
ItemContent::Binary(buf) => encoder.write_buf(buf),
Expand Down Expand Up @@ -1928,12 +1934,14 @@ impl ItemContent {
encoder.write_any(&any[i as usize]);
}
}
ItemContent::Doc(_, doc) => doc.options().encode(encoder),
ItemContent::Move(m) => m.encode(encoder),
ItemContent::Doc(_, doc) => doc.options().encode(encoder)?,
ItemContent::Move(m) => m.encode(encoder)?,
}

Ok(())
}

pub fn encode<E: Encoder>(&self, encoder: &mut E) {
pub fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), Error> {
match self {
ItemContent::Deleted(len) => encoder.write_len(*len),
ItemContent::Binary(buf) => encoder.write_buf(buf),
Expand Down Expand Up @@ -1963,9 +1971,10 @@ impl ItemContent {
encoder.write_any(a);
}
}
ItemContent::Doc(_, doc) => doc.options().encode(encoder),
ItemContent::Move(m) => m.encode(encoder),
ItemContent::Doc(_, doc) => doc.options().encode(encoder)?,
ItemContent::Move(m) => m.encode(encoder)?,
}
Ok(())
}

pub fn decode<D: Decoder>(decoder: &mut D, ref_num: u8) -> Result<Self, Error> {
Expand Down
8 changes: 5 additions & 3 deletions yrs/src/block_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,12 +131,14 @@ impl Decode for StateVector {
}

impl Encode for StateVector {
fn encode<E: Encoder>(&self, encoder: &mut E) {
fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), Error> {
encoder.write_var(self.len());
for (&client, &clock) in self.iter() {
encoder.write_var(client);
encoder.write_var(clock);
}

Ok(())
}
}

Expand Down Expand Up @@ -165,8 +167,8 @@ impl Snapshot {
}

impl Encode for Snapshot {
fn encode<E: Encoder>(&self, encoder: &mut E) {
self.delete_set.encode(encoder);
fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), Error> {
self.delete_set.encode(encoder)?;
self.state_map.encode(encoder)
}
}
Expand Down
10 changes: 6 additions & 4 deletions yrs/src/compatibility_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ fn state_vector() {
let sv = StateVector::decode_v1(payload).unwrap();
assert_eq!(sv, expected);

let serialized = sv.encode_v1();
let serialized = sv.encode_v1().unwrap();
assert_eq!(serialized.as_slice(), payload);
}

Expand Down Expand Up @@ -363,7 +363,7 @@ fn roundtrip_v1(payload: &[u8], expected: &Vec<BlockCarrier>) {
assert_eq!(blocks, expected, "failed to decode V1");

let store: Store = u.into();
let serialized = store.encode_v1();
let serialized = store.encode_v1().unwrap();
assert_eq!(serialized, payload, "failed to encode V1");
}

Expand All @@ -375,7 +375,7 @@ fn roundtrip_v2(payload: &[u8], expected: &Vec<BlockCarrier>) {
assert_eq!(blocks, expected, "failed to decode V2");

let store: Store = u.into();
let serialized = store.encode_v2();
let serialized = store.encode_v2().unwrap();
assert_eq!(serialized, payload, "failed to encode V2");
}

Expand All @@ -400,7 +400,9 @@ fn negative_zero_decoding_v2() {
root.insert(&mut txn, "characters", ArrayPrelim::<_, Any>::from([]));
let expected = root.to_json(&txn);

let buffer = txn.encode_state_as_update_v2(&StateVector::default());
let buffer = txn
.encode_state_as_update_v2(&StateVector::default())
.unwrap();

let u = Update::decode_v2(&buffer).unwrap();

Expand Down
Loading