Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
2 changes: 1 addition & 1 deletion MODULE.bazel
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module(
name = "phaser",
version = "3.1.0"
version = "3.1.1"
)

bazel_dep(name = "bazel_skylib", version = "1.9.0")
Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ a serialization step** — the bytes in the buffer *are* the message.
Choose a protobuf-style C++ API, a ROS-style public-field API, or a C API.
Python and Rust clients use the protobuf-style accessors. All of them share
the same native payload and the same protobuf and ROS wire conversion backends.
The C and Rust clients copy that payload with `native_payload` and load it
with `parse_native_payload`. `serialize_as_string` remains the protobuf
transcoding.

> 📖 For the full reference, see the **[Phaser User Guide](phaser/docs/phaser_user_guide.md)**.

Expand Down
44 changes: 43 additions & 1 deletion phaser/compiler/message_gen_c.cc
Original file line number Diff line number Diff line change
Expand Up @@ -677,6 +677,47 @@ void MessageGenerator::GenerateBindings(
prefix +
"_parse_from_string(self.ptr, phaser_bytes_ptr(bytes), bytes.len()) })\n"
" }\n");
// Data()/ByteSizeLong() are the native payload. serialize_as_string is the
// protobuf transcoding of that payload, so a receiver that speaks Phaser
// uses these two instead.
Bind(decl, def, rust_extern_out, rust_body_out,
"PhaserBytes " + prefix + "_native_payload(" + const_self + ")",
Guard(cpp, true, "return PhaserBytes{nullptr, size_t{0}};") +
" const void* data = h->get()->Data();\n"
" const size_t size = h->get()->ByteSizeLong();\n"
" if (data == nullptr || size == 0) {\n"
" return PhaserBytes{nullptr, size_t{0}};\n"
" }\n"
" return ::phaser::capi::Copy(std::string_view(\n"
" static_cast<const char*>(data), size));\n",
prefix + "_native_payload(msg: *const " + raw + ") -> PhaserBytes",
" pub fn native_payload(&self) -> Vec<u8> {\n copy_bytes(unsafe { " +
prefix + "_native_payload(self.ptr) })\n }\n");
Bind(decl, def, rust_extern_out, rust_body_out,
"uint8_t " + prefix + "_parse_native_payload(" + mut_self +
", const uint8_t* data, size_t len)",
Guard(cpp, false, "return 0;") +
" if (data == nullptr || len == 0 ||\n"
" !::phaser::internal::IsStructurallyValidPhaser(\n"
" absl::MakeConstSpan(reinterpret_cast<const char*>(data),\n"
" len))) {\n"
" return 0;\n"
" }\n"
" Msg view = Msg::CreateReadonly(data, len);\n"
" h->get()->Clear();\n"
" const absl::Status status = h->get()->CloneFrom(view);\n"
" if (!status.ok() || h->get()->AllocationFailed()) {\n"
" h->get()->Clear();\n"
" return 0;\n"
" }\n"
" return 1;\n",
prefix + "_parse_native_payload(msg: *mut " + raw +
", data: *const u8, len: usize) -> u8",
" pub fn parse_native_payload(&mut self, bytes: &[u8]) -> bool {\n"
" flag(unsafe { " +
prefix +
"_parse_native_payload(self.ptr, phaser_bytes_ptr(bytes), bytes.len()) })\n"
" }\n");

for (const auto& field : fields_) {
EmitCField(field->field, decl, def, rust_extern_out, rust_body_out,
Expand Down Expand Up @@ -722,7 +763,8 @@ void Generator::GenerateBindings(std::ostream& c_header, std::ostream& c_source,
std::filesystem::path include_path(GeneratedIncludeFilename(
package_name_, target_name_, std::string(file_->name())));
include_path.replace_extension(".phaser.c.h");
c_source << "\n#include \"phaser/runtime/phaser_c_handle.h\"\n#include \""
c_source << "\n#include \"phaser/runtime/phaser_c_handle.h\"\n"
"#include \"phaser/runtime/wireformat.h\"\n#include \""
<< include_path.string() << "\"\nextern \"C\" {\n";
for (int i = 0; i < file_->enum_type_count(); ++i) {
EmitEnum(file_->enum_type(i), c_header, rust);
Expand Down
20 changes: 19 additions & 1 deletion phaser/docs/phaser_user_guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,12 @@ with `phaser_free`. A null `data` pointer is empty. Bool crosses the ABI as
`uint8_t`. Strings and bytes are a pointer plus a length, so interior zeros
survive. Enum arguments and results are `int32_t`.

`_native_payload` copies the native Phaser buffer (`Data()` and
`ByteSizeLong()`). Free it with `phaser_free`. `_parse_native_payload` copies
that buffer's fields into the message and returns 0, leaving the message
unchanged, when the bytes are not a Phaser payload. `_serialize_as_string` and
`_parse_from_string` are the protobuf transcoding.

`phaser_AnyMessage` is declared in `phaser/runtime/phaser_c.h`. Any fields
return that type. It has no `_new`; take it from `mutable_any` or `any`, then
`phaser_AnyMessage_free` the handle. The generated `google.protobuf.Any`
Expand Down Expand Up @@ -455,13 +461,25 @@ msg.add_samples(1.5);
assert_eq!(msg.child().label(), "cam");

msg.set_kind(Kind::CAMERA);
let payload = msg.native_payload();
let mut copy = Foo::new(payload.len());
assert!(copy.parse_native_payload(&payload));
assert_eq!(copy.name(), "sensor");

let blob = msg.serialize_as_string();
let mut copy = Foo::new(1024);
assert!(copy.parse_from_string(&blob));
assert!(copy.debug_string().contains("cam"));
copy.clear();
```

`native_payload` is a copy of `Data()` / `ByteSizeLong()`: the native Phaser
buffer, with no protobuf transcoding. Offsets in that image are absolute, so
two messages with the same fields are not byte-identical. `parse_native_payload`
copies the fields into this message and leaves it unchanged when the bytes are
not a Phaser payload. The source buffer does not need to stay alive.
`serialize_as_string` and `parse_from_string` still speak protobuf.
`byte_size_long` is the native payload length.

`new` returns a `'static` message. Accessors that return a message tie that
handle's lifetime to the borrow of the parent, and `Drop` frees the handle.
End the child borrow before using the parent again. Strings are `String` on
Expand Down
9 changes: 9 additions & 0 deletions phaser/runtime/message.cc
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,14 @@ namespace phaser {
namespace {
// Keeping a bigger image would cost more memory than copying it saves time.
constexpr size_t kMaxNewBufferImageSize = 64 * 1024;

// Builds the permanent failure statuses before main, so the first buffer
// that fills up does not allocate.
const bool kPermanentErrorsReady = [] {
(void)internal::AllocationFailedError();
(void)internal::BufferTooSmallError();
return true;
}();
} // namespace

NewBufferImage::NewBufferImage(Maker make) {
Expand All @@ -40,6 +48,7 @@ NewBufferImage::NewBufferImage(Maker make) {

::phaser::PayloadBuffer* NewBufferImage::CopyTo(void* addr,
size_t size) const {
(void)kPermanentErrorsReady;
if (addr == nullptr || size_ == 0 || size < size_ ||
size > std::numeric_limits<uint32_t>::max()) {
return nullptr;
Expand Down
27 changes: 25 additions & 2 deletions phaser/runtime/message.h
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,31 @@ namespace internal {
std::abort();
}

// A process-lifetime status. Copying it adjusts a refcount, so failing does
// not allocate, and message() still returns the text. The first call builds
// it; message.cc does that before main.
inline absl::Status PermanentError(absl::StatusCode code,
absl::string_view /*message*/) {
static const absl::NoDestructor<absl::Status> full(
absl::Status(absl::StatusCode::kResourceExhausted,
"phaser: payload buffer is full"));
static const absl::NoDestructor<absl::Status> too_small(
absl::Status(absl::StatusCode::kInvalidArgument,
"phaser: buffer is too small"));
if (code == absl::StatusCode::kInvalidArgument) {
return *too_small;
}
return *full;
}

inline absl::Status AllocationFailedError() {
return absl::ResourceExhaustedError("phaser: payload buffer is full");
return PermanentError(absl::StatusCode::kResourceExhausted,
"phaser: payload buffer is full");
}

inline absl::Status BufferTooSmallError() {
return PermanentError(absl::StatusCode::kInvalidArgument,
"phaser: buffer is too small");
}
} // namespace internal
} // namespace phaser
Expand Down Expand Up @@ -1856,7 +1879,7 @@ ::phaser::PayloadBuffer* NewFixedBuffer(void* addr, size_t size,
// message's fixed parts.
inline absl::Status NewFixedBufferError(const void* addr, size_t size) {
if (!CanHoldFixedBuffer(addr, size)) {
return absl::InvalidArgumentError("phaser: buffer is too small");
return internal::BufferTooSmallError();
}
return internal::AllocationFailedError();
}
Expand Down
23 changes: 23 additions & 0 deletions phaser/testdata/c_api_test.c
Original file line number Diff line number Diff line change
Expand Up @@ -157,10 +157,33 @@ int main(void) {
phaser_AnyMessage_free(packed);

CHECK(phaser_foo_bar_TestMessage_byte_size_long(msg) > 0);
PhaserBytes native = phaser_foo_bar_TestMessage_native_payload(msg);
CHECK(native.data != NULL);
CHECK(native.size == phaser_foo_bar_TestMessage_byte_size_long(msg));
CHECK(native.data[0] == 0);
phaser_foo_bar_TestMessage* native_copy = phaser_foo_bar_TestMessage_new(native.size);
CHECK(phaser_foo_bar_TestMessage_parse_native_payload(native_copy, native.data,
native.size));
s = phaser_foo_bar_TestMessage_s(native_copy);
CHECK(bytes_eq(s, (const uint8_t*)"hi", 2));
phaser_free(s.data);
buffer = phaser_foo_bar_TestMessage_buffer(native_copy);
CHECK(bytes_eq(buffer, raw_buf, 3));
phaser_free(buffer.data);

PhaserBytes debug = phaser_foo_bar_TestMessage_debug_string(msg);
CHECK(contains(debug, "nested"));
phaser_free(debug.data);
PhaserBytes blob = phaser_foo_bar_TestMessage_serialize_as_string(msg);
CHECK(blob.size != native.size ||
memcmp(blob.data, native.data, native.size) != 0);
CHECK(!phaser_foo_bar_TestMessage_parse_native_payload(native_copy, blob.data,
blob.size));
s = phaser_foo_bar_TestMessage_s(native_copy);
CHECK(bytes_eq(s, (const uint8_t*)"hi", 2));
phaser_free(s.data);
phaser_free(native.data);
phaser_foo_bar_TestMessage_free(native_copy);
phaser_foo_bar_TestMessage* copy = phaser_foo_bar_TestMessage_new(1024);
CHECK(phaser_foo_bar_TestMessage_parse_from_string(copy, blob.data, blob.size));
phaser_free(blob.data);
Expand Down
25 changes: 25 additions & 0 deletions phaser/testdata/rust_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,32 @@ fn getters_setters_and_round_trip() {

assert!(msg.byte_size_long() > 0);
assert!(msg.debug_string().contains("nested"));
let native = msg.native_payload();
assert_eq!(native.len(), msg.byte_size_long());
assert_eq!(native[0], 0);
let mut native_copy = TestMessage::new(native.len());
assert!(native_copy.parse_native_payload(&native));
assert_eq!(native_copy.s(), "hi");
assert_eq!(native_copy.buffer(), b"a\0b");
assert_eq!(native_copy.e(), EnumTest::FOO);
assert_eq!(native_copy.m().str(), "nested");
assert_eq!(native_copy.vm(0).str(), "e1");
assert_eq!(native_copy.values(0).key(), "k");
assert_eq!(native_copy.any().type_url(), type_url);

let detached = {
let mut temp = TestMessage::new(256);
temp.set_s("gone");
temp.native_payload()
};
let mut revived = TestMessage::new(detached.len());
assert!(revived.parse_native_payload(&detached));
assert_eq!(revived.s(), "gone");

let blob = msg.serialize_as_string();
assert_ne!(blob, native);
assert!(!native_copy.parse_native_payload(&blob));
assert_eq!(native_copy.s(), "hi");
let mut copy = TestMessage::new(1024);
assert!(copy.parse_from_string(&blob));
assert_eq!(copy.s(), "hi");
Expand Down
Loading