// Native side of tycho_io.
//
// Path resolution mirrors what `tycho_shader_read_file` did before this package
// existed: try the path as given, then walk up from the executable directory up
// to 12 levels. Examples run from `_build/...`, so a path written relative to the
// repository root only resolves through that walk-up.

#borrow(path)
extern "c" fn read_file_ffi(path : Bytes, plen : Int32) -> Bytes = "tycho_io_read_file"

#borrow(path, data)
extern "c" fn write_file_ffi(
  path : Bytes,
  plen : Int32,
  data : Bytes,
  dlen : Int32,
) -> Int32 = "tycho_io_write_file"

#borrow(path)
extern "c" fn asset_exists_ffi(path : Bytes, plen : Int32) -> Int32 = "tycho_io_asset_exists"

extern "c" fn now_ms_ffi() -> UInt64 = "tycho_io_now_ms"

fn c_read_file(path : String) -> Bytes {
  let p = @utf8.encode(path)
  read_file_ffi(p, p.length())
}

fn c_write_file(path : String, data : Bytes) -> Int32 {
  let p = @utf8.encode(path)
  write_file_ffi(p, p.length(), data, data.length())
}

fn c_asset_exists(path : String) -> Int32 {
  let p = @utf8.encode(path)
  asset_exists_ffi(p, p.length())
}

fn c_now_ms() -> UInt64 {
  now_ms_ffi()
}