Category talk:Wren-ioutil: Difference between revisions
→Source code: Added Input.password method, removed type aliases which are no longer needed.
(Fixed a potential bug.) |
(→Source code: Added Input.password method, removed type aliases which are no longer needed.) |
||
Line 463:
}
}
// Prompts the user to enter a password with a minimum/maximum length and returns it.
// Only printable ASCII characters other than space are valid or if 'allowSymbols' is
// false, only ASCII alphanumeric characters. Other characters, except
// ENTER, BACKSPACE, CTRL-C and CTRL-D which behave normally, are ignored.
// Valid characters are replaced with bullets as they are typed though any attempt
// to type characters beyond the maximum length is ignored.
static password(prompt, minLen, maxLen, allowSymbols) {
if (minLen.type != Num || !minLen.isInteger || minLen < 0) {
Fiber.abort("Minimum length must be a non-negative integer.")
}
if (maxLen.type != Num || !maxLen.isInteger || maxLen < minLen) {
Fiber.abort("Maximum length must not be less than minimum length.")
}
Stdin.isRaw = true
var alphanum = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var pwd = ""
Output.fwrite(prompt)
while (true) {
var byte = Stdin.readByte()
if (byte > 32 && byte < 127) {
if (pwd.count < maxLen) {
var char = String.fromByte(byte)
if (allowSymbols || alphanum.indexOf(char) != -1) {
Output.fwrite("•")
pwd = pwd + char
}
}
} else if (byte == 8 || byte == 127) {
if (pwd.count > 0) {
Output.fwrite("\b \b")
pwd = pwd[0...-1]
}
} else if (byte == 10 || byte == 13) {
if (pwd.count < minLen) {
System.print("\nMinimum length is %(minLen) characters, try again.")
pwd = ""
Output.fwrite(prompt)
} else {
Stdin.isRaw = false
System.print()
return pwd
}
} else if (byte == 3 || byte == 4) {
Stdin.isRaw = false
if (byte == 3) {
System.print("^C")
} else {
System.print("Stdin was closed.")
}
Fiber.abort("")
}
}
}
// Convenience version of the above method which always allows symbols.
static password(prompt, minLen, maxLen) { password(prompt, minLen, maxLen, true) }
}
Line 480 ⟶ 537:
Stdout.flush()
}
}</syntaxhighlight>
|