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

Opt-in native getters and setters for "newtypes"/"value types" #405

Closed
wants to merge 4 commits into from

Conversation

dzfranklin
Copy link
Contributor

@dzfranklin dzfranklin commented Jun 5, 2023

My goal is to incrementally make the generated code easier to use without getting bogged down in something ambitious (#136). This is intended for simple types that nearly primitive values.

To opt-in you add an annotation and implement a trait

struct User {
    id @0 :Uuid;
}

struct Uuid $Rust.valueType {
  d1 @0 :UInt32;
  d2 @1 :UInt16;
  d3 @2 :UInt16;
  d4 @3 :UInt64;
}
use uuid::Uuid;

impl capnp::traits::ValueType for account_capnp::uuid::Owned {
    type Type = Uuid;

    fn read(reader: Self::Reader<'_>) -> capnp::Result<Self::Type> {
        let d4 = reader.get_d4().to_be_bytes();
        Ok(Uuid::from_fields(reader.get_d1(), reader.get_d2(), reader.get_d3(), &d4))
    }

    fn build(mut builder: Self::Builder<'_>, value: Self::Type) -> capnp::Result<()> {
        let (d1, d2, d3, d4) = uuid.as_fields();
        let d4 = u64::from_be_bytes(*d4);
        builder.set_d1(d1);
        builder.set_d2(d2);
        builder.set_d3(d3);
        builder.set_d4(d4);
        Ok(())
    }
}
let message = capnp::message::Builder::new_default();
let root = message.init_root::<account_capnp::user::Builder>();

let admin_id = Uuid::from_str("a1b2c3d4-e5f6-7a8b-9c0d-1e2f3a4b5c6d").unwrap();
root.set_id(admin_id);
assert_eq!(root.reborrow_as_reader().get_id(), admin_id);

Fixes #245

Given

    struct Test {
        field @0 :Text $Rust.getOption;
    }

you get getters like so

    assert_eq!(struct_with.get_field(), Some("foo"));
    assert_eq!(struct_without.get_field(), None));

The setters are unchanged to match the Rust convention.

Fixes capnproto#249.
@dzfranklin
Copy link
Contributor Author

I've ended up thinking this isn't worthwhile

@dzfranklin dzfranklin closed this Jun 11, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Support newtypes
1 participant