Skip to content

Commit

Permalink
replace ok_or by ok_or_else for lazy evaluation
Browse files Browse the repository at this point in the history
  • Loading branch information
BingqingLyu committed Nov 14, 2023
1 parent de7182b commit b5f389b
Show file tree
Hide file tree
Showing 36 changed files with 381 additions and 360 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -43,28 +43,28 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let config_map: HashMap<_, _> = parsed.into_iter().collect();
let rpc_port: u16 = config_map
.get("rpc.port")
.ok_or(StartServerError::empty_config_error("rpc.port"))?
.ok_or_else(|| StartServerError::empty_config_error("rpc.port"))?
.parse()?;
let server_id: u64 = config_map
.get("server.id")
.ok_or(StartServerError::empty_config_error("server.id"))?
.ok_or_else(|| StartServerError::empty_config_error("server.id"))?
.parse()?;
let server_size: usize = config_map
.get("server.size")
.ok_or(StartServerError::empty_config_error("server.size"))?
.ok_or_else(|| StartServerError::empty_config_error("server.size"))?
.parse()?;
let hosts: Vec<&str> = config_map
.get("network.servers")
.ok_or(StartServerError::empty_config_error("network.servers"))?
.ok_or_else(|| StartServerError::empty_config_error("network.servers"))?
.split(",")
.collect();
let worker_thread_num: i32 = config_map
.get("pegasus.worker.num")
.ok_or(StartServerError::empty_config_error("pegasus.worker.num"))?
.ok_or_else(|| StartServerError::empty_config_error("pegasus.worker.num"))?
.parse()?;
let vineyard_graph_id: i64 = config_map
.get("graph.vineyard.object.id")
.ok_or(StartServerError::empty_config_error("graph.vineyard.object.id"))?
.ok_or_else(|| StartServerError::empty_config_error("graph.vineyard.object.id"))?
.parse()?;

assert_eq!(server_size, hosts.len());
Expand Down
8 changes: 4 additions & 4 deletions interactive_engine/executor/common/dyn_type/src/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,7 @@ impl DateTimeFormats {
pub fn from_date32(date32: i32) -> Result<Self, CastError> {
NaiveDate::from_ymd_opt(date32 / 10000, ((date32 % 10000) / 100) as u32, (date32 % 100) as u32)
.map(|d| DateTimeFormats::Date(d))
.ok_or(CastError::new::<DateTimeFormats>(RawType::Integer))
.ok_or_else(|| CastError::new::<DateTimeFormats>(RawType::Integer))
}

// the time32 is stored HHMMSSsss, e.g., 121314100
Expand All @@ -453,13 +453,13 @@ impl DateTimeFormats {
(time32 % 1000) as u32,
)
.map(|t| DateTimeFormats::Time(t))
.ok_or(CastError::new::<DateTimeFormats>(RawType::Integer))
.ok_or_else(|| CastError::new::<DateTimeFormats>(RawType::Integer))
}

pub fn from_timestamp_millis(timestamp: i64) -> Result<Self, CastError> {
NaiveDateTime::from_timestamp_millis(timestamp)
.map(|dt| DateTimeFormats::DateTime(dt))
.ok_or(CastError::new::<DateTimeFormats>(RawType::Long))
.ok_or_else(|| CastError::new::<DateTimeFormats>(RawType::Long))
}

// we pre-assume some date/time/datetime formats according to ISO formats.
Expand Down Expand Up @@ -522,7 +522,7 @@ impl DateTimeFormats {
DateTimeFormats::DateTime(dt) => dt
.and_local_timezone(FixedOffset::east_opt(0).unwrap())
.single()
.ok_or(CastError::new::<NaiveDateTime>(RawType::DateTimeWithTz)),
.ok_or_else(|| CastError::new::<NaiveDateTime>(RawType::DateTimeWithTz)),
DateTimeFormats::DateTimeWithTz(dt) => Ok(*dt),
}
}
Expand Down
73 changes: 44 additions & 29 deletions interactive_engine/executor/common/dyn_type/src/serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,12 +133,13 @@ impl Decode for DateTimeFormats {
let year = <i16>::read_from(reader)?;
let month = <u8>::read_from(reader)?;
let day = <u8>::read_from(reader)?;
let date = chrono::NaiveDate::from_ymd_opt(year as i32, month as u32, day as u32).ok_or(
io::Error::new(
io::ErrorKind::Other,
format!("invalid date {:?}-{:?}-{:?}", year, month, day),
),
)?;
let date = chrono::NaiveDate::from_ymd_opt(year as i32, month as u32, day as u32)
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::Other,
format!("invalid date {:?}-{:?}-{:?}", year, month, day),
)
})?;
Ok(DateTimeFormats::Date(date))
}
1 => {
Expand All @@ -148,41 +149,55 @@ impl Decode for DateTimeFormats {
let nano = <u32>::read_from(reader)?;
let time =
chrono::NaiveTime::from_hms_nano_opt(hour as u32, minute as u32, second as u32, nano)
.ok_or(io::Error::new(
io::ErrorKind::Other,
format!("invalid time {:?}:{:?}:{:?}.{:?}", hour, minute, second, nano / 1000_000),
))?;
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::Other,
format!(
"invalid time {:?}:{:?}:{:?}.{:?}",
hour,
minute,
second,
nano / 1000_000
),
)
})?;
Ok(DateTimeFormats::Time(time))
}
2 => {
let timestamp_millis = <i64>::read_from(reader)?;
let date_time = chrono::NaiveDateTime::from_timestamp_millis(timestamp_millis).ok_or(
io::Error::new(
io::ErrorKind::Other,
format!("invalid datetime {:?}", timestamp_millis),
),
)?;
let date_time =
chrono::NaiveDateTime::from_timestamp_millis(timestamp_millis).ok_or_else(|| {
io::Error::new(
io::ErrorKind::Other,
format!("invalid datetime {:?}", timestamp_millis),
)
})?;
Ok(DateTimeFormats::DateTime(date_time))
}
3 => {
let native_local_timestamp_millis = <i64>::read_from(reader)?;
let offset = <i32>::read_from(reader)?;
let tz = chrono::FixedOffset::east_opt(offset)
.ok_or(io::Error::new(io::ErrorKind::Other, format!("invalid offset {:?}", offset)))?;
let tz = chrono::FixedOffset::east_opt(offset).ok_or_else(|| {
io::Error::new(io::ErrorKind::Other, format!("invalid offset {:?}", offset))
})?;
let date_time = chrono::NaiveDateTime::from_timestamp_millis(native_local_timestamp_millis)
.ok_or(io::Error::new(
io::ErrorKind::Other,
format!("invalid datetime {:?}", native_local_timestamp_millis),
))?
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::Other,
format!("invalid datetime {:?}", native_local_timestamp_millis),
)
})?
.and_local_timezone(tz)
.single()
.ok_or(io::Error::new(
io::ErrorKind::Other,
format!(
"invalid datetime with timezone {:?} {:?}",
native_local_timestamp_millis, tz
),
))?;
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::Other,
format!(
"invalid datetime with timezone {:?} {:?}",
native_local_timestamp_millis, tz
),
)
})?;

Ok(DateTimeFormats::DateTimeWithTz(date_time))
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ pub struct PlanBuilder {

impl Default for PlanBuilder {
fn default() -> Self {
PlanBuilder {id: DEFAULT_PLAN_ID, plan: vec![] }
PlanBuilder { id: DEFAULT_PLAN_ID, plan: vec![] }
}
}

Expand Down Expand Up @@ -165,7 +165,7 @@ impl PlanBuilder {
let apply = pb::Apply {
join_kind: unsafe { ::std::mem::transmute(join_kind) },
keys: vec![],
sub_plan: Some(pb::PhysicalPlan { plan: sub_plan.take(), plan_id: DEFAULT_PLAN_ID }),
sub_plan: Some(pb::PhysicalPlan { plan: sub_plan.take(), plan_id: DEFAULT_PLAN_ID }),
alias,
};
let op = pb::physical_opr::operator::OpKind::Apply(apply);
Expand Down Expand Up @@ -221,7 +221,7 @@ impl PlanBuilder {
left_keys,
right_keys,
join_kind: unsafe { ::std::mem::transmute(join_kind) },
left_plan: Some(pb::PhysicalPlan { plan: left_plan.take() , plan_id: DEFAULT_PLAN_ID}),
left_plan: Some(pb::PhysicalPlan { plan: left_plan.take(), plan_id: DEFAULT_PLAN_ID }),
right_plan: Some(pb::PhysicalPlan { plan: right_plan.take(), plan_id: DEFAULT_PLAN_ID }),
};
let op = pb::physical_opr::operator::OpKind::Join(join);
Expand All @@ -247,7 +247,7 @@ impl PlanBuilder {
pub fn union(&mut self, mut plans: Vec<PlanBuilder>) -> &mut Self {
let mut sub_plans = vec![];
for plan in plans.drain(..) {
sub_plans.push(pb::PhysicalPlan { plan: plan.take() , plan_id: DEFAULT_PLAN_ID});
sub_plans.push(pb::PhysicalPlan { plan: plan.take(), plan_id: DEFAULT_PLAN_ID });
}
let union = pb::Union { sub_plans };
let op = pb::physical_opr::operator::OpKind::Union(union);
Expand All @@ -259,7 +259,7 @@ impl PlanBuilder {
let key = key.try_into().unwrap();
let mut sub_plans = vec![];
for plan in plans.drain(..) {
sub_plans.push(pb::PhysicalPlan { plan: plan.take() , plan_id: DEFAULT_PLAN_ID});
sub_plans.push(pb::PhysicalPlan { plan: plan.take(), plan_id: DEFAULT_PLAN_ID });
}
let intersect = pb::Intersect { sub_plans, key };
let op = pb::physical_opr::operator::OpKind::Intersect(intersect);
Expand Down Expand Up @@ -331,7 +331,7 @@ impl PlanBuilder {
}

pub fn build(self) -> pb::PhysicalPlan {
pb::PhysicalPlan { plan: self.plan , plan_id: self.id}
pb::PhysicalPlan { plan: self.plan, plan_id: self.id }
}
}

Expand Down
30 changes: 15 additions & 15 deletions interactive_engine/executor/ir/common/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -394,14 +394,16 @@ impl TryFrom<pb::IndexPredicate> for Vec<i64> {
let predicate = and_predicate
.predicates
.get(0)
.ok_or(ParsePbError::EmptyFieldError("`AndCondition` is emtpy".to_string()))?;
.ok_or_else(|| ParsePbError::EmptyFieldError("`AndCondition` is emtpy".to_string()))?;

let (key, value) = (predicate.key.as_ref(), predicate.value.as_ref());
let key = key.ok_or("key is empty in kv_pair in indexed_scan")?;
let key = key.ok_or_else(|| {
ParsePbError::EmptyFieldError("key is empty in kv_pair in indexed_scan".to_string())
})?;
if let Some(common_pb::property::Item::Id(_id_key)) = key.item.as_ref() {
let value_item = value.ok_or(ParsePbError::EmptyFieldError(
"`Value` is empty in kv_pair in indexed_scan".to_string(),
))?;
let value_item = value.ok_or_else(|| {
ParsePbError::EmptyFieldError("`Value` is empty in kv_pair in indexed_scan".to_string())
})?;

match value_item {
pb::index_predicate::triplet::Value::Const(value) => match value.item.as_ref() {
Expand Down Expand Up @@ -440,14 +442,12 @@ impl TryFrom<pb::IndexPredicate> for Vec<Vec<(NameOrId, Object)>> {
// PkValue can be one-column or multi-columns, which is a set of and_conditions.
let mut primary_key_value = Vec::with_capacity(and_predicates.predicates.len());
for predicate in &and_predicates.predicates {
let key_pb = predicate
.key
.clone()
.ok_or("key is empty in kv_pair in indexed_scan")?;
let value_pb = predicate
.value
.clone()
.ok_or("value is empty in kv_pair in indexed_scan")?;
let key_pb = predicate.key.clone().ok_or_else(|| {
ParsePbError::EmptyFieldError("key is empty in kv_pair in indexed_scan".to_string())
})?;
let value_pb = predicate.value.clone().ok_or_else(|| {
ParsePbError::EmptyFieldError("value is empty in kv_pair in indexed_scan".to_string())
})?;
let key = match key_pb.item {
Some(common_pb::property::Item::Key(prop_key)) => prop_key.try_into()?,
_ => Err(ParsePbError::Unsupported(
Expand Down Expand Up @@ -909,9 +909,9 @@ impl TryFrom<physical_pb::PhysicalOpr> for physical_pb::physical_opr::operator::
fn try_from(op: PhysicalOpr) -> Result<Self, Self::Error> {
let op_kind = op
.opr
.ok_or(ParsePbError::EmptyFieldError("algebra op is empty".to_string()))?
.ok_or_else(|| ParsePbError::EmptyFieldError("algebra op is empty".to_string()))?
.op_kind
.ok_or(ParsePbError::EmptyFieldError("algebra op_kind is empty".to_string()))?;
.ok_or_else(|| ParsePbError::EmptyFieldError("algebra op_kind is empty".to_string()))?;
Ok(op_kind)
}
}
Expand Down
4 changes: 2 additions & 2 deletions interactive_engine/executor/ir/core/src/glogue/extend_step.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,10 @@ impl ExactExtendEdge {
path_opr
.base
.as_mut()
.ok_or(ParsePbError::EmptyFieldError("PathExpand::base in Pattern".to_string()))?
.ok_or_else(|| ParsePbError::EmptyFieldError("PathExpand::base in Pattern".to_string()))?
.edge_expand
.as_mut()
.ok_or(ParsePbError::EmptyFieldError("PathExpand::base in Pattern".to_string()))?
.ok_or_else(|| ParsePbError::EmptyFieldError("PathExpand::base in Pattern".to_string()))?
.direction = self.dir as i32;
Ok(path_opr.into())
}
Expand Down
Loading

0 comments on commit b5f389b

Please sign in to comment.