Advertisement
Guest User

Untitled

a guest
Apr 24th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. static void Main(string[] args)
  2. {
  3. // Allocate the buffer on the stack (therefore not managed by the GC)
  4. Span<char> buffer = stackalloc char[20];
  5.  
  6. // Ask for the password
  7. Console.Write("Type a password: ");
  8. TypePassword(buffer, 0);
  9. Console.WriteLine();
  10.  
  11. // Unsafe since transformed in string; real usage would avoid that
  12. Console.WriteLine($"Your password: {buffer.ToString()}");
  13.  
  14. // Flush the buffer
  15. Flush(buffer);
  16.  
  17. // Unsafe since transformed in string; real usage would avoid that
  18. Console.WriteLine($"Flushed buffer: {buffer.ToString()}");
  19.  
  20. Console.Read();
  21. }
  22.  
  23. /// <remarks>
  24. /// Pray for tailrec optimization.
  25. /// </remarks>
  26. static Span<char> TypePassword(Span<char> buffer, int i)
  27. {
  28. if (i > buffer.Length) return buffer;
  29.  
  30. switch (Console.ReadKey(intercept: true))
  31. {
  32. // Displayable character
  33. case var key when !char.IsControl(key.KeyChar):
  34. buffer[i] = key.KeyChar;
  35. return TypePassword(buffer, i + 1);
  36.  
  37. // Backspace
  38. case var key when key.Key == ConsoleKey.Backspace && i > 0:
  39. buffer[i] = (char)0;
  40. return TypePassword(buffer, i - 1);
  41.  
  42. // Validation
  43. case var key when key.Key == ConsoleKey.Enter:
  44. return buffer;
  45.  
  46. default:
  47. return TypePassword(buffer, i);
  48. }
  49. }
  50.  
  51. static void Flush<T>(Span<T> span) where T: new()
  52. {
  53. span.Fill(new T());
  54. }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement