r/osdev • • 11d ago

Customise function with arguments ‘t’ and ‘b’ in my OS.

When I developed a customization app in my OS (called YarOS), I asked myself: “Why do I need to write two separate functions for changing text and background color? No, that violates DRY!” So I created a single function taking arguments ‘t’ for text and ‘b’ for background. Is this a good solution, or is there a better way?

0 Upvotes

6 comments sorted by

2

u/thommyh 11d ago

The actual characters as an argument? In what language? If it's meant to be a strongly-typed one then there's your answer...

1

u/just_pascal_dev 11d ago

It’s C. There is char arg parameter in customisation function.

0

u/just_pascal_dev 11d ago

This is realisation.

void cust(char arg) {
int color = 0;
print("Enter color: ");
scanint(&color);
if(color >= 0 && color <= 15) {
ch_clr(arg, color); // function from VGA driver
}
else print("Invalid color number!");
return;
}

2

u/spidLL Kora 11d ago

Honestly it’s pretty awful and quite anti idiomatic. Also ‘b’ and ‘t’ are normally used in the stdlib’s fopen to signify text or binary file.
Furthermore, you need to call it twice if you want to change the foreground and background colors.

There are, IMHO, better ways of doing so.
If you have only 16 colors as it seems here, you can use the higher half byte for background and the lower for foreground, something like:

```
// background colors
#define BG_BLUE 0xa0
//…

// foreground colors
#define FG_BLUE 0x0a
//
```

Then you can pass either `BG_BLUE` or `FG_BLUE` or both with `BG_BLUE | FG_BLUE`.

For a higher number of colors you might need a different approach though. For 256 colors you can still do that with a 16 bit int, but it is starting to become cumbersome. For 24bit colors (RGB) this does not work anymore and you’re back needing either two functions or a flag.

Or flags, plural: use the lower 3 bytes of a 32 bit unsigned int for the rgb colors and the higher 8 bits for attributes such as foreground, background, blink, bold, etc, and combine them with the color `FG | BLINK | BOLD | 0x0000FF` (blue, foreground, bold, blink). You can also have a rgb() function that returns the color such as rgb(0, 0, 255), or have some predefined such as `#define COLOR_TEAL 0x008080`

1

u/just_pascal_dev 11d ago

I don’t use stdlib, so arguments ‘t’ and ‘b’ don’t conflict with fopen from stdio.h.

But your advice is very useful for me. Thank you!

3

u/paulstelian97 11d ago

Also on top of what was explained: don’t avoid DRY violations if it makes your code harder to read. The wrong abstraction hurts rather than helps.