Gluon Lang Show

Gluon is a small, statically-typed, functional programming language designed for application embedding into Rust code.

Gluon lang is a native Rust implementation and does not require any FFI interfacing to foreign C libraries, such as for guile.

Gluon lang provides a feature called “implicit arguments” that can be used to realize parametric polymorphism.

Just Gluon lang is a a bit picky regarding recursion and implicit arguments, for example using the Functor Show from module std.show.
The following document is helpful to understand the feature http://marwes.github.io/2018/06/19/gluon-0.8.html

The following is a short example demonstrating its usage.

Let’s have two file,

  • the module maybe.glu exporting both symbols Maybe and show
  • and the application app.glu
// file: maybe.glu

let show @ { ? } = import! std.show
let { (<>) } = import! std.semigroup

// A `Maybe` represents a parameterized type for an optional value
type Maybe a =
  | Just a
  | Nothing

// Stringifying the `Maybe` value
let show ?d : [Show a] -> Show (Maybe a) =
    let show o =
        match o with
        | Just x -> "Just (" <> d.show x <> ")"
        | Nothing -> "Nothing"
    { show }

in
{  Maybe, show }

Now, the application app.glu imports both symbols, using the following expression

let maybe @ { Maybe , ? } = import! maybe

Here, the placeholder ? is important to import in the function shows as scoped symbol maybe.show to avoid ambiguity with symbol show.show.

// file: app.glu
let prelude = import! std.prelude
let  { Show, show } = import! std.show
let io @ { ? } = import! std.io
let string @ { ? } = import! std.string

let maybe @ { Maybe , ? } = import! maybe

let val : maybe.Maybe String = Just "foo"
in
io.println (show val)

Execution in console will be as follows

$ gluon app.glu 
Just ("foo")

Rust Memory Layout Optimization (Enum)

Usage of enum-types is inherent in Rust, usually causing additional overhead due to the enum-discriminator. But, there are a number of optimizations that may eliminate this memory overhead. The following is just a cheatsheet. For further reading see https://rust-lang.github.io/unsafe-code-guidelines/layout/enums.html

Data-Less and Uninhabited fields

Data containers without data payload or containers over types of “zero byte size” the following optimizations exist.

Introduced by MR https://github.com/rust-lang/rust/pull/45225

Size optimizations implemented so far:

  • ignoring uninhabited variants (i.e. containing uninhabited fields), e.g.:
    • Option<!> is 0 bytes
    • Result<T, !> has the same size as T
  • using arbitrary niches, not just 0, to represent a data-less variant, e.g.:
    • Option<bool>, Option<Option<bool>>, Option<Ordering> are all 1 byte
    • Option<char> is 4 bytes
  • using a range of niches to represent multiple data-less variants, e.g.:
    • enum E { A(bool), B, C, D } is 1 byte

An integer that is known not to equal zero.

Wrappers as Option<T> or Result<T> over “NonZero” data types may be optimized by the compiler.

For example Option<usize> may occupy up to 16 bytes, using 8 additional bytes for the discriminator to represent a flag such as 0x00 and 0x01. In contrast using the NonZeroUsize as in Option<NonZeroUsize> the memory consumption may shrink to 8 bytes in total. using the unused bit of NonZeroUsize to represent the discriminator of the generic data type Option<T>

See https://doc.rust-lang.org/std/num/struct.NonZeroUsize.html

This enables some memory layout optimization. For example, Option<NonZeroUsize> is the same size as usize:

use std::mem::size_of;
assert_eq!(size_of::<Option<core::num::NonZeroUsize>>(), size_of::<usize>());

And analogous to it all other NonZero types https://doc.rust-lang.org/std/num/index.html

Please note, using an optimized Option<NonZeroX>, its enum-discriminator will be one of the ‘unused’ bit-combinations in the underlying integer representation, for example the bit combination all zero representing state Option::None.

Java – Wait for Multiple Processes

In Java, the function Process.onExit() creates a CompletableFuture as exit handler and this is the enabling feature in Java to wait for any termination of a set of processes.

public Process anyProcTermination(List<Process> procs)  {
CompletableFuture<Process>[] exitHandlers =
procs.stream()
.map(p -> p.onExit())
.toArray(CompletableFuture[]::new);
CompletableFuture<Object> exitHandle = CompletableFuture.anyOf(exitHandlers);
return (Process) exitHandle.join();
}

IPv6 resolving hostnames faster

The title of this post might be misleading. IPv6 is not faster than IPv4, but nowadays applications assume IPv6 being the default, having an implication onto the time to establish a connection to a remote host.

Before an application is able to connect to a specific host, first its hostname has got to be resolved via DNS to get to know the corresponding remote IP address.

By default the resolver tries to resolve the corresponding IPv6 address first. If this does not succeed within specific timeout, the resolver is falling back to IPv4.

Thus, if you want to speed up the connection times of your applications, make sure both, your local network and also your internet provider, are supporting IPv6.

If your internet provider does not support native IPv6, it might be better to disable IPv6 in your local network as well, to prevent your local applications from using IPv6 at all.

Do not contract an internet provider for your home area network without IPv6 support!

From the other side of the table, in case you are providing an internet service, your customers might try to connect to your IPv6 service endpoint first, just falling back to IPv4 later. So, your IPv6 endpoint will provide a better usability for your customers.

New Intel Tiger Lake CPU still suffering Meltdown & Spectre

Just came across an ad for the new Lenovo X1 Carbon Gen9, containing an Intel Tiger Lake CPU . This notebook looks interesting to me. I thought, this might replace my aging notebook. And as usual I checked the promoted internal CPU for the security vulnerabilities Specte & Meltdown: https://meltdownattack.com/.

I checked the list of affected CPUs: https://software.intel.com/security-software-guidance/processors-affected-transient-execution-attack-mitigation-product-cpu-model

I must tell you, I am very disappointed! The X1 Carbon Gen9 contains a the Intel CPU family “Tiger Lake”, still being listed as “affected processor” by the Specte & Meltdown security vulnerability! The affected Tiger Lake CPUs are: i7-1185G7, i7-1165G7, i5-1135G7, i3-1115G4, i3-1125G4, i7-1160G7, i5-1130G7, i3-1120G4, and i3-1110G4.

Unbelievable!! Intel did not manage to release a Spectre & Meltdown proof CPU within 3 years!

Well, as it seems, waiting for a notebook containing a Spectre & Meltdown proof CPU, I will never purchase any notebook containing the CPU family Tiger Lake. Probably I will have to wait way way longer for Intel to fix this security vulnerability in future CPUs 🙁

Rust Function implementing Generator

The following example demonstrates how to implement a Rust-function implementing a generator (unstable feature in nightly compiler)

#![feature(generators, generator_trait)]
use std::ops::{Generator, GeneratorState};
use std::pin::Pin;

fn generator() -> impl Generator<
Yield=(),
Return=()>
{
   let generator = || {
      println!("2");
      yield;
      println!("4");
    };
   generator
}

#[derive(Debug, Clone)]
enum MyError {
   Fault
}

fn generator2() -> impl Generator<
   Yield=Result<u32, MyError>,
   Return=&'static str>
{
   let generator = || {
      yield Ok(1);
      yield Err(MyError::Fault);
      return "foo";
   };
   generator
}

fn main() {
   let mut generator = generator();

   println!("1");
   Pin::new(&mut generator).resume(());
   println!("3");
   Pin::new(&mut generator).resume(());
   println!("5");

   println!("-------");

   let mut generator2 = generator2();

   match Pin::new(&mut generator2).resume(()) {
      GeneratorState::Yielded(val) => { println!("{:?}", val); }
      _ => panic!("unexpected value from resume"),
   }

   match Pin::new(&mut generator2).resume(()) {
      GeneratorState::Yielded(val) => { println!  ("{:?}", val); }
      _ => panic!("unexpected value from resume"),
   }

   match Pin::new(&mut generator2).resume(()) {
      GeneratorState::Complete(val) => { println!("{}", val); }
      _ => panic!("unexpected value from resume"),
   }
}