nats.rs icon indicating copy to clipboard operation
nats.rs copied to clipboard

Subject trait

Open derekcollison opened this issue 3 years ago • 4 comments

Inspired by @mfarnbauer-schmidt and https://github.com/nats-io/nats.rs/pull/222 I wanted to see if we could do something that was a simple trait and a bit lighter weight.

Signed-off-by: Derek Collison [email protected]

derekcollison avatar Jan 08 '22 21:01 derekcollison

Its lighter than the other PR, I think the answer is the middle ground of the two. Like having a Subject type and implementing an AsSubject trait for ref str (as being zero copy).

caspervonb avatar Jan 09 '22 14:01 caspervonb

BTW with the latest commit to #222 I changed Subject to wrap str instead of &'s str this makes converting &str to &Subject only a simple cast, i.e. a zero-copy action

MattesWhite avatar Jan 10 '22 09:01 MattesWhite

Zero Copy but does it validate? Meaning there is a runtime costs to using &str now for publish calls etc?

derekcollison avatar Jan 10 '22 13:01 derekcollison

Yes and no. Currently, there are Subject::new_unchecked() and Subject::new() where the first does a zero-copy cast of &str to &Subject ,however, the string is not validated. The later is fallible and performs validation. So if you want to frequently publish to the same subject you can do something like this:

let nc = nats::connect("demo.nats.io")?;
let sub = Subject::new("foo.bar")?; // validate only once

loop {
    nc.publish(sub, &[21, 42, 84])?; // re-use validated subject
    sleep(10);
}

In the case of "foo.bar" where you already know it's a valid subject you can still use Subject::new_unchecked().

MattesWhite avatar Jan 10 '22 16:01 MattesWhite

Closing, as subject trait is already implemented.

Jarema avatar Jan 03 '24 18:01 Jarema