Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Tuesday, August 3, 2021

Deep cloning a generic List in Java

Today I had to deep clone objects in Java. What a nightmare.

First, the Cloneable interface is horribly broken, and writing such a simply code becomes a laborious task. Second, if the object has a List as a field, you must manually clone the elements into a new List.

The code goes as it follows:

public class Foo implements Cloneable {

	private String name;

	private List words;

	@Override
	public Object clone() {
		try {
			Foo cloned = (Foo) super.clone();
			cloned.words = Auxiliar.cloneList(words);
			return cloned;
		} catch (CloneNotSupportedException e) {
			System.out.println("Never happens!");
			return null;
		}
	}

	// Getters and setters omitted.

}

Notice the Another.cloneList() call? This is where we manually clone all the List elements, by calling clone() in each one. This is the solution I found for a generic method:

public class Auxiliar {

	@SuppressWarnings("unchecked")
	public static <T extends Cloneable> List<T> cloneList(List<T> list) {
		try {
			List<T> newList = new ArrayList<>(list.size());
			for (T item : list) {
				newList.add((T) item.getClass().getMethod("clone").invoke(item));
			}
			return newList;
		} catch (IllegalAccessException | IllegalArgumentException
			| InvocationTargetException | NoSuchMethodException | SecurityException e) {
			System.out.println("Never happens!");
			return null;
		}
	}
}

No idea why Cloneable was not deprecated and replaced by something minimally decent yet.

Sunday, July 11, 2021

Accepting both Vec or slice of String or &str in Rust

In whathever programming language, it’s rather common to have a function which accepts an array of strings. Specifically in Rust, there is the notion of slice, which can be used as a reference to a Vec. And also there is the notion of &str, which can be used as a reference to String. Putting both concepts together as an argument is not trivial, though.

Turns out I found a way to make it work by using the AsRef trait – as many things in Rust, traits lead the way. By using generics, it becomes possible:

fn foo<S: AsRef<str>>(names: &[S]) {
	for name in names.iter().map(|s| s.as_ref()) {
		println!("{}", name);
	}
}

Or alternatively using the impl keyword for the trait bound:

fn foo(names: &[impl AsRef<str>]) {
	for name in names.iter().map(|s| s.as_ref()) {
		println!("{}", name);
	}
}

The function above accepts both Vec and slice of String or &str. But notice how, in order to retrieve the string itself, the as_ref() method must be called.

Thursday, July 1, 2021

Missing the ternary operator in Rust

Just out of curiosity, I wrote a Rust macro similar to Visual Basic’s IIf function:

macro_rules! iif {
	($cond:expr, $iftrue:expr, $iffalse:expr) => {
		if $cond { $iftrue } else { $iffalse }
	};
}

Usage:

let n = iif!(1 == 1, "yes", "no");

Close to the ternary operator, which I’m sorely missing in these Rust days.

Wednesday, June 2, 2021

Go’s defer in Rust

One of my all-time favorite features of Go is the defer mechanism. It’s so incredibly simple, and so incredibly ingenious and useful. The fact the deferred statements are called during a panic unwind makes me want to use it in other languages, like Rust.

As for Rust, I’m aware of the scopeguard crate, but it seems to be an overkill to such a simple concept. Plus, it does some fishy workaround to make the FnOnce.

So I decided to write my own Rust version of the defer mechanism, which turns out to be a macro that hides the creation of an object. This object holds a FnOnce which runs when at the end of the scope via Drop trait:

/// Internal struct used by the `defer!` macro.
pub struct Defer<F: FnOnce()> {
	func: Option<F>,
}

impl<F: FnOnce()> Defer<F> {
	pub fn new(func: F) -> Self {
		Self { func: Some(func) }
	}
}

impl<F: FnOnce()> Drop for Defer<F> {
	fn drop(&mut self) {
		self.func.take().map(|f| f());
	}
}

/// Defers the execution of a block until the surrounding scope ends.
macro_rules! defer {
	( $($tt:tt)* ) => {
		let _deferred = crate::defer::Defer::new(|| { $($tt)* });
	};
}

Usage is straightforward:

#[macro_use] mod defer; // considering defer.rs at crate's root

fn main() {
	defer! { println!("hi"); }
}

Edit: I published the code above as a crate: defer-lite.

Saturday, May 29, 2021

Sum types in Go

One thing I always missed in Go was sum types. I’ve seen some discussion before. Although Go doesn’t have this as an explicit, native feature, I found a pattern that suits my needs by defining types and interfaces.

In the example below, I simulate a function that would load application resources, which can be extracted by ID, position or a string identifier. First, we define the interface and the subtypes:

type (
	// Variant type for: ResId, ResPos, ResStr.
	Res interface{ implRes() }

	ResId  uint32
	ResPos uint32
	ResStr string
)

func (ResId)  implRes() {}
func (ResPos) implRes() {}
func (ResStr) implRes() {}

The isRes() function acts like a “tag” for each subtype.

Now, a function that receives the variant type:

func LoadResource(variant Res) {
	switch v := variant.(type) {
	case ResId:
		println("ID", uint32(v))
	case ResPos:
		println("Position", uint32(v))
	case ResStr:
		println("String", string(v))
	default:
		panic("Res does not accept a nil value.")
	}
}

Usage is now trivial:

LoadResource(ResId(2001))
LoadResource(ResPos(4))
LoadResource(ResStr("MY_ICON"))

It’s clean and it works remarkably well. I applied this technique in my Windigo library.

Thursday, May 13, 2021

The ghastly button focus

During my 20 years or so writing Win32 programs, I always relied on SetFocus to focus a control. However, I always noticed a weird behavior on push buttons regarding the BS_DEFPUSHBUTTON style, which was never right. In fact, I remember one of the past WinLamb incarnations which I implemented some trick involving changing the button style when setting the focus.

Anyway, now I found out how to properly set the focus on a control, and it does not involve SetFocus, but rather the WM_NEXTDLGCTL message:

SendMessage(hParent, WM_NEXTDLGCTL, (WPARAM)hButton, MAKELPARAM(TRUE, 0));

And the push button magically sets its own style correctly.

Wednesday, March 31, 2021

Fixing Cargo authentication on GitHub

Today, while performing tests before publishing the first version of WinSafe, I stumbled across a problem I had with Go a few weeks ago. It was caused because GitHub no longer accepts user/password authentications, so everything must be done via SSH. I solved the problem by adding some lines to my ~/.gitconfig file.

But Cargo still cannot fetch packages.

After a lot of digging, I found a setting that finally worked. It involved adding another filter to ~/.gitconfig, which now looks like this:

# Force SSH instead of HTTP
# https://stackoverflow.com/a/27501039/6923555
[url "ssh://git@github.com/"]
	insteadOf = https://github.com/
	
# But crates.io needs to pass
# https://github.com/rust-lang/cargo/issues/8172#issuecomment-659066173
[url "https://github.com/rust-lang/crates.io-index"]
	insteadOf = https://github.com/rust-lang/crates.io-index

The “crates.io” directory was updated and I could use an external crate, something that will be needed when I publish my own.

As a side note, all downloaded crates are stored in ~/.cargo/registry/ directory, which can be safely wiped out to clean the cache.

Thursday, March 25, 2021

Displaying current Git branch in Bash prompt

I decided to show the current Git branch at my bash prompt whenever I’m at a directory which contains a repository. I found a rather convoluted Bash-esque solution, which I adapted to myself:

gitbranch() {
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ \1/'
}
#export PS1="\u@\h \[\e[32m\]\w \[\e[91m\]\$(gitbranch)\[\e[00m\]$ "
export PS1="\[\e]0;\u@\h: \w\a\]${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\[\e[33m\]\$(gitbranch)\[\e[00m\]\$ "

It’s compact and it works as intended.

Thursday, February 18, 2021

Using local dependencies with Go modules

Go 1.16, released this week, deprecated GOPATH. I used it extensively to develop my libs before publishing them, but now I’m forced to convert them to modules, which work with remote repos by default. However, there’s a way to work with local dependencies.

As I found here, we can instruct Go toolchain to search for a local repo, instead of a remote one by using this command:

go mod edit -replace github.com/username/repo=../repo

This changes the go.mod file. Now, to clean up the go.sum file, run:

go mod tidy

After that, you should be able to use a local dependency just like the old GOPATH days.

The downloaded files are still cached, though. To finally clean the entire cache, run:

go clean -cache -modcache

Modules eventually needed by other applications will be downloaded again when due.

Tuesday, January 5, 2021

Downcasting boxed errors in Rust

Today I was trying to write polymorphic error handling in Rust, something achievable with dynamic_cast in C++, and incredibly easy in Go. In Rust, of course, it’s overcomplicated.

After a couple frustrating hours of searching with no success, I stumbled upon the downcast_ref method of the Error trait, which finally allowed me to write what I wanted. Oddly enough, I couldn’t find this solution anywhere.

Note that the String concrete type cannot be retrieved.

Playground link here.

Tuesday, November 24, 2020

Inserting auto IDs in Oracle

When dealing with tables with an auto-incremented ID field, Oracle requires an special syntax if you’re about to insert data manually. You must directly call the name of the sequence of that table, followed by a special field:

INSERT INTO person (id_person, name)
VALUES (sq_id_person.NEXTVAL, 'John')

Note that the name of the sequence is actually arbitrary.

Friday, October 16, 2020

Validating lambda signatures in C++17

WinLamb, as the name itself implies, is heavily based on lambda functions. While searching a way to enforce the lambda signatures in the upcoming C++17 release, I received an incredible answer on StackOverflow:

#include <functional>
#include <type_traits>
	
template<typename F>
auto foo(F&& func) noexcept ->
	std::enable_if_t<
		std::is_same_v<
			decltype(std::function{std::forward<F>(func)}),
			std::function<void(int)>
		>, void
	>
{
	func(33);
}

Up to this point, I was completely unaware of the existence of trailing return types in function declarations.

The validation is extremely restrict, serving my purposes perfectly. And it seems that the upcoming C++20 concepts feature can simplify it quite a lot.

Thursday, August 6, 2020

SFINAE and enable_if

Today, while researching for the upcoming C++17 version of WinLamb, I was rethinking the idea of restricting the allowed types on a template argument. That’s an SFINAE thing, scary to many people – including me sometimes, in my love-hate relationship with advanced C++ stuff.

The thing is that I ended up writing a working piece of code using std::enable_if to restrict a template argument, and I’m quite proud of it.

#include <type_traits>

struct One { int num; };
struct Two { int num; };
struct Tre { int num; };

template<
  typename T,
  typename = std::enable_if_t<
    std::is_same_v<T, One> ||
    std::is_same_v<T, Two>
  >
>
void foo(T& o) { ++o.num; }

int main() {
  One o;
  foo(o);
  return 0;
}

In the code above, One and Two classes will work with foo(), whereas Tre will not compile, despite being exactly like the others.

Thursday, June 25, 2020

CSS folded poster effect

Yesterday I just stumbled across this incredible CSS work, which makes a picture look like a folder poster on Reddit. The CSS was somewhat overengineered, so I removed a bunch of stuff and fixed some parts, and the result is now pretty usable.

The border is set by the padding attribute, and may need to be adjusted according to the image size. The image size itself cannot be properly set, or the effect goes nuts – if you want to resize the image, resize the image file itself.

I hope to use it somewhere, because it’s really cool. Props to the dude who did it.

Monday, June 15, 2020

Embedding rc files into Go Win32 executables

When building Go executables in Windows, the Go toolchain recognizes *.syso files and automatically embeds then into the *.exe – this allows the embedding of resources scripts, which can contain icon and manifest, among other resources. Visual C++ resource compiler, however, only generate *.res files.

I’ve seen people using rsrc tool to add manifest files to executables. The problem is that this tool doesn’t really compile a resource file, nor it converts *.res into *.syso.

Turns out resource file compilation can be done with windres tool, from MinGW package. Since I already have the whole Visual C++ stuff, I didn’t want to install all the package, which is rather big, and I already have MinGW terminal from Git. Fortunately, windres works standalone, the only requisite is that gcc is in the same directory. And we can download both.

Portable MinGW tools can be downloaded from here:

From both packages, extract gcc and windres and save them somewhere else. All the rest can be deleted.

Compile the *.rc file into *.res with Visual C++ Developer Power Shell for VS 2019:

rc /r my-resource.rc

Then, on MinGW prompt, convert *.res into *.syso:

windres -i my-resource.res -o my-resource.syso

Now place my-resource.syso in the same directory of your main.go, and that’s it. For some weird reason, when debugging in VSCode, the program icon may appear wrong, but it will show fine in release builds, which are the ones that really matter:

go build -ldflags "-s -w -H=windowsgui"

Ideally windres would be used to compile the *.rc directly into *.syso, but to do so it needs the Win32 headers from MinGW, which are not present – you’ll get an error. Probably there’s a way to point Visual C++ headers directory to windres, but by now I’m satisfied using windres tool just to convert the *.res.

Friday, May 29, 2020

Rust macro to clone many objects at once

When working at my forthcoming Rust Win32 library, I was frustrated with the unergonomic task of cloning all the objects before referencing them inside a closure. The basic problem goes like this:

let a = a.clone();
let b = b.clone();
stuff.do_something(|| {
  a.foo();
  b.bar();
});

It would be nice to have some kind of syntactic sugar. Then at some point I saw an example that led me to use destructuring, very familiar from my JavaScript experience:

let (a, b) = (a.clone(), b.clone());
stuff.do_something(|| {
  a.foo();
  b.bar();
});

After that, it came to my mind that I could write a macro for that. After about a half hour wrapping my head around the concept, I finally came up with a macro to clone many objects at once:

macro_rules! clone {
  ( $($obj: expr),+ ) => {{
    ( $( $obj.clone() ),+ )
  }};
}

Which finally allowed me to write the most sugary version of all:

let (a, b) = clone!(a, b);
stuff.do_something(|| {
  a.foo();
  b.bar();
});

Testable in the Rust Playground.

Monday, April 6, 2020

Better antialiasing on Windows Visual Studio Code

In Windows, Google Chrome browser suffers from font bad rendering, with fonts being too thin and washed on screen. I don’t really know the technical cause, but it seems related to antialiasing and how the fonts are drawn, maybe a DirectX Graphics misuse.

Visual Studio Code is built upon Electron infrastructure, which in its turn uses Chrome engine to render stuff. So, VSCode suffers from the same problem: fonts being too thin and bad to read. Writing source code in such an environment is hard on the eyes. Until this day, I simply used Consolas font, which is naturally thicker. But I was never satisfied.

On Chrome, I fixed the problem by using Font Rendering Enhancer extension. It’s a rather simple extension that just adds the following style everywhere:

* {
  text-shadow: transparent 0px 0px 0px,
    rgba(0, 0, 0, 0.5) 0px 0px 0px !important;
}

The variation occurs in the 0.5 value: the higher the value, the darker the fonts will be rendered.

At some point, I also started facing the same problem on Firefox, and I asked about it on Reddit. Then I used addon to apply the style globally, and the problem was solved.

Now, back to Visual Studio Code, I started wondering whether it would be possible to add a global style to the whole window, since it’s just a browser window, after all. Turns out it’s possible by directly injecting CSS into Developer Tools, but it will go away when you close VSCode. Now, to make this change permanent – at least until the next update –, we can edit the main CSS file of VSCode and inject the CSS snipped globally. The file is:

(install dir)
 resources
  app
   out
    vs
     workbench
      workbench.desktop.main.css

There’s a side effect, however: when opening the VSCode again, you’ll receive the following warning:

Your Code installation appears to be corrupt. Please reinstall.

What means VSCode checks its own files when it’s launched, and that’s good, given the amount of garbage that an Electron program has. You can ignore this warning though, although there’s a very remote risk that something bad was actually injected into your VSCode installation without your consent, and you’ll be vulnerable. But it would be a very rare event, indeed. You’ll also see “[Unsupported]” in the titlebar.

Monday, March 16, 2020

Choosing between useState and useReducer in React

Right now I’m designing a rather important architecture at work, and I’m using React for it. After writing a simple enough implementation with Redux, I came to the conclusion that, in fact, I don’t need Redux in this architecture, since I’m only storing auth information. Context API seems to be enough.

So, in order to have a mutable and reactive value in the application context, I must choose between useState and useReducer hooks.

While studying the matter, I found a rather good answer to this question:

  • When it’s just an independent element of state you’re managing: useState;
  • When one element of your state relies on the value of another element of your state in order to update: useReducer.

Although the examples given by the author are way too long, the idea is spot on. In my particular case, since the state is just a monolithic block of data, useState seems to fit my needs.

Wednesday, February 5, 2020

False memory leak reports of static objects

I was having a weird memory leak report in a C++ program, happening right after I close it, and triggered by a call to _CrtDumpMemoryLeaks, which exists in the very end of WinMain function in WinLamb. I was puzzled, because I’ve commented everything out, and I still had the memory leak.

Turns out _CrtDumpMemoryLeaks is called at the end of WinMain, before the static object destructors are called. And there you go: if any statically allocated object had made a heap allocation, the memory won’t be freed yet, thus the report.

I’m not the only one with this problem, but so far no solution had any effect. By now I’ll just avoid static allocation of objects which alloc memory on the heap, and carry on with life. Maybe I’m too used to the JavaScript blessings.

Thursday, January 9, 2020

What types are heap-allocated in Rust

Today I stumbled on this question regarding which standard Rust types do alloc in the heap. I have this question popping in my head quite often, so here are the heap-allocated ones:

  • Box, simple heap allocation;
  • Rc, reference counter;
  • Arc, thread-safe atomic reference counter;
  • collections.

Reference to the answer can be found here.