string_util.cc 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /*
  2. * Copyright 2017 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "Firestore/Port/string_util.h"
  17. #include <leveldb/db.h>
  18. namespace Firestore {
  19. std::string PrefixSuccessor(leveldb::Slice prefix) {
  20. // We can increment the last character in the string and be done
  21. // unless that character is 255 (0xff), in which case we have to erase the
  22. // last character and increment the previous character, unless that
  23. // is 255, etc. If the string is empty or consists entirely of
  24. // 255's, we just return the empty string.
  25. std::string limit(prefix.data(), prefix.size());
  26. while (!limit.empty()) {
  27. size_t index = limit.length() - 1;
  28. if (limit[index] == '\xff') { // char literal avoids signed/unsigned.
  29. limit.erase(index);
  30. } else {
  31. limit[index]++;
  32. break;
  33. }
  34. }
  35. return limit;
  36. }
  37. std::string ImmediateSuccessor(leveldb::Slice s) {
  38. // Return the input string, with an additional NUL byte appended.
  39. std::string out;
  40. out.reserve(s.size() + 1);
  41. out.append(s.data(), s.size());
  42. out.push_back('\0');
  43. return out;
  44. }
  45. } // namespace Firestore