Full Code of aisamanra/rust-haskell-ffi for AI

master e7114da60484 cached
6 files
5.5 KB
1.6k tokens
8 symbols
1 requests
Download .txt
Repository: aisamanra/rust-haskell-ffi
Branch: master
Commit: e7114da60484
Files: 6
Total size: 5.5 KB

Directory structure:
gitextract_314mv98u/

├── LICENSE
├── Makefile
├── README.md
├── fact.rs
├── main.hs
└── point.rs

================================================
FILE CONTENTS
================================================

================================================
FILE: LICENSE
================================================
This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to <http://unlicense.org>



================================================
FILE: Makefile
================================================
RC = LD_LIBRARY_PATH=/usr/local/lib rustc
GHC = ghc

all: main

libfact.a: fact.rs
	$(RC) --crate-type staticlib fact.rs

libpoint.a: point.rs
	$(RC) --crate-type staticlib point.rs

main: libfact.a libpoint.a main.hs
	$(GHC) main.hs libfact.a libpoint.a -lpthread -o main

clean:
	rm -f libfact.a libpoint.a main.hi main.o main


================================================
FILE: README.md
================================================
# Rust-Haskell FFI Example

A lot of Haskell people I've talked to are excited about the prospect of
using Rust as a replacement for C in certain speed-critical or low-level
parts of their application. To that end, and in light of the recent
(as of this writing) Rust 1.0 alpha release, I've shown here a small
example of calling Rust from Haskell.

This contains a single Haskell file and two Rust libraries which Haskell
can call out to.
The first Rust library is contained in `fact.rs` and implements a simple
factorial, which is easier to wrap; the second is contained in `point.rs`
and demonstrates allocating memory in Rust, passing it to Haskell, using
wrapped Rust functions to manipulate it, and finally allowing Haskell's
GC to call back into Rust to free it.

This of course requires GHC and a reasonably recent version of rustc
installed. This version has been tested with GHC versions `7.8.4` and
`7.10.1`, and the following rustc versions:

    1.0.0 (a59de37e9 2015-05-13) (built 2015-05-14)

All the examples here I release into the public domain.


================================================
FILE: fact.rs
================================================
#![crate_type = "lib"]

#[no_mangle]
pub extern fn fact(x: u64) -> u64 {
    match x {
        0 => 1,
        _ => x * fact(x-1),
    }
}


================================================
FILE: main.hs
================================================
{-# LANGUAGE ForeignFunctionInterface #-}

import Foreign
import Foreign.C.Types
import Foreign.ForeignPtr

-- Wrapping the fact.rs module...
foreign import ccall "fact"
  c_fact :: CULong -> CULong

fact :: Int -> Int
fact = fromIntegral . c_fact . fromIntegral

-- A little bit more work to wrap the point.rs module; I also
-- don't bother to write a proper representation for the
-- underlying Point, which ought to be an instance of Storable
-- if we want to manipulate it in Rust-land or do pointer
-- arithmetic.
type Point = ForeignPtr PointRepr
data PointRepr

foreign import ccall safe "mk_point"
  mk_point :: CULong -> CULong -> IO (Ptr PointRepr)

foreign import ccall safe "add_point"
  add_point :: Ptr PointRepr -> Ptr PointRepr -> IO ()

foreign import ccall safe "print_point"
  print_point :: Ptr PointRepr -> IO ()

foreign import ccall safe "&free_point"
  free_point :: FunPtr (Ptr PointRepr -> IO ())

-- We use the free_point function as a finalizer when we
-- create a point; this lets the Haskell GC take over for
-- us.
mkPoint :: Int -> Int -> IO Point
mkPoint x y = do
  ptr <- mk_point (fromIntegral x) (fromIntegral y)
  newForeignPtr free_point ptr

-- This modifies the first point in-place.
addPoint :: Point -> Point -> IO ()
addPoint x y = withForeignPtr x (\ x' ->
               withForeignPtr y (\ y' ->
                 add_point x' y'))

-- This prints its argument
printPoint :: Point -> IO ()
printPoint p = withForeignPtr p print_point

-- Testing the point functions; we don't need to free
-- explicitly because GHC should call our finalizer
points :: IO ()
points = do
  a <- mkPoint 2 3
  b <- mkPoint 1 1
  addPoint a b
  printPoint a

-- And here we go!
main :: IO ()
main = do
  putStr "fact(5) = "
  print (fact 5)
  points


================================================
FILE: point.rs
================================================
#![crate_type = "lib"]

// We aren't exposing the internals of this, so I don't bother giving it
// a C representation.
pub struct Point {
    x: u64,
    y: u64,
}

// Rust-land functions...
impl Point {
    fn new(x: u64, y: u64) -> Point {
        Point { x: x, y: y }
    }

    fn add_mut(&mut self, p: &Point) {
        self.x = self.x + p.x;
        self.y = self.y + p.y;
    }
}

// What we're doing here is a little bit unsafe---by exposing
// these elsewhere, we effectively transfer the 'ownership' out
// of Rust-land. In this case, we'll have a corresponding free
// function which takes ownership back again.
#[no_mangle]
pub extern fn mk_point(x: u64, y: u64) -> Box<Point> {
    Box::new(Point::new(x, y))
}

// We free something in Rust by… taking ownership of it and doing nothing.
#[no_mangle]
pub extern fn free_point(_: Box<Point>) {}

// Wrap our add_mut method for exporting.
#[no_mangle]
pub extern fn add_point(p1: &mut Point, p2: &Point) {
    p1.add_mut(p2);
}

// Wrap our print method for exporting.
#[no_mangle]
pub extern fn print_point(p: &Point) {
    println!("Point(x={}, y={})", p.x, p.y);
}
Download .txt
gitextract_314mv98u/

├── LICENSE
├── Makefile
├── README.md
├── fact.rs
├── main.hs
└── point.rs
Download .txt
SYMBOL INDEX (8 symbols across 2 files)

FILE: fact.rs
  function fact (line 4) | pub extern fn fact(x: u64) -> u64 {

FILE: point.rs
  type Point (line 5) | pub struct Point {
    method new (line 12) | fn new(x: u64, y: u64) -> Point {
    method add_mut (line 16) | fn add_mut(&mut self, p: &Point) {
  function mk_point (line 27) | pub extern fn mk_point(x: u64, y: u64) -> Box<Point> {
  function free_point (line 33) | pub extern fn free_point(_: Box<Point>) {}
  function add_point (line 37) | pub extern fn add_point(p1: &mut Point, p2: &Point) {
  function print_point (line 43) | pub extern fn print_point(p: &Point) {
Condensed preview — 6 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (6K chars).
[
  {
    "path": "LICENSE",
    "chars": 1211,
    "preview": "This is free and unencumbered software released into the public domain.\n\nAnyone is free to copy, modify, publish, use, c"
  },
  {
    "path": "Makefile",
    "chars": 329,
    "preview": "RC = LD_LIBRARY_PATH=/usr/local/lib rustc\nGHC = ghc\n\nall: main\n\nlibfact.a: fact.rs\n\t$(RC) --crate-type staticlib fact.rs"
  },
  {
    "path": "README.md",
    "chars": 1064,
    "preview": "# Rust-Haskell FFI Example\n\nA lot of Haskell people I've talked to are excited about the prospect of\nusing Rust as a rep"
  },
  {
    "path": "fact.rs",
    "chars": 139,
    "preview": "#![crate_type = \"lib\"]\n\n#[no_mangle]\npub extern fn fact(x: u64) -> u64 {\n    match x {\n        0 => 1,\n        _ => x * "
  },
  {
    "path": "main.hs",
    "chars": 1774,
    "preview": "{-# LANGUAGE ForeignFunctionInterface #-}\n\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.ForeignPtr\n\n-- Wrapping "
  },
  {
    "path": "point.rs",
    "chars": 1129,
    "preview": "#![crate_type = \"lib\"]\n\n// We aren't exposing the internals of this, so I don't bother giving it\n// a C representation.\n"
  }
]

About this extraction

This page contains the full source code of the aisamanra/rust-haskell-ffi GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 6 files (5.5 KB), approximately 1.6k tokens, and a symbol index with 8 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!