[Mono-dev] Patch for System.IO.Ports.SerialPort ReadLine function

Michael Mattess MichaelMattess at rauland.com.au
Sun Nov 4 21:41:36 EST 2007


Hi

 

This morning I have put together a little patch for the
System.IO.Ports.SerialPort ReadLine function so that it uses the NewLine
property value rather than '\n' to identify the end of a line (see bug
#321988).

 

Below is my replacement ReadLine() function.  I could add some code to
more efficiently handle the specific (and common) case where NewLine is
a single character. Bus since this is serial coms I doubt that this code
will be a performance bottle neck and the general implementation should
be ok.

 

Also I noticed that the NewLine property can be assigned an empty
string, which throws an exception in MS.Net (see bug #339012).

 

I have tested this function by itself with some standalone unit tests,
by removing the call to  stream.Read and replacing it with a call to a
mocked up read function.

 

--------------------------------------------------------------

 

public string ReadLine (){

    CheckOpen();

    List<byte> bytes_read = new List<byte>();

    byte[] buff = new byte[1];

    int new_line_offset = 0;

 

    while(true) {

        int n = stream.Read(buff, 0, 1);

 

        if(n == -1) {

            break;

        }

 

        bytes_read.Add(buff[0]);

 

 

        if(bytes_read.Count >= new_line.Length) {

            bool isNewLine = true;

 

            //check if we have read a NewLine string.

            for(int i = 0; i < new_line.Length; i++) {

                if(bytes_read[new_line_offset + i] != new_line[i]) {

                    isNewLine = false;

                    break;

                }

            }

 

            if(isNewLine) {

                //Remove the NewLine string from the read line.

                bytes_read.RemoveRange(new_line_offset,
new_line.Length);

                break;

            }

 

            new_line_offset++;

        }

    }

 

 

Regards,

Michael Mattess

 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.ximian.com/pipermail/mono-devel-list/attachments/20071105/8a565250/attachment.html 


More information about the Mono-devel-list mailing list