day3_common.carbon 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. // https://adventofcode.com/2024/day/3
  5. library "day3_common";
  6. import library "io_utils";
  7. // Reads "mul(a,b)", and returns (true, a, b).
  8. // On error, stops before the first invalid character and returns (false, 0, 0).
  9. // TODO: -> Optional((i32, i32))
  10. fn ReadMul() -> (bool, i32, i32) {
  11. var a: i32;
  12. var b: i32;
  13. if (ConsumeChar('m') and ConsumeChar('u') and ConsumeChar('l') and
  14. ConsumeChar('(') and ReadInt(ref a) and ConsumeChar(',') and
  15. ReadInt(ref b) and ConsumeChar(')')) {
  16. return (true, a, b);
  17. }
  18. return (false, 0, 0);
  19. }
  20. // Reads "do()" or "don't()", and returns (true, was_do).
  21. // On error, stops before the first invalid character and returns (false, false).
  22. fn ReadDoOrDont() -> (bool, bool) {
  23. // "do"
  24. if (not ConsumeChar('d') or not ConsumeChar('o')) {
  25. return (false, false);
  26. }
  27. var do: bool = true;
  28. // "n't"
  29. if (ConsumeChar('n')) {
  30. if (not ConsumeChar('\'') or not ConsumeChar('t')) {
  31. return (false, false);
  32. }
  33. do = false;
  34. }
  35. // "()"
  36. if (not ConsumeChar('(') or not ConsumeChar(')')) {
  37. return (false, false);
  38. }
  39. return (true, do);
  40. }