StringUtils.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using Ryujinx.HLE.HOS;
  2. using System;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. namespace Ryujinx.HLE.Utilities
  8. {
  9. static class StringUtils
  10. {
  11. public static byte[] GetFixedLengthBytes(string inputString, int size, Encoding encoding)
  12. {
  13. inputString = inputString + "\0";
  14. int bytesCount = encoding.GetByteCount(inputString);
  15. byte[] output = new byte[size];
  16. if (bytesCount < size)
  17. {
  18. encoding.GetBytes(inputString, 0, inputString.Length, output, 0);
  19. }
  20. else
  21. {
  22. int nullSize = encoding.GetByteCount("\0");
  23. output = encoding.GetBytes(inputString);
  24. Array.Resize(ref output, size - nullSize);
  25. output = output.Concat(encoding.GetBytes("\0")).ToArray();
  26. }
  27. return output;
  28. }
  29. public static byte[] HexToBytes(string hexString)
  30. {
  31. //Ignore last charactor if HexLength % 2 != 0.
  32. int bytesInHex = hexString.Length / 2;
  33. byte[] output = new byte[bytesInHex];
  34. for (int index = 0; index < bytesInHex; index++)
  35. {
  36. output[index] = byte.Parse(hexString.Substring(index * 2, 2), NumberStyles.HexNumber);
  37. }
  38. return output;
  39. }
  40. public static string ReadUtf8String(ServiceCtx context, int index = 0)
  41. {
  42. long position = context.Request.PtrBuff[index].Position;
  43. long size = context.Request.PtrBuff[index].Size;
  44. using (MemoryStream ms = new MemoryStream())
  45. {
  46. while (size-- > 0)
  47. {
  48. byte value = context.Memory.ReadByte(position++);
  49. if (value == 0)
  50. {
  51. break;
  52. }
  53. ms.WriteByte(value);
  54. }
  55. return Encoding.UTF8.GetString(ms.ToArray());
  56. }
  57. }
  58. }
  59. }