gsm0808: add encoder for cause codes and use it

At the moment the all gsm0808 cause codes are encoded directly using the
tlv API directly to put a one byte TLV field. This works ok for most
situations where the cause code consists of a single byte. However,
gsm0808 specifies a two byte cause code model where cause codes may be
extended up to two bytes. Instead of implementing the encoding over and
over and again, let's rather have an encoder function we can call.

- Add an encoder function that can generate single byte and extended
  cause codeds and makes the length decision automatically.

- Use only this function to append cause codes

Change-Id: I71d58fad89502a43532f60717ca022c15c73f8bb
diff --git a/tests/gsm0808/gsm0808_test.c b/tests/gsm0808/gsm0808_test.c
index 197ec06..63b8720 100644
--- a/tests/gsm0808/gsm0808_test.c
+++ b/tests/gsm0808/gsm0808_test.c
@@ -30,6 +30,13 @@
 #include <arpa/inet.h>
 #include <errno.h>
 
+#define EXPECT_ENCODED(hexstr) do { \
+		const char *enc_str = msgb_hexdump(msg); \
+		printf("%s: encoded: %s(rc = %u)\n", __func__, enc_str, rc_enc); \
+		OSMO_ASSERT(strcmp(enc_str, hexstr " ") == 0); \
+		OSMO_ASSERT(rc_enc == msg->len); \
+	} while(0)
+
 #define VERIFY(msg, data, len) 						\
 	if (msgb_l3len(msg) != len) {					\
 		printf("%s:%d Length don't match: %d vs. %d. %s\n", 	\
@@ -65,6 +72,27 @@
 	scl->len = 3;
 }
 
+void test_gsm0808_enc_cause(void)
+{
+	/* NOTE: This must be tested early because many of the following tests
+	 * rely on the generation of a proper cause code. */
+
+	uint8_t rc_enc;
+	struct msgb *msg;
+
+	/* Test with a single byte cause code */
+	msg = msgb_alloc(1024, "output buffer");
+	rc_enc = gsm0808_enc_cause(msg, 0x41);
+	EXPECT_ENCODED("04 01 41");
+	msgb_free(msg);
+
+	/* Test with an extended (two byte) cause code */
+	msg = msgb_alloc(1024, "output buffer");
+	rc_enc = gsm0808_enc_cause(msg, 0x8041);
+	EXPECT_ENCODED("04 02 80 41");
+	msgb_free(msg);
+}
+
 static void test_create_layer3(void)
 {
 	static const uint8_t res[] = {
@@ -824,13 +852,6 @@
 	msgb_free(msg);
 }
 
-#define EXPECT_ENCODED(hexstr) do { \
-		const char *enc_str = msgb_hexdump(msg); \
-		printf("%s: encoded: %s(rc = %u)\n", __func__, enc_str, rc_enc); \
-		OSMO_ASSERT(strcmp(enc_str, hexstr " ") == 0); \
-		OSMO_ASSERT(rc_enc == msg->len); \
-	} while(0)
-
 static void test_gsm0808_enc_dec_cell_id_list_lac()
 {
 	struct gsm0808_cell_id_list2 enc_cil;
@@ -1770,6 +1791,7 @@
 int main(int argc, char **argv)
 {
 	printf("Testing generation of GSM0808 messages\n");
+	test_gsm0808_enc_cause();
 	test_create_layer3();
 	test_create_layer3_aoip();
 	test_create_reset();