Keyboard.jack readLine() what should maxLength of string be?

classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|

Keyboard.jack readLine() what should maxLength of string be?

peterxu422
When implementing readLine() in Keyboard class, we don't know the length of the string ahead of time, so what's the best way to go about this?

One way I can think of is just declaring String.new(length) where length is an arbitrarily large enough constant, however, the disadvantage would be that it could be wasteful memory for input strings that are small and not enough for large input strings.

Another way I could think of is to just keep recreating a new string variable with a length that is one larger than the previous one and copying the string contents of the previous one into the new one until the new line character is reached. However, the disadvantage to this is that it would involve a lot more operations which would make it slower.
Reply | Threaded
Open this post in threaded view
|

Re: Keyboard.jack readLine() what should maxLength of string be?

cadet1620
Administrator
peterxu422 wrote
When implementing readLine() in Keyboard class, we don't know the length of the string ahead of time, so what's the best way to go about this?
The simplest thing to do is to pick an arbitrary maximum response length, say 80 characters, and always allocate an 80 character string and discard and do not echo any characters that cannot be appended to the string.

Another approach is to allocate a single larger string in Keyboard.init(), perhaps 250 characters -- enough for a bit more than a 3 line response -- and read into that string. When you get the new-line, you can allocate a string that is exactly the required length and copy the response data into it.

An even more sophisticated approach would be to initially allocate a smaller buffer in Keyboard.init() and if the user ever types more than will fit in the buffer, allocate a new and bigger buffer, copying the already read data into the new buffer before destroying the old buffer. This way a minimal amount of extra memory will be used unless the user types a long response, but you do not incur the overhead of allocating and freeing memory blocks for each character typed.

--Mark
Reply | Threaded
Open this post in threaded view
|

Re: Keyboard.jack readLine() what should maxLength of string be?

Sai krishna
This post was updated on .
CONTENTS DELETED
The author has deleted this message.
Reply | Threaded
Open this post in threaded view
|

Re: Keyboard.jack readLine() what should maxLength of string be?

WBahn
Administrator
You already asked this question over here:

http://nand2tetris-questions-and-answers-forum.32033.n3.nabble.com/ascii-code-provided-in-the-book-doesn-t-match-the-wiki-page-tp4030061p4035003.html

Please only post a question once. Multiple posts of the same thing just leads to chaos and confusion.