ByteSequences.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. * Copyright (c) 2022, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/CharacterTypes.h>
  7. #include <LibWeb/Infra/ByteSequences.h>
  8. namespace Web::Infra {
  9. // https://infra.spec.whatwg.org/#byte-lowercase
  10. void byte_lowercase(ByteBuffer& bytes)
  11. {
  12. // To byte-lowercase a byte sequence, increase each byte it contains, in the range 0x41 (A) to 0x5A (Z), inclusive, by 0x20.
  13. for (size_t i = 0; i < bytes.size(); ++i)
  14. bytes[i] = to_ascii_lowercase(bytes[i]);
  15. }
  16. // https://infra.spec.whatwg.org/#byte-uppercase
  17. void byte_uppercase(ByteBuffer& bytes)
  18. {
  19. // To byte-uppercase a byte sequence, subtract each byte it contains, in the range 0x61 (a) to 0x7A (z), inclusive, by 0x20.
  20. for (size_t i = 0; i < bytes.size(); ++i)
  21. bytes[i] = to_ascii_uppercase(bytes[i]);
  22. }
  23. // https://infra.spec.whatwg.org/#byte-sequence-starts-with
  24. bool is_prefix_of(ReadonlyBytes potential_prefix, ReadonlyBytes input)
  25. {
  26. // "input starts with potentialPrefix" can be used as a synonym for "potentialPrefix is a prefix of input".
  27. return input.starts_with(potential_prefix);
  28. }
  29. // https://infra.spec.whatwg.org/#byte-less-than
  30. bool is_byte_less_than(ReadonlyBytes a, ReadonlyBytes b)
  31. {
  32. // 1. If b is a prefix of a, then return false.
  33. if (is_prefix_of(b, a))
  34. return false;
  35. // 2. If a is a prefix of b, then return true.
  36. if (is_prefix_of(a, b))
  37. return true;
  38. // 3. Let n be the smallest index such that the nth byte of a is different from the nth byte of b.
  39. // (There has to be such an index, since neither byte sequence is a prefix of the other.)
  40. // 4. If the nth byte of a is less than the nth byte of b, then return true.
  41. // 5. Return false.
  42. for (size_t i = 0; i < a.size(); ++i) {
  43. if (a[i] != b[i])
  44. return a[i] < b[i];
  45. }
  46. VERIFY_NOT_REACHED();
  47. }
  48. }