Document that null STACK_OF(T) can be used with several functions

Lots of code relies on this, so we ought to document it. A null
STACK_OF(T) is treated as an immutable empty list.

Change-Id: I10d0ba8f7b33c7f3febaf92c2cd3da25a0eb0f80
Reviewed-on: https://boringssl-review.googlesource.com/c/boringssl/+/67407
Reviewed-by: Theo Buehler <theorbuehler@gmail.com>
Auto-Submit: David Benjamin <davidben@google.com>
Commit-Queue: Bob Beck <bbe@google.com>
Reviewed-by: Bob Beck <bbe@google.com>
diff --git a/crypto/stack/stack_test.cc b/crypto/stack/stack_test.cc
index 228182b..d2342a5 100644
--- a/crypto/stack/stack_test.cc
+++ b/crypto/stack/stack_test.cc
@@ -517,3 +517,15 @@
     }
   }
 }
+
+TEST(StackTest, NullIsEmpty) {
+  EXPECT_EQ(0u, sk_TEST_INT_num(nullptr));
+
+  EXPECT_EQ(nullptr, sk_TEST_INT_value(nullptr, 0));
+  EXPECT_EQ(nullptr, sk_TEST_INT_value(nullptr, 1));
+
+  bssl::UniquePtr<TEST_INT> value = TEST_INT_new(6);
+  ASSERT_TRUE(value);
+  size_t index;
+  EXPECT_FALSE(sk_TEST_INT_find(nullptr, &index, value.get()));
+}
diff --git a/include/openssl/stack.h b/include/openssl/stack.h
index 23b9d89..46ced49 100644
--- a/include/openssl/stack.h
+++ b/include/openssl/stack.h
@@ -139,7 +139,8 @@
 STACK_OF(SAMPLE) *sk_SAMPLE_new_null(void);
 
 // sk_SAMPLE_num returns the number of elements in |sk|. It is safe to cast this
-// value to |int|. |sk| is guaranteed to have at most |INT_MAX| elements.
+// value to |int|. |sk| is guaranteed to have at most |INT_MAX| elements. If
+// |sk| is NULL, it is treated as the empty list and this function returns zero.
 size_t sk_SAMPLE_num(const STACK_OF(SAMPLE) *sk);
 
 // sk_SAMPLE_zero resets |sk| to the empty state but does nothing to free the
@@ -147,7 +148,8 @@
 void sk_SAMPLE_zero(STACK_OF(SAMPLE) *sk);
 
 // sk_SAMPLE_value returns the |i|th pointer in |sk|, or NULL if |i| is out of
-// range.
+// range. If |sk| is NULL, it is treated as an empty list and the function
+// returns NULL.
 SAMPLE *sk_SAMPLE_value(const STACK_OF(SAMPLE) *sk, size_t i);
 
 // sk_SAMPLE_set sets the |i|th pointer in |sk| to |p| and returns |p|. If |i|
@@ -195,7 +197,8 @@
 // If the stack is sorted (see |sk_SAMPLE_sort|), this function uses a binary
 // search. Otherwise it performs a linear search. If it finds a matching
 // element, it writes the index to |*out_index| (if |out_index| is not NULL) and
-// returns one. Otherwise, it returns zero.
+// returns one. Otherwise, it returns zero. If |sk| is NULL, it is treated as
+// the empty list and the function returns zero.
 //
 // Note this differs from OpenSSL. The type signature is slightly different, and
 // OpenSSL's version will implicitly sort |sk| if it has a comparison function