bsrule.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # Copyright 2023 Modelling, Simulation and Design Lab (MSDL)
  2. # at the University of Antwerp (http://msdl.uantwerpen.be/).
  3. #
  4. # Licensed under the GNU Public License v3 (the "License");
  5. # you may not use this file except in compliance with the
  6. # License. You may obtain a copy of the License at
  7. # https://www.gnu.org/licenses/gpl-3.0.en.html
  8. #
  9. # Unless required by applicable law or agreed to in writing,
  10. # software distributed under the License is distributed on an
  11. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
  12. # either express or implied. See the License for the specific
  13. # language governing permissions and limitations under the
  14. # License.
  15. from pytcore.util.infinity import INFINITY
  16. from pytcore.tcore.composer import Composer
  17. from pytcore.rules.brule import BRule
  18. class BSRule(Composer):
  19. '''
  20. Selects a branch in which the matcher succeeds, as long as matches can be found.
  21. '''
  22. def __init__(self, branches, max_iterations=INFINITY):
  23. '''
  24. Selects a branch in which the matcher succeeds, as long as matches can be found.
  25. @param branches: A list of ARules.
  26. @param max_iterations: The maximum number of times to apply the transformation.
  27. '''
  28. super(BSRule, self).__init__()
  29. self.brule = BRule(branches)
  30. self.max_iterations = max_iterations
  31. self.iterations = 0
  32. def packet_in(self, packet):
  33. self.exception = None
  34. self.is_success = False
  35. while self.iterations < self.max_iterations:
  36. # Re-apply the BRule
  37. packet = self.brule.packet_in(packet)
  38. if not self.brule.is_success:
  39. self.exception = self.brule.exception
  40. return packet
  41. else:
  42. self.is_success = True
  43. self.iterations += 1
  44. return packet