rust-protobuf icon indicating copy to clipboard operation
rust-protobuf copied to clipboard

Add From and Into support for SystemTime using references

Open neilisaac opened this issue 2 years ago • 3 comments

Enable conversions between Timestamp and SystemTime using references without cloning, and add support for SystemTime::from(Timestamp) in addition to Into (which is derived from the From implementations)

Refer to the note in https://doc.rust-lang.org/std/convert/trait.Into.html

neilisaac avatar Jan 04 '23 15:01 neilisaac

Can add the same for Duration too.

neilisaac avatar Jan 04 '23 15:01 neilisaac

There was a report that this violates Rust conventions: https://github.com/stepancheg/rust-protobuf/issues/690

Also, is it Rust convention to convert from &? Are there examples of something similar in rust stdlib? For example, there's no From<&32> for u64.

stepancheg avatar Dec 05 '23 22:12 stepancheg

@stepancheg my issue is mainly an ergonomics problem where we need to clone a Timestamp before converting it:

// intuitively I'd like to do
let t: SystemTime = msg.timestamp_field.into();
// or
let t = SystemTime::from(&msg.timestamp_field);

// however we need to do
let t: SystemTime = msg.timestamp_field.clone().into();
// or
let t = SystemTime::from(msg.timestamp_field.clone());

You don't need From<&u32> because u32 supports Copy.

Can Timestamp just implement Copy?

The clone doesn't have any meaningful overhead since there's no allocation, so it's just ergonomics. It's not always obvious how do convert a Timestamp into SystemTime, and I've seen multiple PRs where folks implemented the conversion manually because their ide couldn't suggest a better way.

Based on these conventions I'd probably say that implementing Timestamp::to_system_time(&self) ("borrowed -> owned (non-Copy types)") would be reasonable for a non-Copy struct, however if Timestamp implemented Copy, we wouldn't have this issue.

neilisaac avatar Dec 11 '23 23:12 neilisaac