Re: [PATCH 34/35] tty: make tty_get_byte_size available

From: Joe Perches
Date: Thu May 06 2021 - 03:16:14 EST


On Wed, 2021-05-05 at 11:19 +0200, Jiri Slaby wrote:
> Many tty drivers contain code to compute bits count depending on termios
> cflags. So extract this code from serial core to a separate tty helper
> function called tty_get_byte_size.
[]
> diff --git a/drivers/tty/tty_ioctl.c b/drivers/tty/tty_ioctl.c
[]
> +/**
> + * tty_get_byte_size - get size of a byte
> + * @cflag: termios cflag value
> + * @account_flags: account for start and stop bits, second stop bit (if
> + * set), and parity (if set)
> + *
> + * Get the size of a byte in bits depending on @cflag. Depending on
> + * @account_flags parameter, the result also accounts start and stop bits,
> + * the second stop bit, and parity bit.
> + */
> +unsigned char tty_get_byte_size(unsigned int cflag, bool account_flags)
> +{
> + unsigned char bits = account_flags ? 2 : 0;
> +
> + /* byte size and parity */
> + switch (cflag & CSIZE) {
> + case CS5:
> + bits += 5;
> + break;
> + case CS6:
> + bits += 6;
> + break;
> + case CS7:
> + bits += 7;
> + break;
> + case CS8:
> + default:
> + bits += 8;
> + break;
> + }
> +
> + if (account_flags && (cflag & CSTOPB))
> + bits++;
> +
> + if (account_flags && (cflag & PARENB))
> + bits++;
> +
> + return bits;
> +}
> +EXPORT_SYMBOL_GPL(tty_get_byte_size);

Perhaps clearer not testing account_flags multiple times.

unsigned char tty_get_byte_size(unsigned int cflag, bool account_flags)
{
unsigned char bits;

/* byte size and parity */
switch (cflag & CSIZE) {
case CS5:
bits = 5;
break;
case CS6:
bits = 6;
break;
case CS7:
bits = 7;
break;
case CS8:
default:
bits = 8;
break;
}

if (account_flags) {
bits += 2; /* start/stop bits */

if (cflag & CSTOPB)
bits++;

if (cflag & PARENB)
bits++;
}

return bits;
}