aboutsummaryrefslogtreecommitdiff
path: root/pw_fuzzer/public/pw_fuzzer/fuzztest.h
blob: 9e72ec274e3ccca2676494f2c5ff37469251a16e (plain)
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
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
// Copyright 2023 The Pigweed Authors
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
#pragma once

/// @file fuzztest.h
/// Pigweed interface to FuzzTest
///
/// @rst
/// This header exposes the portion of the FuzzTest interface that only depends
/// on permitted C++ standard library `headers`_, including `macros`_ and
/// `domains`_.
///
/// It also extends the interface to provide domains for common Pigweed types,
/// such as those from the following modules:
///
/// * :ref:`module-pw_containers`
/// * :ref:`module-pw_result`
/// * :ref:`module-pw_status`
/// * :ref:`module-pw_string`
///
/// .. _domains:
///    https://github.com/google/fuzztest/blob/main/doc/domains-reference.md
/// .. _headers: https://pigweed.dev/docs/style_guide.html#permitted-headers
/// .. _macros:
///    https://github.com/google/fuzztest/blob/main/doc/fuzz-test-macro.md
/// @endrst

#include "pw_containers/flat_map.h"
#include "pw_containers/inline_deque.h"
#include "pw_containers/inline_queue.h"
#include "pw_containers/intrusive_list.h"
#include "pw_containers/vector.h"
#include "pw_fuzzer/internal/fuzztest.h"
#include "pw_result/result.h"
#include "pw_status/status.h"
#include "pw_status/status_with_size.h"
#include "pw_string/string.h"

namespace pw::fuzzer {

template <typename T>
using Domain = fuzztest::Domain<T>;

////////////////////////////////////////////////////////////////
// Arbitrary domains
// Additional specializations are provided with the Pigweed domains.

/// @struct ArbitraryImpl
/// @fn Arbitrary
///
/// Produces values for fuzz target function parameters.
///
/// This defines a new template rather than using the `fuzztest` one directly in
/// order to facilitate specializations for Pigweed types.
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#arbitrary-domains
template <typename T, typename = void>
struct ArbitraryImpl {
  auto operator()() { return fuzztest::Arbitrary<T>(); }
};
template <typename T>
auto Arbitrary() {
  return ArbitraryImpl<T>()();
}

////////////////////////////////////////////////////////////////
// Numerical domains

/// Produces values from a closed interval.
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#numerical-domains
using fuzztest::InRange;

/// Like Arbitrary<T>(), but does not produce the zero value.
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#numerical-domains
using fuzztest::NonZero;

/// Produces numbers greater than zero.
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#numerical-domains
using fuzztest::Positive;

/// Produces the zero value and numbers greater than zero.
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#numerical-domains
using fuzztest::NonNegative;

/// Produces numbers less than zero.
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#numerical-domains
using fuzztest::Negative;

/// Produces the zero value and numbers less than zero.
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#numerical-domains
using fuzztest::NonPositive;

/// Produces floating points numbers that are neither infinity nor NaN.
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#numerical-domains
using fuzztest::Finite;

////////////////////////////////////////////////////////////////
// Character domains

/// Produces any char except '\0'.
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#character-domains
using fuzztest::NonZeroChar;

/// Alias for `InRange('0', '9')`.
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#character-domains
using fuzztest::NumericChar;

/// Alias for `InRange('a', 'z')`.
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#character-domains
using fuzztest::LowerChar;

/// Alias for `InRange('A', 'Z')`.
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#character-domains
using fuzztest::UpperChar;

/// Alias for `OneOf(LowerChar(), UpperChar())`.
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#character-domains
using fuzztest::AlphaChar;

/// Alias for `OneOf(AlphaChar(), NumericChar())`.
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#character-domains
using fuzztest::AlphaNumericChar;

/// Produces printable characters (`InRange<char>(32, 126)`).
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#character-domains
using fuzztest::PrintableAsciiChar;

/// Produces ASCII characters (`InRange<char>(0, 127)`).
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#character-domains
using fuzztest::AsciiChar;

////////////////////////////////////////////////////////////////
// Regular expression domains

// TODO: b/285775246 - Add support for `fuzztest::InRegexp`.
// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#inregexp-domains
// using fuzztest::InRegexp;

////////////////////////////////////////////////////////////////
// Enumerated domains

/// Produces values from an enumerated set.
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#elementof-domains
using fuzztest::ElementOf;

/// Produces combinations of binary flags from a provided list.
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#bitflagcombinationof-domains
using fuzztest::BitFlagCombinationOf;

////////////////////////////////////////////////////////////////
// Container domains

/// @struct ContainerOfImpl
/// @fn ContainerOf
///
/// Produces containers of elements provided by inner domains.
///
/// This defines a new template rather than using the `fuzztest` one directly in
/// order to specify the static container capacity as part of the container
/// type.
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#container-combinators
template <typename Container, typename = void>
struct ContainerOfImpl {
  template <int&... ExplicitArgumentBarrier, typename Inner>
  auto operator()(Inner inner) {
    return fuzztest::ContainerOf<Container>(std::move(inner))
        .WithMaxSize(Container{}.max_size());
  }
};
template <typename Container, int&... ExplicitArgumentBarrier, typename Inner>
auto ContainerOf(Inner inner) {
  return ContainerOfImpl<Container>()(std::move(inner));
}

namespace internal {

template <typename T, typename = void>
struct IsContainer : std::false_type {};

template <typename T>
struct IsContainer<T, std::void_t<decltype(T().begin(), T().end())>>
    : std::true_type {};

}  // namespace internal

/// Produces containers of at least one element provided by inner domains.
///
/// The container type is given by a template parameter.
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#container-combinators
using fuzztest::NonEmpty;

/// @struct UniqueElementsContainerOfImpl
/// @fn UniqueElementsContainerOf
///
/// Produces containers of unique elements provided by inner domains.
///
/// This defines a new template rather than using the `fuzztest` one directly in
/// order to specify the static container capacity as part of the container
/// type.
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#container-combinators
template <typename Container, typename = void>
struct UniqueElementsContainerOfImpl {
  template <int&... ExplicitArgumentBarrier, typename Inner>
  auto operator()(Inner inner) {
    return fuzztest::UniqueElementsContainerOf<Container>(std::move(inner))
        .WithMaxSize(Container{}.max_size());
  }
};
template <typename Container, int&... ExplicitArgumentBarrier, typename Inner>
auto UniqueElementsContainerOf(Inner inner) {
  return UniqueElementsContainerOfImpl<Container>()(std::move(inner));
}

////////////////////////////////////////////////////////////////
// Aggregate domains

/// Produces std::array<T>s of elements provided by inner domains.
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#container-combinators
using fuzztest::ArrayOf;

/// Specializes @cpp_class{pw::fuzzer::ContainerOfImpl} for arrays, which do not
/// need a maximum size applied.
///
/// @param[in]  inner   Domain the produces values of type `T`.
///
/// @retval     Domain that produces `std::array<T, kArraySize>`s.
template <typename T, size_t N>
struct ContainerOfImpl<std::array<T, N>> {
  template <int&... ExplicitArgumentBarrier, typename Inner>
  auto operator()(Inner inner) {
    return fuzztest::ContainerOf<std::array<T, N>>(std::move(inner));
  }
};

/// Produces user-defined structs.
///
/// The struct type is given by a template parameter.
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#structof
using fuzztest::StructOf;

/// Produces user-defined objects.
///
/// The class type is given by a template parameter.
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#constructorof
using fuzztest::ConstructorOf;

/// Produces `std::pair<T1, T2>`s from provided inner domains.
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#pairof
using fuzztest::PairOf;

/// Produces `std::tuple<T...>`s from provided inner domains.
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#tupleof
using fuzztest::TupleOf;

/// Produces `std::variant<T...>` from provided inner domains.
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#variantof
using fuzztest::VariantOf;

/// Produces `std::optional<T>` from provided inner domain.
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#optionalof
using fuzztest::OptionalOf;

/// Produces `std::optional<T>` from provided inner domain that is null.
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#optionalof
using fuzztest::NullOpt;

/// Produces `std::optional<T>` from provided inner domain that is not null.
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#optionalof
using fuzztest::NonNull;

////////////////////////////////////////////////////////////////
// Other miscellaneous domains

/// Produces values by choosing between provided inner domains.
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#oneof
using fuzztest::OneOf;

/// Produces values equal to the provided value.
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#oneof
using fuzztest::Just;

/// Produces values by applying a function to values from provided domains.
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#map
using fuzztest::Map;

/// Creates a domain by applying a function to values from provided domains.
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#flatmap
using fuzztest::FlatMap;

/// Produces values from a provided domain that will cause a provided predicate
/// to return true.
///
/// See
/// https://github.com/google/fuzztest/blob/main/doc/domains-reference.md#filter
using fuzztest::Filter;

////////////////////////////////////////////////////////////////
// pw_status-related types

/// Implementation of @cpp_func{pw::fuzzer::Arbitrary} for
/// @cpp_class{pw::Status}.
template <>
struct ArbitraryImpl<Status> {
  auto operator()() {
    return ConstructorOf<Status>(
        Map([](int code) { return static_cast<pw_Status>(code); },
            InRange<int>(PW_STATUS_OK, PW_STATUS_LAST)));
  }
};

/// Implementation of @cpp_func{pw::fuzzer::Arbitrary} for
/// @cpp_class{pw::StatusWithSize}.
template <>
struct ArbitraryImpl<StatusWithSize> {
  auto operator()() {
    return ConstructorOf<StatusWithSize>(Arbitrary<Status>(),
                                         Arbitrary<size_t>());
  }
};

/// Like @cpp_func{pw::fuzzer::Arbitrary<Status>}, except that
/// @cpp_func{pw::OkStatus} is filtered out.
inline auto NonOkStatus() {
  return ConstructorOf<pw::Status>(
      Map([](int code) { return static_cast<pw_Status>(code); },
          InRange<int>(PW_STATUS_CANCELLED, PW_STATUS_UNAUTHENTICATED)));
}

////////////////////////////////////////////////////////////////
// pw_result-related types

/// Returns a FuzzTest domain that produces @cpp_class{pw::Result}s.
///
/// The value produced may either be value produced by the given domain, or a
/// @cpp_class{pw::Status} indicating an error.
///
/// Alternatively, you can use `Arbitrary<Result<T>>`.
///
/// @param[in] inner  Domain that produces values of type `T`.
///
/// @retval    Domain that produces `Result<T>`s.
template <int&... ExplicitArgumentBarrier, typename Inner>
auto ResultOf(Inner inner) {
  return Map(
      [](std::optional<typename Inner::value_type> value, Status status) {
        if (value) {
          return Result<typename Inner::value_type>(*value);
        }
        return Result<typename Inner::value_type>(status);
      },
      OptionalOf(std::move(inner)),
      NonOkStatus());
}

/// Implementation of @cpp_func{pw::fuzzer::Arbitrary} for
/// @cpp_class{pw::Result}.
template <typename T>
struct ArbitraryImpl<Result<T>> {
  auto operator()() { return ResultOf(Arbitrary<T>()); }
};

////////////////////////////////////////////////////////////////
// pw_containers-related types

/// Returns a FuzzTest domain that produces @cpp_class{pw::Vector}s.
///
/// Use this in place of `fuzztest::VectorOf`. The vector's maximum size is set
/// by the template parameter.
///
/// Alternatively, you can use `Arbitrary<Vector<T, kMaxSize>>`.
///
/// @param[in] inner  Domain that produces values of type `T`.
///
/// @retval    Domain that produces `Vector<T>`s.
template <size_t kMaxSize, int&... ExplicitArgumentBarrier, typename Inner>
auto VectorOf(Inner inner) {
  return ContainerOf<Vector<typename Inner::value_type, kMaxSize>>(inner)
      .WithMaxSize(kMaxSize);
}

/// Implementation of @cpp_func{pw::fuzzer::Arbitrary} for
/// @cpp_class{pw::Vector}.
template <typename T, size_t kMaxSize>
struct ArbitraryImpl<Vector<T, kMaxSize>> {
  auto operator()() { return VectorOf<kMaxSize>(Arbitrary<T>()); }
};

/// Like `fuzztest::UniqueElementsVectorOf`, but uses a @cpp_class{pw::Vector}
/// in place of a `std::vector`.
///
/// @param[in]  inner   Domain the produces values for the vector.
///
/// @retval     Domain that produces `@cpp_class{pw::Vector}`s.
template <size_t kMaxSize, int&... ExplicitArgumentBarrier, typename Inner>
auto UniqueElementsVectorOf(Inner inner) {
  return UniqueElementsContainerOf<
      Vector<typename Inner::value_type, kMaxSize>>(std::move(inner));
}

/// Returns a FuzzTest domain that produces @cpp_class{pw::containers::Pair}s.
///
/// Use this in place of `fuzztest::PairOf` when working with
/// @cpp_class{pw::containers::FlatMap}s.
///
/// Alternatively, you can use `Arbitrary<pw::containers::Pair<K, V>>`.
///
/// @param[in] keys     Domain that produces values of type `K`.
/// @param[in] values   Domain that produces values of type `V`.
///
/// @retval    Domain that produces `containers::Pair<T>`s.
template <int&... ExplicitArgumentBarrier,
          typename KeyDomain,
          typename ValueDomain>
auto FlatMapPairOf(KeyDomain keys, ValueDomain values) {
  return StructOf<containers::Pair<typename KeyDomain::value_type,
                                   typename ValueDomain::value_type>>(
      std::move(keys), std::move(values));
}

/// Implementation of @cpp_func{pw::fuzzer::Arbitrary} for
/// @cpp_class{pw::containers::Pair}.
template <typename K, typename V>
struct ArbitraryImpl<containers::Pair<K, V>> {
  auto operator()() { return FlatMapPairOf(Arbitrary<K>(), Arbitrary<V>()); }
};

/// Transforms a domain that produces containers of keys and values into a
/// domain that produces @cpp_class{pw::containers::FlatMap}s
///
/// This method can be used to apply additional constraints to the set of keys
/// and/or values overall, e.g. by requiring all keys to be unique.
///
/// @param[in] keys     Domain that produces containers of keys.
/// @param[in] values   Domain that produces containers of values.
///
/// @retval    Domain that produces `containers::Pair<T>`s.
template <size_t kArraySize,
          int&... ExplicitArgumentBarrier,
          typename KeyDomain,
          typename ValueDomain>
auto MapToFlatMap(KeyDomain keys, ValueDomain values) {
  using ContainerK = typename KeyDomain::value_type;
  using ContainerV = typename ValueDomain::value_type;
  static_assert(internal::IsContainer<ContainerK>::value);
  static_assert(internal::IsContainer<ContainerV>::value);
  using K = typename ContainerK::value_type;
  using V = typename ContainerV::value_type;
  return Map(
      [](const ContainerK& keys_c, const ContainerV& vals_c) {
        auto key = keys_c.begin();
        auto val = vals_c.begin();
        std::array<containers::Pair<K, V>, kArraySize> pairs;
        for (auto& item : pairs) {
          PW_ASSERT(key != keys_c.end());
          PW_ASSERT(val != vals_c.end());
          item.first = *key++;
          item.second = *val++;
        }
        return pairs;
      },
      std::move(keys),
      std::move(values));
}

/// Returns a FuzzTest domain that produces
/// @cpp_class{pw::containers::FlatMap}s.
///
/// Use this in place of `fuzztest::MapOf` and/or `fuzztest::UnorderedMapOf`.
/// The map's size is set by the template parameter. The map is populated by
/// pairs of values from the given `KeyDomain` and `ValueDomain`.
///
/// Alternatively, you can use `Arbitrary<FlatMap<K, V, kArraySize>>`.
///
/// Note that neither approach returns a domain that produces `FlatMap<K< V>`s.
/// Such a domain is infeasible, since `FlatMap<K, V>`s are not movable or
/// copyable. Instead, these functions return domains that produce arrays of
/// `Pair<K, V>`s that can be implicitly converted to `FlatMap<K, V>`s.
///
/// @param[in] keys    Domain that produces map keys.
/// @param[in] values  Domain that produces map values.
///
/// @retval    Domain that produces `std::array<T, kArraySize>`s.
template <size_t kArraySize,
          int&... ExplicitArgumentBarrier,
          typename KeyDomain,
          typename ValueDomain>
auto FlatMapOf(KeyDomain keys, ValueDomain values) {
  return ArrayOf<kArraySize>(FlatMapPairOf(std::move(keys), std::move(values)));
}

/// Implementation of @cpp_func{pw::fuzzer::Arbitrary} for
/// @cpp_class{pw::containers::FlatMap}.
template <typename K, typename V, size_t kArraySize>
struct ArbitraryImpl<containers::FlatMap<K, V, kArraySize>> {
  auto operator()() {
    return FlatMapOf<kArraySize>(Arbitrary<K>(), Arbitrary<V>());
  }
};

/// Implementation of @cpp_func{pw::fuzzer::ContainerOf} for
/// @cpp_class{pw::containers::FlatMap}.
///
/// Since flat maps have a static capacity, the returned domains do not produce
/// FuzzTest containers, but aggregates. As a result, container methods such as
/// `WithMaxSize` cannot be applied. Use @cpp_func{pw::fuzzer::MapToFlatMap}
/// instead to apply constraints to the set of keys and values.
///
/// @param[in]  inner   Domain the produces @cpp_class{pw::containers::Pair}s.
///
/// @retval     Domain that produces `@cpp_class{pw::containers::FlatMap}`s.
template <typename K, typename V, size_t kArraySize>
struct ContainerOfImpl<containers::FlatMap<K, V, kArraySize>> {
  template <int&... ExplicitArgumentBarrier, typename Inner>
  auto operator()(Inner inner) {
    static_assert(
        std::is_same_v<typename Inner::value_type, containers::Pair<K, V>>,
        "The domain passed to `pw::fuzzer::ContainerOf<FlatMap<K, V>>` must "
        "produce `pw::containers::Pair<K, V>`s. An example of a valid domain is"
        "`pw::fuzzer::FlatMapPairOf(FooDomain<K>(), BarDomain<V>())`");
    return ArrayOf<kArraySize>(std::move(inner));
  }
};

/// Transforms a domain that produces containers into a domain that produces
/// @cpp_class{pw::BasicInlineDeque}s.
///
/// The domains returned by @cpp_func{pw::fuzzer::BasicDequeOf} and
/// `Arbitrary<BasicInlineDeque>` do not create FuzzTest containers. This method
/// can be used to apply container methods such as `WithMinSize` or
/// `UniqueElementsContainerOf` before building a deque from that container.
///
/// @param[in] inner  Domain that produces containers.
///
/// @retval    Domain that produces `@cpp_class{pw::BasicInlineDeque}`s.
template <typename SizeType,
          size_t kCapacity,
          int&... ExplicitArgumentBarrier,
          typename Inner>
auto MapToBasicDeque(Inner inner) {
  using Container = typename Inner::value_type;
  static_assert(internal::IsContainer<Container>::value);
  using T = typename Container::value_type;
  return Map(
      [](const Container& items) {
        return BasicInlineDeque<T, SizeType, kCapacity>(items.begin(),
                                                        items.end());
      },
      std::move(inner));
}

/// Returns a FuzzTest domain that produces @cpp_class{pw::BasicInlineDeque}s.
///
/// Use this or @cpp_func{pw::fuzzer::DequeOf} in place of `fuzztest::DequeOf`.
/// The deque's maximum size is set by the template parameter.
///
/// Alternatively, you can use `Arbitrary<BasicInlineDeque<T, kCapacity>>`.
///
/// @param[in] inner  Domain that produces values of type `T`.
///
/// @retval    Domain that produces values of type
///            `BasicInlineDeque<T, SizeType, kCapacity>`.
template <typename SizeType,
          size_t kCapacity,
          int&... ExplicitArgumentBarrier,
          typename Inner>
auto BasicDequeOf(Inner inner) {
  return MapToBasicDeque<SizeType, kCapacity>(
      VectorOf<kCapacity>(std::move(inner)));
}

// BasicDequeFrom(VectorOf<kCapacity>(Arbitrary<int>()))
/// Implementation of @cpp_func{pw::fuzzer::Arbitrary} for
/// @cpp_class{pw::BasicInlineDeque}.
template <typename T, typename SizeType, size_t kCapacity>
struct ArbitraryImpl<BasicInlineDeque<T, SizeType, kCapacity>> {
  auto operator()() {
    return BasicDequeOf<SizeType, kCapacity>(Arbitrary<T>());
  }
};

/// Implementation of @cpp_func{pw::fuzzer::ContainerOf} for
/// @cpp_class{pw::containers::BasicInlineDeque}.
///
/// Since inline deques have a static capacity, the returned domains do not
/// produce FuzzTest containers, but aggregates. As a result, container methods
/// such as `WithMaxSize` cannot be applied. Instead, use
/// @cpp_func{pw::fuzzer::MapToDeque} or @cpp_func{pw::fuzzer::MapToBasicDeque}
/// to apply constraints to the set of keys and values.
///
/// @param[in]  inner   Domain the produces values of type `T`.
///
/// @retval     Domain that produces `@cpp_class{pw::BasicInlineDeque}`s.
template <typename T, typename SizeType, size_t kCapacity>
struct ContainerOfImpl<BasicInlineDeque<T, SizeType, kCapacity>> {
  template <int&... ExplicitArgumentBarrier, typename Inner>
  auto operator()(Inner inner) {
    return BasicDequeOf<SizeType, kCapacity>(std::move(inner));
  }
};

/// Transforms a domain that produces containers into a domain that produces
/// @cpp_class{pw::InlineDeque}s.
///
/// The domains returned by @cpp_func{pw::fuzzer::equeOf} and
/// `Arbitrary<InlineDeque>` do not create FuzzTest containers. This method
/// can be used to apply container methods such as `WithMinSize` or
/// `UniqueElementsContainerOf` before building a deque from that container.
///
/// @param[in] inner  Domain that produces containers.
///
/// @retval    Domain that produces `@cpp_class{pw::InlineDeque}`s.
template <size_t kCapacity, int&... ExplicitArgumentBarrier, typename Inner>
auto MapToDeque(Inner inner) {
  return MapToBasicDeque<uint16_t, kCapacity>(std::move(inner));
}

/// Returns a FuzzTest domain that produces @cpp_class{pw::InlineDeque}s.
///
/// Use this or @cpp_func{pw::fuzzer::BasicDequeOf} in place of
/// `fuzztest::DequeOf`. The deque's maximum size is set by the template
/// parameter.
///
/// Alternatively, you can use `Arbitrary<InlineDeque<T, kCapacity>>`.
///
/// @param[in] inner  Domain that produces values of type `T`.
///
/// @retval    Domain that produces values of type `InlineDeque<T, kCapacity>`.
template <size_t kCapacity, int&... ExplicitArgumentBarrier, typename Inner>
auto DequeOf(Inner inner) {
  return BasicDequeOf<uint16_t, kCapacity>(std::move(inner));
}

/// Implementation of @cpp_func{pw::fuzzer::Arbitrary} for
/// @cpp_class{pw::InlineDeque}.
template <typename T, size_t kCapacity>
struct ArbitraryImpl<InlineDeque<T, kCapacity>> {
  auto operator()() { return DequeOf<kCapacity>(Arbitrary<T>()); }
};

/// Transforms a domain that produces containers into a domain that produces
/// @cpp_class{pw::BasicInlineQueue}s.
///
/// The domains returned by @cpp_func{pw::fuzzer::BasicQueueOf} and
/// `Arbitrary<BasicInlineQueue>` do not create FuzzTest containers. This method
/// can be used to apply container methods such as `WithMinSize` or
/// `UniqueElementsContainerOf` before building a queue from that container.
///
/// @param[in] inner  Domain that produces containers.
///
/// @retval    Domain that produces `@cpp_class{pw::BasicInlineQueue}`s.
template <typename SizeType,
          size_t kCapacity,
          int&... ExplicitArgumentBarrier,
          typename Inner>
auto MapToBasicQueue(Inner inner) {
  using Container = typename Inner::value_type;
  static_assert(internal::IsContainer<Container>::value);
  using T = typename Container::value_type;
  return Map(
      [](const Container& items) {
        return BasicInlineQueue<T, SizeType, kCapacity>(items.begin(),
                                                        items.end());
      },
      std::move(inner));
}

/// Returns a FuzzTest domain that produces @cpp_class{pw::BasicInlineQueue}s.
///
/// Use this, @cpp_func{pw::fuzzer::QueueOf}, or
/// @cpp_func{pw::fuzzer::ScopedListOf} in place of `fuzztest::ListOf`. The
/// queue's maximum size is set by the template parameter.
///
/// Alternatively, you can use `Arbitrary<BasicInlineQueue<T, kCapacity>>`.
///
/// @param[in] inner  Domain that produces values of type `T`.
///
/// @retval    Domain that produces values of type
///            `BasicInlineQueue<T, SizeType, kCapacity>`.
template <typename SizeType,
          size_t kCapacity,
          int&... ExplicitArgumentBarrier,
          typename Inner>
auto BasicQueueOf(Inner inner) {
  return MapToBasicQueue<SizeType, kCapacity>(
      VectorOf<kCapacity>(std::move(inner)));
}

/// Implementation of @cpp_func{pw::fuzzer::Arbitrary} for
/// @cpp_class{pw::BasicInlineQueue}.
template <typename T, typename SizeType, size_t kCapacity>
struct ArbitraryImpl<BasicInlineQueue<T, SizeType, kCapacity>> {
  auto operator()() {
    return BasicQueueOf<SizeType, kCapacity>(Arbitrary<T>());
  }
};

/// Implementation of @cpp_func{pw::fuzzer::ContainerOf} for
/// @cpp_class{pw::containers::BasicInlineQueue}.
///
/// Since inline queues have a static capacity, the returned domains do not
/// produce FuzzTest containers, but aggregates. As a result, container methods
/// such as `WithMaxSize` cannot be applied. Instead, use
/// @cpp_func{pw::fuzzer::MapToQueue} or @cpp_func{pw::fuzzer::MapToBasicQueue}
/// to apply constraints to the set of keys and values.
///
/// @param[in]  inner   Domain the produces values of type `T`.
///
/// @retval     Domain that produces `@cpp_class{pw::BasicInlineQueue}`s.
template <typename T, typename SizeType, size_t kCapacity>
struct ContainerOfImpl<BasicInlineQueue<T, SizeType, kCapacity>> {
  template <int&... ExplicitArgumentBarrier, typename Inner>
  auto operator()(Inner inner) {
    return BasicQueueOf<SizeType, kCapacity>(std::move(inner));
  }
};

/// Transforms a domain that produces containers into a domain that produces
/// @cpp_class{pw::InlineQueue}s.
///
/// The domains returned by @cpp_func{pw::fuzzer::QueueOf} and
/// `Arbitrary<InlineQueue>` do not create FuzzTest containers. This method
/// can be used to apply container methods such as `WithMinSize` or
/// `UniqueElementsContainerOf` before building a queue from that container.
///
/// @param[in] inner  Domain that produces containers.
///
/// @retval    Domain that produces `@cpp_class{pw::InlineQueue}`s.
template <size_t kCapacity, int&... ExplicitArgumentBarrier, typename Inner>
auto MapToQueue(Inner inner) {
  return MapToBasicQueue<uint16_t, kCapacity>(std::move(inner));
}

/// Returns a FuzzTest domain that produces @cpp_class{pw::InlineQueue}s.
///
/// Use this, @cpp_func{pw::fuzzer::BasicQueueOf}, or
/// @cpp_func{pw::fuzzer::ScopedListOf} in place of `fuzztest::ListOf`. The
/// queue's maximum size is set by the template parameter.
///
/// Alternatively, you can use `Arbitrary<InlineQueue<T, kCapacity>>`.
///
/// @param[in] inner  Domain that produces values of type `T`.
///
/// @retval    Domain that produces values of type `InlineQueue<T, kCapacity>`.
template <size_t kCapacity, int&... ExplicitArgumentBarrier, typename Inner>
auto QueueOf(Inner inner) {
  return BasicQueueOf<uint16_t, kCapacity>(std::move(inner));
}

/// Implementation of @cpp_func{pw::fuzzer::Arbitrary} for
/// @cpp_class{pw::InlineQueue}.
template <typename T, size_t kCapacity>
struct ArbitraryImpl<InlineQueue<T, kCapacity>> {
  auto operator()() { return QueueOf<kCapacity>(Arbitrary<T>()); }
};

// Supporting types and functions for creating `IntrusiveList<T>`s.
namespace internal {

/// Construct an `Item` and emplace it in the given `Vector`.
///
/// The `Item` is constructed using arguments passed as a tuple.
/// This should only be called by the overload that generates the index sequence
/// used to expand the tuple.
///
/// @param[out] vector The vector to add the item to.
/// @param[in]  args   A tuple of arguments to pass to the constructor of `T`.
/// @param[in]  (n/a)  An sequence used to index the tuple.
template <int&... ExplicitArgumentBarrier,
          typename T,
          typename Args,
          size_t... Index>
void EmplaceItem(Vector<T>& vector,
                 const Args& args,
                 std::index_sequence<Index...>) {
  vector.emplace_back(std::get<Index>(args)...);
}

/// Construct an `Item` and emplace it in the given `Vector`.
///
/// The `Item` is constructed using arguments passed as a tuple.
///
/// @param[out] vector The vector to add the item to.
/// @param[in]  args   A tuple of arguments to pass to the constructor of `T`.
template <int&... ExplicitArgumentBarrier, typename T, typename Args>
void EmplaceItem(Vector<T>& vector, const Args& args) {
  EmplaceItem(
      vector,
      args,
      std::make_index_sequence<std::tuple_size<std::decay_t<Args>>::value>{});
}

}  // namespace internal

/// Associates an `IntrusiveList<T>` with a `Vector<T>` that stores its `Item`s.
///
/// The `Item`s are constructed from a sequence of argument tuples passed to
// constructor.
template <typename T, size_t kMaxSize>
class ScopedList {
 public:
  ~ScopedList() { list_.clear(); }

  template <int&... ExplicitArgumentBarrier, typename Tuple>
  explicit ScopedList(const Vector<Tuple>& arg_tuples) {
    for (const auto& arg_tuple : arg_tuples) {
      items_.emplace_back(std::make_from_tuple<T>(arg_tuple));
      // internal::EmplaceItem(items_, arg);
      list_.push_back(items_.back());
    }
  }

  ScopedList(const ScopedList& other) = delete;
  ScopedList& operator=(const ScopedList& other) = delete;

  ScopedList(ScopedList&& other) { *this = std::move(other); }
  ScopedList& operator=(ScopedList&& other) {
    list_.clear();
    other.list_.clear();
    items_ = std::move(other.items_);
    list_.assign(items_.begin(), items_.end());
    return *this;
  }

  const IntrusiveList<T>& list() const { return list_; }

 private:
  IntrusiveList<T> list_;
  Vector<T, kMaxSize> items_;
};

/// Transforms a domain that produces containers into a domain that produces
/// @cpp_class{pw::fuzzer::ScopedList}s.
///
/// The domains returned by @cpp_func{pw::fuzzer::ScopedListOf} do not create
/// FuzzTest containers. This method can be used to apply container methods such
/// as `WithMinSize` or `UniqueElementsContainerOf` before building an intrusive
/// list from that container.
///
/// @param[in] inner  Domain that produces containers.
///
/// @retval    Domain that produces `@cpp_class{pw::fuzzer::ScopedList}`s.
template <typename T,
          size_t kMaxSize,
          int&... ExplicitArgumentBarrier,
          typename Inner>
auto MapToScopedList(Inner inner) {
  using Container = typename Inner::value_type;
  static_assert(internal::IsContainer<Container>::value);
  using Tuple = typename Container::value_type;
  static_assert(
      std::is_same_v<T, decltype(std::make_from_tuple<T>(Tuple()))>,
      "The domain passed to `pw::fuzzer::MapToScopedList<T, kMaxSize>>` must "
      "produce `std::tuple`s of constructor arguments for `T`, e.g. using "
      "`pw::fuzzer::TupleOf`.");
  return ConstructorOf<ScopedList<T, kMaxSize>>(std::move(inner));
}

/// Returns a FuzzTest domain that produces @cpp_class{pw::fuzzer::ScopedList}s.
///
/// Use this, @cpp_func{pw::fuzzer::BasicQueueOf}, or
/// @cpp_func{pw::fuzzer::QueueOf} in place of `fuzztest::ListOf`. The list's
/// maximum size is set by the template parameter.
///
/// @param[in] inner...  Domains that produces `IntrusiveList<T>::Item`s.
///
/// @retval    Domain that produces `ScopedList<T, kMaxSize>`s.
template <typename T,
          size_t kMaxSize,
          int&... ExplicitArgumentBarrier,
          typename... Inner>
auto ScopedListOf(Inner... inner) {
  return MapToScopedList<T, kMaxSize>(
      VectorOf<kMaxSize>(TupleOf(std::move(inner)...)));
}

////////////////////////////////////////////////////////////////
// pw_string-related types

/// Returns a FuzzTest domain that produces @cpp_class{pw::InlineBasicString}s.
///
/// Use this in place of `fuzztest::StringOf`. The characters of the string
/// are drawn from the given domain. The string capacity is given by the
/// template parameter.
///
/// Alternatively, you can use `Arbitrary<InlineString<kCapacity>>`.
///
/// @param[in] inner  Domain that produces values of a character type.
///
/// @retval    Domain that produces `InlineBasicString<kCapacity>`s.
template <size_t kCapacity, int&... ExplicitArgumentBarrier, typename Inner>
auto StringOf(Inner inner) {
  return ContainerOf<InlineBasicString<typename Inner::value_type, kCapacity>>(
             inner)
      .WithMaxSize(kCapacity);
}

/// Implementation of @cpp_func{pw::fuzzer::Arbitrary} for
/// @cpp_class{pw::InlineBasicString}.
template <typename T, size_t kCapacity>
struct ArbitraryImpl<InlineBasicString<T, kCapacity>> {
  auto operator()() { return StringOf<kCapacity>(Arbitrary<T>()); }
};

/// Returns a FuzzTest domain that produces @cpp_class{pw::InlineString}s.
///
/// Use this in place of `fuzztest::String`. The string capacity is given by the
/// template parameter.
///
/// @retval    Domain that produces `InlineString<kCapacity>`s.
template <size_t kCapacity>
auto String() {
  return StringOf<kCapacity>(Arbitrary<char>());
}

/// Returns a FuzzTest domain that produces @cpp_class{pw::InlineString}s
/// containing only ASCII characters.
///
/// Use this in place of `fuzztest::AsciiString`. The string capacity is given
/// by the template parameter.
///
/// @retval    Domain that produces `InlineString<kCapacity>`s.
template <size_t kCapacity>
auto AsciiString() {
  return StringOf<kCapacity>(AsciiChar());
}

/// Returns a FuzzTest domain that produces @cpp_class{pw::InlineString}s
/// containing only printable ASCII characters.
///
/// Use this in place of `fuzztest::PrintableAsciiString`. The string capacity
/// is given by the template parameter.
///
/// @retval    Domain that produces printable `InlineString<kCapacity>`s.
template <size_t kCapacity>
auto PrintableAsciiString() {
  return StringOf<kCapacity>(PrintableAsciiChar());
}

}  // namespace pw::fuzzer