String.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. //===-- String.cpp - SPIR-V Strings -----------------------------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #include "clang/SPIRV/String.h"
  10. #include "llvm/llvm_assert/assert.h"
  11. namespace clang {
  12. namespace spirv {
  13. namespace string {
  14. /// \brief Reinterprets a given string as sequence of words.
  15. std::vector<uint32_t> encodeSPIRVString(llvm::StringRef strChars) {
  16. // Initialize all words to 0.
  17. size_t numChars = strChars.size();
  18. std::vector<uint32_t> result(numChars / 4 + 1, 0);
  19. // From the SPIR-V spec, literal string is
  20. //
  21. // A nul-terminated stream of characters consuming an integral number of
  22. // words. The character set is Unicode in the UTF-8 encoding scheme. The UTF-8
  23. // octets (8-bit bytes) are packed four per word, following the little-endian
  24. // convention (i.e., the first octet is in the lowest-order 8 bits of the
  25. // word). The final word contains the string's nul-termination character (0),
  26. // and all contents past the end of the string in the final word are padded
  27. // with 0.
  28. //
  29. // So the following works on little endian machines.
  30. char *strDest = reinterpret_cast<char *>(result.data());
  31. strncpy(strDest, strChars.data(), numChars);
  32. return result;
  33. }
  34. /// \brief Reinterprets the given vector of 32-bit words as a string.
  35. /// Expectes that the words represent a NULL-terminated string.
  36. /// Assumes Little Endian architecture.
  37. std::string decodeSPIRVString(llvm::ArrayRef<uint32_t> strWords) {
  38. if (!strWords.empty()) {
  39. return reinterpret_cast<const char *>(strWords.data());
  40. }
  41. return "";
  42. }
  43. } // end namespace string
  44. } // end namespace spirv
  45. } // end namespace clang