Skip to content

Commit

Permalink
Add extra info in the struct traits section of mojo cpp bindings doc
Browse files Browse the repository at this point in the history
This change adds a note and an example to clarify why it's safe to
return read-only views in struct traits accessors.

Change-Id: I0b6b646de10dd01fe5ae347f48d9a119b6e118a6
Reviewed-on: https://chromium-review.googlesource.com/c/1316787
Commit-Queue: Oksana Zhuravlova <oksamyt@chromium.org>
Reviewed-by: Ken Rockot <rockot@google.com>
Cr-Commit-Position: refs/heads/master@{#605837}
  • Loading branch information
Oksana Zhuravlova authored and Commit Bot committed Nov 6, 2018
1 parent 7dc9e60 commit 4b59467
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions mojo/public/cpp/bindings/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1332,6 +1332,35 @@ height, its message will be rejected and the pipe will be closed. In this way,
type mapping can serve to enable custom validation logic in addition to making
callsites and interface implemention more convenient.
When the struct fields have non-primitive types, e.g. string or array,
returning a read-only view of the data in the accessor is recommended to
avoid copying. It is safe because the input object is guaranteed to
outlive the usage of the result returned by the accessor method.
The following example uses `StringPiece` to return a view of the GURL's
data (`//url/mojom/url_gurl_mojom_traits.h`):

``` cpp
#include "base/strings/string_piece.h"
#include "url/gurl.h"
#include "url/mojom/url.mojom.h"
#include "url/url_constants.h"

namespace mojo {

template <>
struct StructTraits<url::mojom::UrlDataView, GURL> {
static base::StringPiece url(const GURL& r) {
if (r.possibly_invalid_spec().length() > url::kMaxURLChars ||
!r.is_valid()) {
return base::StringPiece();
}
return base::StringPiece(r.possibly_invalid_spec().c_str(),
r.possibly_invalid_spec().length());
}
} // namespace mojo
```
### Enabling a New Type Mapping
We've defined the `StructTraits` necessary, but we still need to teach the
Expand Down

0 comments on commit 4b59467

Please sign in to comment.