Skip to content

Instantly share code, notes, and snippets.

@gmemstr
Created March 23, 2019 20:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gmemstr/ce6ff3cb429e62f59df90d9fc9201e72 to your computer and use it in GitHub Desktop.
Save gmemstr/ce6ff3cb429e62f59df90d9fc9201e72 to your computer and use it in GitHub Desktop.
Generates all possible CSS hex colours
package main
import (
"encoding/hex"
"os"
"strconv"
)
func main() {
f, err := os.OpenFile("colours.css", os.O_WRONLY, 0600)
if err != nil {
panic(err)
}
defer f.Close()
_, err = f.WriteString("hex {")
if err != nil {
panic(err)
}
for r := 0; r <= 255; r++ {
rHex := getHex(r)
for g := 0; g <= 255; g++ {
gHex := getHex(g)
for b := 0; b <= 255; b++ {
bHex := getHex(b)
formatted := "color: #" + rHex + gHex + bHex
_, err := f.Write([]byte(formatted))
if err != nil {
panic(err)
}
}
}
}
_, err = f.WriteString("}")
if err != nil {
panic(err)
}
}
func getHex(num int) string {
hexColour := hex.EncodeToString([]byte(strconv.Itoa(num)))
if len(hexColour) == 1 {
hexColour = "0" + hexColour
}
return hexColour
}
@gmemstr
Copy link
Author

gmemstr commented Mar 23, 2019

Current benchmarks have the time set to ~17 seconds writing to an SSD, and ~10 seconds on a ramdisk/tmpfs. The biggest bottleneck is definitely disk speed, followed closely by the getHex() function. Pretty sure that could be greatly optimized, just not sure how yet.

@gmemstr
Copy link
Author

gmemstr commented Mar 23, 2019

Version by @spoopy on Discord

package main

import (
	"fmt"
	"os"
	"strings"
)

func main() {
	f, err := os.OpenFile("colours.css", os.O_WRONLY, 0600)
	if err != nil {
		panic(err)
	}

	defer f.Close()

	var sb strings.Builder
	_, err = sb.WriteString("hex {")
	if err != nil {
		panic(err)
	}
	// 16777215 is FFFFFF in hex
	max := 16777215
	for i := 0; i <= max; i++ {
		_, err := fmt.Fprintf(&sb, "color: #%06X;\n", i)
		if err != nil {
			panic(err)
		}
	}
	_, err = sb.WriteString("}")
	if err != nil {
		panic(err)
	}
	_, err = f.WriteString(sb.String())
	if err != nil {
		panic(err)
	}
}

< 3 seconds on ramdisk

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment