Skip to content

Instantly share code, notes, and snippets.

@jhass
Last active November 12, 2015 19:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jhass/cbc509e8ed1025b22a70 to your computer and use it in GitHub Desktop.
Save jhass/cbc509e8ed1025b22a70 to your computer and use it in GitHub Desktop.
Platform indepedent standard library for Crystal
lib LibC
# Common bindings go here
fun chdir(...)
fun printf(...)
fun wprintf(...)
fun atoi(...)
fun watoic(...)
end
ifdef windows
require "./windows_c_wrapper"
elsdef linux
require "./linux_c_wrapper"
end
lib LibC
# Platform specific bindings that might not exist on other platforms or
# are incompatible
fun linux_only(...)
fun different_signature(...)
end
module CWrapper
# Boilerplate could be reduced by macro usage, for example a macro method_missing
def self.stat(path)
LibC.stat(path)
end
def self.chdir(dir)
LibC.chdir(dir)
end
def self.atoi(string)
LibC.atoi(string)
end
def self.printf(format, args)
LibC.printf(format, args)
end
end
require "./lib_c"
class File
def self.stat(path)
CWrapper.stat(path)
end
end
class Dir
def self.chdir(dir)
CWrapper.chdir(dir)
end
end
class String
def to_i
Cwrapper.atoi(self)
end
end
module Kernel
def printf(format, args)
CWrapper.printf(format, args)
end
end
lib LibC
# Platform specific bindings that might not exist on other platforms or
# are incompatible
fun windows_only(...)
fun different_signature(...)
end
module CWrapper
# Boilerplate could be reduced by macro usage, for example a macro method_missing
def self.stat(path)
LibC.stat(path.to_utf16)
end
def self.chdir(dir)
LibC.chdir(dir.to_utf16)
end
def self.atoi(string)
LibC.watoi(string.to_utf16)
end
def self.printf(format, args)
LibC.wprintf(format.to_utf16, args)
end
end
@jhass
Copy link
Author

jhass commented Mar 18, 2015

An application that needs to care about different semantics between two functions, like atoi and watoi on Windows, is already by the fact that it needs to differentiate these, platform dependent. It has two choices:

  1. It can regain platform independence by adding a new functionality to the standard library that has a common interface and behaviour on all platforms. The platform specific details of this implementation would be implemented in the respective wrapper modules. Due to Crystals open class model, this is trivial, however this scheme can also easily be replicated in the application itself.
  2. It can stay platform dependent by bypassing the wrappers and calling the bindings directly in the application code, LibC.atoi instead of String#to_i or CWrapper.atoi.

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