1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
|
// Protocol Buffers - Google's data interchange format
// Copyright 2023 Google LLC. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd
use std::fmt::{self, Debug};
use std::iter;
use std::iter::FusedIterator;
/// Repeated scalar fields are implemented around the runtime-specific
/// `RepeatedField` struct. `RepeatedField` stores an opaque pointer to the
/// runtime-specific representation of a repeated scalar (`upb_Array*` on upb,
/// and `RepeatedField<T>*` on cpp).
use std::marker::PhantomData;
use crate::{
AsMut, AsView, IntoMut, IntoProxied, IntoView, Message, Mut, MutProxied, MutProxy, Proxied,
Proxy, View, ViewProxy,
__internal::runtime::{InnerRepeated, InnerRepeatedMut, RawRepeatedField},
__internal::{Private, SealedInternal},
};
/// Views the elements in a `repeated` field of `T`.
#[repr(transparent)]
pub struct RepeatedView<'msg, T> {
// This does not need to carry an arena in upb, so it can be just the raw repeated field
raw: RawRepeatedField,
_phantom: PhantomData<&'msg T>,
}
impl<'msg, T> Copy for RepeatedView<'msg, T> {}
impl<'msg, T> Clone for RepeatedView<'msg, T> {
fn clone(&self) -> Self {
*self
}
}
unsafe impl<'msg, T> Sync for RepeatedView<'msg, T> {}
unsafe impl<'msg, T> Send for RepeatedView<'msg, T> {}
impl<'msg, T> Debug for RepeatedView<'msg, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RepeatedView").field("raw", &self.raw).finish()
}
}
/// Mutates the elements in a `repeated` field of `T`.
pub struct RepeatedMut<'msg, T> {
pub(crate) inner: InnerRepeatedMut<'msg>,
_phantom: PhantomData<&'msg mut T>,
}
unsafe impl<'msg, T> Sync for RepeatedMut<'msg, T> {}
impl<'msg, T> Debug for RepeatedMut<'msg, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RepeatedMut").field("raw", &self.inner.raw).finish()
}
}
#[doc(hidden)]
impl<'msg, T> RepeatedView<'msg, T> {
#[doc(hidden)]
#[inline]
pub fn as_raw(&self, _private: Private) -> RawRepeatedField {
self.raw
}
/// # Safety
/// - `inner` must be valid to read from for `'msg`
#[doc(hidden)]
#[inline]
pub unsafe fn from_raw(_private: Private, raw: RawRepeatedField) -> Self {
Self { raw, _phantom: PhantomData }
}
}
impl<'msg, T> RepeatedView<'msg, T>
where
T: ProxiedInRepeated + 'msg,
{
/// Gets the length of the repeated field.
#[inline]
pub fn len(&self) -> usize {
T::repeated_len(*self)
}
/// Returns true if the repeated field has no values.
#[inline]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Gets the value at `index`.
///
/// Returns `None` if `index > len`.
#[inline]
pub fn get(self, index: usize) -> Option<View<'msg, T>> {
if index >= self.len() {
return None;
}
// SAFETY: `index` has been checked to be in-bounds
Some(unsafe { self.get_unchecked(index) })
}
/// Gets the value at `index` without bounds-checking.
///
/// # Safety
/// Undefined behavior if `index >= len`
#[inline]
pub unsafe fn get_unchecked(self, index: usize) -> View<'msg, T> {
// SAFETY: in-bounds as promised
unsafe { T::repeated_get_unchecked(self, index) }
}
/// Iterates over the values in the repeated field.
pub fn iter(self) -> RepeatedIter<'msg, T> {
self.into_iter()
}
}
#[doc(hidden)]
impl<'msg, T> RepeatedMut<'msg, T> {
/// # Safety
/// - `inner` must be valid to read and write from for `'msg`
/// - There must be no aliasing references or mutations on the same
/// underlying object.
#[doc(hidden)]
#[inline]
pub unsafe fn from_inner(_private: Private, inner: InnerRepeatedMut<'msg>) -> Self {
Self { inner, _phantom: PhantomData }
}
#[doc(hidden)]
#[inline]
pub fn as_raw(&mut self, _private: Private) -> RawRepeatedField {
self.inner.raw
}
}
impl<'msg, T> RepeatedMut<'msg, T>
where
T: ProxiedInRepeated + 'msg,
{
/// Gets the length of the repeated field.
#[inline]
pub fn len(&self) -> usize {
self.as_view().len()
}
/// Returns true if the repeated field has no values.
#[inline]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Gets the value at `index`.
///
/// Returns `None` if `index >= len`.
#[inline]
pub fn get(&self, index: usize) -> Option<View<T>> {
self.as_view().get(index)
}
/// Gets the value at `index`.
///
/// Returns `None` if `index >= len`.
#[inline]
pub fn get_mut<'r>(&'r mut self, index: usize) -> Option<Mut<'msg, T>>
where
T: Message,
'r: 'msg,
{
if index >= self.len() {
return None;
}
// SAFETY: `index` has been checked to be in-bounds
Some(unsafe { self.get_mut_unchecked(index) })
}
/// Gets the value at `index` without bounds-checking.
///
/// # Safety
/// Undefined behavior if `index >= len`.
#[inline]
pub unsafe fn get_mut_unchecked<'r>(&'r mut self, index: usize) -> Mut<'msg, T>
where
T: Message,
'r: 'msg,
{
// SAFETY: in-bounds as promised
unsafe { T::repeated_get_mut_unchecked(self.as_mut(), index) }
}
/// Gets the value at `index` without bounds-checking.
///
/// # Safety
/// Undefined behavior if `index >= len`.
#[inline]
pub unsafe fn get_unchecked(&self, index: usize) -> View<T> {
// SAFETY: in-bounds as promised
unsafe { self.as_view().get_unchecked(index) }
}
/// Appends `val` to the end of the repeated field.
#[inline]
pub fn push(&mut self, val: impl IntoProxied<T>) {
T::repeated_push(self.as_mut(), val);
}
/// Sets the value at `index` to the value `val`.
///
/// # Panics
/// Panics if `index >= len`.
#[inline]
pub fn set(&mut self, index: usize, val: impl IntoProxied<T>) {
let len = self.len();
if index >= len {
panic!("index {index} >= repeated len {len}");
}
unsafe { self.set_unchecked(index, val) }
}
/// Sets the value at `index` to the value `val`.
///
/// # Safety
/// Undefined behavior if `index >= len`.
#[inline]
pub unsafe fn set_unchecked(&mut self, index: usize, val: impl IntoProxied<T>) {
unsafe { T::repeated_set_unchecked(self.as_mut(), index, val) }
}
/// Iterates over the values in the repeated field.
pub fn iter(&self) -> RepeatedIter<T> {
self.as_view().into_iter()
}
/// Copies from the `src` repeated field into this one.
pub fn copy_from(&mut self, src: RepeatedView<'_, T>) {
T::repeated_copy_from(src, self.as_mut())
}
/// Clears the repeated field.
pub fn clear(&mut self) {
T::repeated_clear(self.as_mut())
}
}
impl<T> Repeated<T>
where
T: ProxiedInRepeated,
{
pub fn as_view(&self) -> View<Repeated<T>> {
RepeatedView { raw: self.inner.raw(), _phantom: PhantomData }
}
#[doc(hidden)]
pub fn inner(&self, _private: Private) -> &InnerRepeated {
&self.inner
}
}
impl<'msg, T> IntoProxied<Repeated<T>> for RepeatedView<'msg, T>
where
T: 'msg + ProxiedInRepeated,
{
fn into_proxied(self, _private: Private) -> Repeated<T> {
let mut repeated: Repeated<T> = Repeated::new();
T::repeated_copy_from(self, repeated.as_mut());
repeated
}
}
impl<'msg, T> IntoProxied<Repeated<T>> for RepeatedMut<'msg, T>
where
T: 'msg + ProxiedInRepeated,
{
fn into_proxied(self, _private: Private) -> Repeated<T> {
IntoProxied::into_proxied(self.as_view(), _private)
}
}
impl<'msg, T, I, U> IntoProxied<Repeated<T>> for I
where
I: Iterator<Item = U>,
T: 'msg + ProxiedInRepeated,
U: IntoProxied<T>,
{
fn into_proxied(self, _private: Private) -> Repeated<T> {
let mut repeated: Repeated<T> = Repeated::new();
repeated.as_mut().extend(self);
repeated
}
}
/// Types that can appear in a `Repeated<T>`.
///
/// This trait is implemented by generated code to communicate how the proxied
/// type can be manipulated for a repeated field.
///
/// Scalars and messages implement `ProxiedInRepeated`.
///
/// # Safety
/// - It must be sound to call `*_unchecked*(x)` with an `index` less than
/// `repeated_len(x)`.
pub unsafe trait ProxiedInRepeated: Proxied + SealedInternal {
/// Constructs a new owned `Repeated` field.
#[doc(hidden)]
fn repeated_new(_private: Private) -> Repeated<Self>;
/// Frees the repeated field in-place, for use in `Drop`.
///
/// # Safety
/// - After `repeated_free`, no other methods on the input are safe to call.
#[doc(hidden)]
unsafe fn repeated_free(_private: Private, _repeated: &mut Repeated<Self>);
/// Gets the length of the repeated field.
fn repeated_len(repeated: View<Repeated<Self>>) -> usize;
/// Appends a new element to the end of the repeated field.
fn repeated_push(repeated: Mut<Repeated<Self>>, val: impl IntoProxied<Self>);
/// Clears the repeated field of elements.
fn repeated_clear(repeated: Mut<Repeated<Self>>);
/// # Safety
/// `index` must be less than `Self::repeated_len(repeated)`
unsafe fn repeated_get_unchecked(repeated: View<Repeated<Self>>, index: usize) -> View<Self>;
/// # Safety
/// `index` must be less than `Self::repeated_len(repeated)`
#[allow(unused_variables)]
unsafe fn repeated_get_mut_unchecked(repeated: Mut<Repeated<Self>>, index: usize) -> Mut<Self>
where
Self: Message,
{
panic!("repeated_get_mut_unchecked is only implemented for messages");
}
/// # Safety
/// `index` must be less than `Self::repeated_len(repeated)`
unsafe fn repeated_set_unchecked(
repeated: Mut<Repeated<Self>>,
index: usize,
val: impl IntoProxied<Self>,
);
/// Copies the values in the `src` repeated field into `dest`.
fn repeated_copy_from(src: View<Repeated<Self>>, dest: Mut<Repeated<Self>>);
/// Ensures that the repeated field has enough space allocated to insert at
/// least `additional` values without an allocation.
fn repeated_reserve(repeated: Mut<Repeated<Self>>, additional: usize);
}
/// An iterator over the values inside of a [`View<Repeated<T>>`](RepeatedView).
pub struct RepeatedIter<'msg, T> {
view: RepeatedView<'msg, T>,
current_index: usize,
}
impl<'msg, T> Debug for RepeatedIter<'msg, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RepeatedIter")
.field("view", &self.view)
.field("current_index", &self.current_index)
.finish()
}
}
/// A `repeated` field of `T`, used as the owned target for `Proxied`.
///
/// Users will generally write [`View<Repeated<T>>`](RepeatedView) or
/// [`Mut<Repeated<T>>`](RepeatedMut) to access the repeated elements
pub struct Repeated<T: ProxiedInRepeated> {
pub(crate) inner: InnerRepeated,
_phantom: PhantomData<T>,
}
// SAFETY: `Repeated` is Sync because it does not implement interior mutability.
unsafe impl<T: ProxiedInRepeated> Sync for Repeated<T> {}
// SAFETY: `Repeated` is Send because it's not bound to a specific thread e.g.
// it does not use thread-local data or similar.
unsafe impl<T: ProxiedInRepeated> Send for Repeated<T> {}
impl<T: ProxiedInRepeated> Repeated<T> {
pub fn new() -> Self {
T::repeated_new(Private)
}
#[doc(hidden)]
pub fn from_inner(_private: Private, inner: InnerRepeated) -> Self {
Self { inner, _phantom: PhantomData }
}
pub(crate) fn as_mut(&mut self) -> RepeatedMut<'_, T> {
RepeatedMut { inner: self.inner.as_mut(), _phantom: PhantomData }
}
}
impl<T: ProxiedInRepeated> Default for Repeated<T> {
fn default() -> Self {
Repeated::new()
}
}
impl<T: ProxiedInRepeated> Drop for Repeated<T> {
fn drop(&mut self) {
// SAFETY: only called once
unsafe { T::repeated_free(Private, self) }
}
}
impl<T> Proxied for Repeated<T>
where
T: ProxiedInRepeated,
{
type View<'msg>
= RepeatedView<'msg, T>
where
Repeated<T>: 'msg;
}
impl<T> SealedInternal for Repeated<T> where T: ProxiedInRepeated {}
impl<T> AsView for Repeated<T>
where
T: ProxiedInRepeated,
{
type Proxied = Self;
fn as_view(&self) -> RepeatedView<'_, T> {
self.as_view()
}
}
impl<T> MutProxied for Repeated<T>
where
T: ProxiedInRepeated,
{
type Mut<'msg>
= RepeatedMut<'msg, T>
where
Repeated<T>: 'msg;
}
impl<T> AsMut for Repeated<T>
where
T: ProxiedInRepeated,
{
type MutProxied = Self;
fn as_mut(&mut self) -> RepeatedMut<'_, T> {
self.as_mut()
}
}
impl<'msg, T> SealedInternal for RepeatedView<'msg, T> where T: ProxiedInRepeated + 'msg {}
impl<'msg, T> Proxy<'msg> for RepeatedView<'msg, T> where T: ProxiedInRepeated + 'msg {}
impl<'msg, T> AsView for RepeatedView<'msg, T>
where
T: ProxiedInRepeated + 'msg,
{
type Proxied = Repeated<T>;
#[inline]
fn as_view(&self) -> View<'msg, Self::Proxied> {
*self
}
}
impl<'msg, T> IntoView<'msg> for RepeatedView<'msg, T>
where
T: ProxiedInRepeated + 'msg,
{
#[inline]
fn into_view<'shorter>(self) -> View<'shorter, Self::Proxied>
where
'msg: 'shorter,
{
RepeatedView { raw: self.raw, _phantom: PhantomData }
}
}
impl<'msg, T> ViewProxy<'msg> for RepeatedView<'msg, T> where T: ProxiedInRepeated + 'msg {}
impl<'msg, T> SealedInternal for RepeatedMut<'msg, T> where T: ProxiedInRepeated + 'msg {}
impl<'msg, T> Proxy<'msg> for RepeatedMut<'msg, T> where T: ProxiedInRepeated + 'msg {}
impl<'msg, T> AsView for RepeatedMut<'msg, T>
where
T: ProxiedInRepeated + 'msg,
{
type Proxied = Repeated<T>;
#[inline]
fn as_view(&self) -> RepeatedView<'_, T> {
RepeatedView { raw: self.inner.raw, _phantom: PhantomData }
}
}
impl<'msg, T> IntoView<'msg> for RepeatedMut<'msg, T>
where
T: ProxiedInRepeated + 'msg,
{
#[inline]
fn into_view<'shorter>(self) -> RepeatedView<'shorter, T>
where
'msg: 'shorter,
{
RepeatedView { raw: self.inner.raw, _phantom: PhantomData }
}
}
impl<'msg, T> AsMut for RepeatedMut<'msg, T>
where
T: ProxiedInRepeated + 'msg,
{
type MutProxied = Repeated<T>;
#[inline]
fn as_mut(&mut self) -> RepeatedMut<'_, T> {
RepeatedMut { inner: self.inner, _phantom: PhantomData }
}
}
impl<'msg, T> IntoMut<'msg> for RepeatedMut<'msg, T>
where
T: ProxiedInRepeated + 'msg,
{
#[inline]
fn into_mut<'shorter>(self) -> RepeatedMut<'shorter, T>
where
'msg: 'shorter,
{
RepeatedMut { inner: self.inner, _phantom: PhantomData }
}
}
impl<'msg, T> MutProxy<'msg> for RepeatedMut<'msg, T> where T: ProxiedInRepeated + 'msg {}
impl<'msg, T> iter::Iterator for RepeatedIter<'msg, T>
where
T: ProxiedInRepeated + 'msg,
{
type Item = View<'msg, T>;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
let val = self.view.get(self.current_index);
if val.is_some() {
self.current_index += 1;
}
val
}
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.len();
(len, Some(len))
}
}
impl<'msg, T: ProxiedInRepeated> ExactSizeIterator for RepeatedIter<'msg, T> {
fn len(&self) -> usize {
self.view.len() - self.current_index
}
}
// TODO: impl DoubleEndedIterator
impl<'msg, T: ProxiedInRepeated> FusedIterator for RepeatedIter<'msg, T> {}
impl<'msg, T> iter::IntoIterator for RepeatedView<'msg, T>
where
T: ProxiedInRepeated + 'msg,
{
type Item = View<'msg, T>;
type IntoIter = RepeatedIter<'msg, T>;
fn into_iter(self) -> Self::IntoIter {
RepeatedIter { view: self, current_index: 0 }
}
}
impl<'msg, T> iter::IntoIterator for &'_ RepeatedView<'msg, T>
where
T: ProxiedInRepeated + 'msg,
{
type Item = View<'msg, T>;
type IntoIter = RepeatedIter<'msg, T>;
fn into_iter(self) -> Self::IntoIter {
RepeatedIter { view: *self, current_index: 0 }
}
}
impl<'borrow, T> iter::IntoIterator for &'borrow RepeatedMut<'_, T>
where
T: ProxiedInRepeated + 'borrow,
{
type Item = View<'borrow, T>;
type IntoIter = RepeatedIter<'borrow, T>;
fn into_iter(self) -> Self::IntoIter {
RepeatedIter { view: self.as_view(), current_index: 0 }
}
}
impl<'msg, 'view, T, ViewT> Extend<ViewT> for RepeatedMut<'msg, T>
where
T: ProxiedInRepeated + 'view,
ViewT: IntoProxied<T>,
{
fn extend<I: IntoIterator<Item = ViewT>>(&mut self, iter: I) {
let iter = iter.into_iter();
T::repeated_reserve(self.as_mut(), iter.size_hint().0);
for item in iter {
self.push(item);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use googletest::prelude::*;
#[gtest]
fn test_primitive_repeated() {
macro_rules! primitive_repeated_tests {
($($t:ty => [$($vals:expr),* $(,)?]),* $(,)?) => {
$({
// Constructs a new, owned, `Repeated`, only used for tests.
let mut r = Repeated::<$t>::new();
let mut r = r.as_mut();
assert_that!(r.len(), eq(0));
assert!(r.iter().next().is_none(), "starts with empty iter");
assert!(r.iter().next().is_none(), "starts with empty mut iter");
assert!(r.is_empty(), "starts is_empty");
let mut expected_len = 0usize;
$(
let val: View<$t> = $vals;
r.push(val);
assert_that!(r.get(expected_len), eq(Some(val)));
expected_len += 1;
assert_that!(r.len(), eq(expected_len));
)*
assert_that!(r, elements_are![$(eq($vals)),*]);
r.set(0, <$t as Default>::default());
assert_that!(r.get(0).expect("elem 0"), eq(<$t as Default>::default()));
r.clear();
assert!(r.is_empty(), "is_empty after clear");
assert!(r.iter().next().is_none(), "iter empty after clear");
assert!(r.into_iter().next().is_none(), "mut iter empty after clear");
})*
}
}
primitive_repeated_tests!(
u32 => [1,2,3],
i32 => [1,2],
f64 => [10.0, 0.1234f64],
bool => [false, true, true, false],
);
}
#[gtest]
fn test_repeated_extend() {
let mut r = Repeated::<i32>::new();
r.as_mut().extend([0; 0]);
assert_that!(r.as_mut().len(), eq(0));
r.as_mut().extend([0, 1]);
assert_that!(r.as_mut(), elements_are![eq(0), eq(1)]);
let mut x = Repeated::<i32>::new();
x.as_mut().extend([2, 3]);
r.as_mut().extend(&x.as_mut());
assert_that!(r.as_mut(), elements_are![eq(0), eq(1), eq(2), eq(3)]);
}
#[gtest]
fn test_repeated_iter_into_proxied() {
let r: Repeated<i32> = [0, 1, 2, 3].into_iter().into_proxied(Private);
assert_that!(r.as_view(), elements_are![eq(0), eq(1), eq(2), eq(3)]);
}
}
|