+ sr_spew("Draining serial port %s.", serial->port);
+
+ if (!serial->lib_funcs || !serial->lib_funcs->drain)
+ return SR_ERR_NA;
+
+ return serial->lib_funcs->drain(serial);
+}
+
+/*
+ * Provide an internal RX data buffer for the serial port. This is not
+ * supposed to be used directly by applications. Instead optional and
+ * alternative transports for serial communication can use this buffer
+ * if their progress is driven from background activity, and is not
+ * (directly) driven by external API calls.
+ *
+ * BEWARE! This implementation assumes that data which gets communicated
+ * via UART can get stored in a GString (which is a char array). Since
+ * the API hides this detail, we can address this issue later when needed.
+ * Callers use the API which communicates bytes.
+ */
+
+/**
+ * Discard previously queued RX data. Internal to the serial subsystem,
+ * coordination between common and transport specific support code.
+ *
+ * @param[in] serial Previously opened serial port instance.
+ *
+ * @internal
+ */
+SR_PRIV void sr_ser_discard_queued_data(struct sr_serial_dev_inst *serial)
+{
+ if (!serial)
+ return;
+ if (!serial->rcv_buffer)
+ return;
+
+ g_string_truncate(serial->rcv_buffer, 0);
+}
+
+/**
+ * Get amount of queued RX data. Internal to the serial subsystem,
+ * coordination between common and transport specific support code.
+ *
+ * @param[in] serial Previously opened serial port instance.
+ *
+ * @internal
+ */
+SR_PRIV size_t sr_ser_has_queued_data(struct sr_serial_dev_inst *serial)
+{
+ if (!serial)
+ return 0;
+ if (!serial->rcv_buffer)
+ return 0;
+
+ return serial->rcv_buffer->len;
+}
+
+/**
+ * Queue received data. Internal to the serial subsystem, coordination
+ * between common and transport specific support code.
+ *
+ * @param[in] serial Previously opened serial port instance.
+ * @param[in] data Pointer to data bytes to queue.
+ * @param[in] len Number of data bytes to queue.
+ *
+ * @internal
+ */
+SR_PRIV void sr_ser_queue_rx_data(struct sr_serial_dev_inst *serial,
+ const uint8_t *data, size_t len)
+{
+ if (!serial)
+ return;
+ if (!data || !len)
+ return;
+
+ if (serial->rcv_buffer)
+ g_string_append_len(serial->rcv_buffer, (const gchar *)data, len);
+}
+
+/**
+ * Retrieve previously queued RX data. Internal to the serial subsystem,
+ * coordination between common and transport specific support code.
+ *
+ * @param[in] serial Previously opened serial port instance.
+ * @param[out] data Pointer to store retrieved data bytes into.
+ * @param[in] len Number of data bytes to retrieve.
+ *
+ * @internal
+ */
+SR_PRIV size_t sr_ser_unqueue_rx_data(struct sr_serial_dev_inst *serial,
+ uint8_t *data, size_t len)
+{
+ size_t qlen;
+ GString *buf;
+
+ if (!serial)
+ return 0;
+ if (!data || !len)
+ return 0;
+
+ qlen = sr_ser_has_queued_data(serial);
+ if (!qlen)
+ return 0;
+
+ buf = serial->rcv_buffer;
+ if (len > buf->len)
+ len = buf->len;
+ if (len) {
+ memcpy(data, buf->str, len);
+ g_string_erase(buf, 0, len);