Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- static void Main(string[] args)
- {
- // Allocate the buffer on the stack (therefore not managed by the GC)
- Span<char> buffer = stackalloc char[20];
- // Ask for the password
- Console.Write("Type a password: ");
- TypePassword(buffer, 0);
- Console.WriteLine();
- // Unsafe since transformed in string; real usage would avoid that
- Console.WriteLine($"Your password: {buffer.ToString()}");
- // Flush the buffer
- Flush(buffer);
- // Unsafe since transformed in string; real usage would avoid that
- Console.WriteLine($"Flushed buffer: {buffer.ToString()}");
- Console.Read();
- }
- /// <remarks>
- /// Pray for tailrec optimization.
- /// </remarks>
- static Span<char> TypePassword(Span<char> buffer, int i)
- {
- if (i > buffer.Length) return buffer;
- switch (Console.ReadKey(intercept: true))
- {
- // Displayable character
- case var key when !char.IsControl(key.KeyChar):
- buffer[i] = key.KeyChar;
- return TypePassword(buffer, i + 1);
- // Backspace
- case var key when key.Key == ConsoleKey.Backspace && i > 0:
- buffer[i] = (char)0;
- return TypePassword(buffer, i - 1);
- // Validation
- case var key when key.Key == ConsoleKey.Enter:
- return buffer;
- default:
- return TypePassword(buffer, i);
- }
- }
- static void Flush<T>(Span<T> span) where T: new()
- {
- span.Fill(new T());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement