1193323Sed//===-- llvm/ADT/SetOperations.h - Generic Set Operations -------*- C++ -*-===//
2193323Sed//
3353358Sdim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4353358Sdim// See https://llvm.org/LICENSE.txt for license information.
5353358Sdim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6193323Sed//
7193323Sed//===----------------------------------------------------------------------===//
8193323Sed//
9193323Sed// This file defines generic set operations that may be used on set's of
10193323Sed// different types, and different element types.
11193323Sed//
12193323Sed//===----------------------------------------------------------------------===//
13193323Sed
14193323Sed#ifndef LLVM_ADT_SETOPERATIONS_H
15193323Sed#define LLVM_ADT_SETOPERATIONS_H
16193323Sed
17193323Sednamespace llvm {
18193323Sed
19193323Sed/// set_union(A, B) - Compute A := A u B, return whether A changed.
20193323Sed///
21193323Sedtemplate <class S1Ty, class S2Ty>
22193323Sedbool set_union(S1Ty &S1, const S2Ty &S2) {
23193323Sed  bool Changed = false;
24193323Sed
25193323Sed  for (typename S2Ty::const_iterator SI = S2.begin(), SE = S2.end();
26193323Sed       SI != SE; ++SI)
27193323Sed    if (S1.insert(*SI).second)
28193323Sed      Changed = true;
29193323Sed
30193323Sed  return Changed;
31193323Sed}
32193323Sed
33193323Sed/// set_intersect(A, B) - Compute A := A ^ B
34193323Sed/// Identical to set_intersection, except that it works on set<>'s and
35193323Sed/// is nicer to use.  Functionally, this iterates through S1, removing
36193323Sed/// elements that are not contained in S2.
37193323Sed///
38193323Sedtemplate <class S1Ty, class S2Ty>
39193323Sedvoid set_intersect(S1Ty &S1, const S2Ty &S2) {
40193323Sed   for (typename S1Ty::iterator I = S1.begin(); I != S1.end();) {
41296417Sdim     const auto &E = *I;
42193323Sed     ++I;
43193323Sed     if (!S2.count(E)) S1.erase(E);   // Erase element if not in S2
44193323Sed   }
45193323Sed}
46193323Sed
47193323Sed/// set_difference(A, B) - Return A - B
48193323Sed///
49193323Sedtemplate <class S1Ty, class S2Ty>
50193323SedS1Ty set_difference(const S1Ty &S1, const S2Ty &S2) {
51193323Sed  S1Ty Result;
52193323Sed  for (typename S1Ty::const_iterator SI = S1.begin(), SE = S1.end();
53193323Sed       SI != SE; ++SI)
54193323Sed    if (!S2.count(*SI))       // if the element is not in set2
55193323Sed      Result.insert(*SI);
56193323Sed  return Result;
57193323Sed}
58193323Sed
59193323Sed/// set_subtract(A, B) - Compute A := A - B
60193323Sed///
61193323Sedtemplate <class S1Ty, class S2Ty>
62193323Sedvoid set_subtract(S1Ty &S1, const S2Ty &S2) {
63193323Sed  for (typename S2Ty::const_iterator SI = S2.begin(), SE = S2.end();
64193323Sed       SI != SE; ++SI)
65193323Sed    S1.erase(*SI);
66193323Sed}
67193323Sed
68193323Sed} // End llvm namespace
69193323Sed
70193323Sed#endif
71