Correct Way to Test for Empty Buffer

Here is something that caught me out. Here are a series of simple programs that test the different way buffers can be tested if empty.

The first case gives an error when testiing b == null

Buffer b = create

b = ""

if (b == null) {
  print "Hello"
}

delete b

-R-E- DXL: <Line:5> null buffer parameter was passed into argument position 2
-I- DXL: execution halted

 

The next case gives an error when testing if b == ""
Buffer b = create

b = ""

if (b == "") {
  print "Hello"
}

delete b

-E- DXL: <Line:5> incorrect arguments for (==)
-E- DXL: <Line:5> incorrect arguments for (if)
-I- DXL: All done. Errors reported: 2. Warnings reported: 0.

 

In the next case because null is a function, people might try this. However it gives no result, an incorrect answer, but no error. This is a trap because the condition is never true if b is empty.
Buffer b = create

b = ""

if (null(b)) {
  print "Hello"
}

delete b

No error, does not print anything

 

But this works. In this case try testing for !null(b). The correct answer is printed if b is not empty.
Buffer b = create

b = "1"

if (!null(b)) {
  print "Hello"
}

delete b

prints Hello

 

However this is the correct solution, working for empty and non empty Buffers.
Buffer b = create

b = ""

if (stringOf b == null) {
  print "Hello"
}

delete b

prints Hello

 

Recorded here for posterity and because it is not documented elsewhere.


ADent - Wed Nov 18 03:55:30 EST 2015

Re: Correct Way to Test for Empty Buffer
Mathias Mamsch - Wed Nov 18 04:28:03 EST 2015

I would test the emptiness of a buffer using:

Buffer buf = create(); 

if (length buf == 0) { 
    print "Empty";
}

Since the buffer stores its length, this is a very fast operation. Note that using (stringOf b) will produce a string that will be persisted in the string table, and therefore leak memory. This is especially relevant when using this function on very large buffers.

Note that a null buffer should be treated like an error, so I would normally not do something like: if (null buf || length buf == 0)  { ... }

Regards, Mathias