Tuesday, June 30, 2020

Simple solution to the wrap around buffer problem

THE CHALLENGE

My buffer is 2000 characters, with the first 80 reserved for the status line at the bottom of the screen. The remaining 1920 characters wrap, that is location 1999 is line 24, column 80 if you move one character down you should be at location 80, line 1 column 1. This is not straightforward modulo 1920 math because of the status line at the beginning. 

In may places, my code will be moving through a field indexing from the first character position to the last. Fields can exist where the start position is high in the buffer but the field wraps around so that the end position is low. In one test case, my last field on the screen began at location 240 (line 3 column 1) and extended through the rest of the buffer. It was therefore terminated when it wrapped around and encountered the attribute character at location 81 (line 1 column 2). Thus line 1 column 1 was the last position in the field. Yes, it is a contrived example but the code must work properly for all legit cases. 

SIMPLE SOLUTION

In every spot where I accept a buffer address, I handle the wrapping. That is, if I am presented an address less than 80, I add 1920 so that I have 'backed up' to the tail end of the buffer. If I see an address beyond 1999, I subtract 1920 from it so that I wrap around to the low end. 

This allows a 'for' loop to work properly marching up from a start address near the bottom of the screen and its end address being near the top. The loop will calculate indexes that move beyond the end address 1999 but my fix will cause the actual access to wrap. 

No comments:

Post a Comment