├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── main.lua ├── run.sh └── src ├── arrays.lua ├── arrays.rs ├── lib.rs ├── loverust.lua ├── strings.lua ├── strings.rs ├── tables.lua └── tables.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | **/*.rs.bk 3 | Cargo.lock 4 | 5 | inspect.lua 6 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "loverust" 3 | version = "0.1.0" 4 | authors = ["Skeletonxf "] 5 | 6 | [dependencies] 7 | libc = "0.2" 8 | 9 | [lib] 10 | name = "loverust" 11 | crate-type = ["dylib"] 12 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Rust2d 2 | 3 | This is a work in progress library of utility code for creating a project where love2d Lua code can call Rust code to do the heavy lifting. Love2d is "a framework for making 2D games in the Lua programming language". This project provides Rust code compiled to a dynamic library which is then called via LuaJIT's FFI. The 'C' code that LuaJIT calls is then wrapped in lua code. Rust, unlike C or Lua has a (first class) package manager from which we can access a huge number of libraries very easily. Exposing these to Lua to should be able to save a lot of effort when writing games or other software. Although the project is focused on applications for use with the Love2d framework, the library code should run fine in any LuaJIT interpreter. 4 | 5 | ## Examples 6 | - Small [pong game](https://github.com/Skeletonxf/rust2d/tree/pong) using Rust for the update function and then lots of observers to draw it in love2d. 7 | 8 | # Modules 9 | 10 | - **arrays** Code for sending and recieving arrays over FFI. 11 | - **strings** Code for sending and recieving strings over FFI. 12 | - **tables** Work in progress code for sending Lua tables over FFI. 13 | 14 | ## Non modules 15 | 16 | These can be sent freely with no wrapping. 17 | 18 | - **numbers** 19 | - **booleans** 20 | 21 | # Library 22 | 23 | Each module written on the Rust side has a Lua module by the same name and location which is responsible for calling the Rust code. The only exceptions to this are testing code in main.lua, lib.rs and loverust.lua. The former 2 are where new library functionality is tested, and the latter is responsible for loading the Rust code to call from Lua. 24 | 25 | # Notes 26 | 27 | The Rust FFI omnibus, Rust tutorial and LuaJIT FFI tutorial pages have been extremely helpful for me in creating this project. 28 | 29 | - http://jakegoulding.com/rust-ffi-omnibus/ 30 | - https://doc.rust-lang.org/tutorial.html 31 | - http://luajit.org/ext_ffi.html 32 | -------------------------------------------------------------------------------- /main.lua: -------------------------------------------------------------------------------- 1 | local ffi = require 'ffi' 2 | 3 | ffi.cdef[[ 4 | void hello(); 5 | bool is_odd(unsigned int number); 6 | char * print_and_return(const char *string); 7 | void print(const char *string); 8 | uint32_t add_two_numbers(uint32_t, uint32_t); 9 | // mirror the rust Vector2 struct definition 10 | typedef struct vector2 { 11 | uint32_t x; 12 | uint32_t y; 13 | } vector2_t; 14 | vector2_t vector2_swap(vector2_t); 15 | ]] 16 | 17 | local loverust = require 'src.loverust' 18 | 19 | local arrays = require 'src.arrays' 20 | local strings = require 'src.strings' 21 | 22 | loverust.hello() 23 | print('Is 1 odd? ' .. tostring(loverust.is_odd(1))) 24 | 25 | local cstring = loverust.print_and_return("💖plswork") 26 | local luaSting = strings.copy(cstring) 27 | print('It worked! ' .. luaSting) 28 | strings.free(cstring) 29 | print('And no memory leak!') 30 | 31 | print('We still have the lua string from Rust') 32 | loverust.print(luaSting) 33 | 34 | print('Addition ' .. loverust.add_two_numbers(1, 2)) 35 | 36 | local carray = ffi.new("int[3]", {1,2,3}) 37 | print('Rust inspection of c array:') 38 | loverust.print_array(carray, 3) 39 | 40 | local vector2 = ffi.new("struct vector2", {1, 2}) 41 | local swapped = loverust.vector2_swap(vector2) 42 | 43 | print((ffi.new("int[3]", {1,4,9}))[0]) 44 | 45 | local array = arrays.new(loverust.generate_array()) 46 | print(array) 47 | array:free() 48 | array = nil 49 | 50 | local complicatedTable = { 51 | 1,2,{ 52 | 3,5,6, 53 | baz = 'foobaz' 54 | },4, 55 | baz = 4, 56 | barbaz = true, 57 | foo = 'bar', 58 | foobar = { 59 | 1, 6, 'baz', 60 | foobaz = { 61 | 4, 'bazfoo' 62 | } 63 | } 64 | } 65 | 66 | local tables = require 'src.tables' 67 | tables.export(complicatedTable) 68 | -------------------------------------------------------------------------------- /run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | if cargo build --release ; then 3 | love . 4 | else 5 | echo "Build failed" 6 | fi 7 | -------------------------------------------------------------------------------- /src/arrays.lua: -------------------------------------------------------------------------------- 1 | local arrays = { 2 | _DESCRIPTION = [[ 3 | A wrapper around a struct containing an array originating from Rust. 4 | Luajit gives us a reference to cdata arrays so we can index the values. 5 | The struct contains a length parameter so we know how many elements 6 | are in the array. 7 | ]], 8 | _URL = 'https://github.com/Skeletonxf/rust2d', 9 | _LICENSE = 'MPL2' 10 | } 11 | 12 | local ffi = require 'ffi' 13 | local loverust = require 'src.loverust' 14 | 15 | ffi.cdef[[ 16 | void print_array(const uint32_t *array, size_t length); 17 | 18 | // wrapper around an array for recieving from rust functions 19 | typedef struct array { 20 | double * data; 21 | size_t length; 22 | } array_t; 23 | void free_array(array_t); 24 | array_t generate_array(); 25 | ]] 26 | 27 | 28 | local Array = {} 29 | Array.__index = Array 30 | 31 | -- wraps a struct array held in C 32 | function arrays.new(structArray) 33 | local array = {} 34 | array.struct = structArray 35 | setmetatable(array, Array) 36 | return array 37 | end 38 | 39 | function Array.length(self) 40 | if not self.struct then 41 | error('No struct to query', 2, debug.traceback()) 42 | end 43 | return tonumber(self.struct.length) 44 | end 45 | 46 | function Array.get(self, i) 47 | if not self.struct then 48 | error('No struct to query', 2, debug.traceback()) 49 | end 50 | local data = self.struct.data 51 | if i >= self:length() or i < 0 then 52 | error('Out of bounds for array', 2, debug.traceback()) 53 | end 54 | return self.struct.data[i] 55 | end 56 | 57 | function Array.free(self) 58 | -- call Rust to free the vector held in the struct 59 | -- and then nil the fields in this wrapper 60 | loverust.free_array(self.struct) 61 | self = {} 62 | end 63 | 64 | function Array.__tostring(self) 65 | local s = 'CArray[' 66 | local i = 0 67 | while i < (self:length()) do 68 | s = s .. tostring(self:get(i)) 69 | if i < self:length() - 1 then 70 | s = s .. ',' 71 | end 72 | i = i + 1 73 | end 74 | s = s .. ']' 75 | return s 76 | end 77 | 78 | return arrays 79 | -------------------------------------------------------------------------------- /src/arrays.rs: -------------------------------------------------------------------------------- 1 | extern crate libc; 2 | 3 | use libc::size_t; 4 | 5 | // Same precision as Lua number (double) 6 | // also the same as libc::c_double; 7 | type LuaNumber = f64; 8 | 9 | use std; 10 | use std::slice; 11 | 12 | /** 13 | * A struct that can be mirrored in C to facilitate returning arrays to C 14 | * that can then be indexed freely via Lua as cdata. 15 | */ 16 | #[repr(C)] 17 | pub struct Array { 18 | data: *mut LuaNumber, 19 | length: size_t, 20 | } 21 | 22 | #[no_mangle] 23 | pub extern "C" fn free_array(array: Array) { 24 | assert!(!array.data.is_null()); 25 | unsafe { 26 | // reclaim the Vec so it can be dropped 27 | Box::from_raw(array.data); 28 | } 29 | } 30 | 31 | /** 32 | * Converts a Rust Vec to an Array to pass through FFI 33 | */ 34 | pub fn vec_to_array(mut data: Vec) -> Array { 35 | let array = Array { 36 | data: data.as_mut_ptr(), 37 | length: data.len(), 38 | }; 39 | // forget about the Vec so it is not dropped 40 | // at the end of this function 41 | std::mem::forget(data); 42 | array 43 | } 44 | 45 | #[no_mangle] 46 | pub extern "C" fn generate_array() -> Array { 47 | vec_to_array(vec![1.0f64, 4.0f64, 3.0f64, 8.0f64]) 48 | } 49 | 50 | /** 51 | * Prints an Array originating from LuaJIT 52 | * 53 | * # Safety 54 | * 55 | * The array pointer must be valid. 56 | */ 57 | #[no_mangle] 58 | pub unsafe extern "C" fn print_array(c_array_pointer: *const u32, length: size_t) { 59 | let array_slice = { 60 | assert!(!c_array_pointer.is_null()); 61 | 62 | slice::from_raw_parts(c_array_pointer, length as usize) 63 | }; 64 | println!("{:?}", array_slice); 65 | } 66 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![allow(clippy::missing_safety_doc)] 2 | 3 | extern crate libc; 4 | 5 | use std::fmt; 6 | 7 | use std::ffi::CStr; 8 | use std::os::raw::c_char; 9 | 10 | use strings::to_c_owned_string; 11 | use strings::to_rust_string; 12 | 13 | pub mod arrays; 14 | 15 | pub mod tables; 16 | 17 | pub mod strings; 18 | 19 | #[no_mangle] 20 | pub extern "C" fn hello() { 21 | println!("Hello from rust"); 22 | } 23 | 24 | #[no_mangle] 25 | pub extern "C" fn is_odd(n: u16) -> bool { 26 | (n % 2) == 0 27 | } 28 | 29 | /** 30 | * Prints the c string supplied 31 | * Unlike lua/c code this prints unicode properly 32 | */ 33 | #[no_mangle] 34 | pub unsafe extern "C" fn print(cstring: *const c_char) { 35 | let slice = CStr::from_ptr(cstring); 36 | match slice.to_str() { 37 | Ok(s) => println!("{}", s), 38 | Err(e) => eprintln!("{}", e), 39 | } 40 | } 41 | 42 | #[no_mangle] 43 | pub unsafe extern "C" fn print_and_return(c_string_pointer: *const c_char) -> *mut c_char { 44 | let mut rust_string = to_rust_string(c_string_pointer); 45 | // modify the rust String 46 | println!("Recieved {}", rust_string); 47 | rust_string.push('💖'); 48 | println!("Created {}", rust_string); 49 | to_c_owned_string(rust_string) 50 | } 51 | 52 | #[no_mangle] 53 | pub extern "C" fn add_two_numbers(x: u32, y: u32) -> u32 { 54 | x + y 55 | } 56 | 57 | /* 58 | * A struct that can be passed between C and Rust 59 | */ 60 | #[repr(C)] 61 | pub struct Vector2 { 62 | x: u32, 63 | y: u32, 64 | } 65 | 66 | /* 67 | * Display implementation for easy viewing 68 | */ 69 | impl fmt::Display for Vector2 { 70 | fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { 71 | fmt.write_str("{")?; 72 | fmt.write_str(&self.x.to_string())?; 73 | fmt.write_str(", ")?; 74 | fmt.write_str(&self.y.to_string())?; 75 | fmt.write_str("}")?; 76 | Ok(()) 77 | } 78 | } 79 | 80 | #[no_mangle] 81 | pub extern "C" fn vector2_swap(vector2: Vector2) -> Vector2 { 82 | println!("Before {}", vector2); 83 | let swapped = Vector2 { 84 | x: vector2.y, 85 | y: vector2.x, 86 | }; 87 | println!("After {}", swapped); 88 | swapped 89 | } 90 | -------------------------------------------------------------------------------- /src/loverust.lua: -------------------------------------------------------------------------------- 1 | local ffi = require 'ffi' 2 | -- Windows 3 | if love.system.getOS() == 'Windows' then 4 | return ffi.load('./target/release/loverust.dll') 5 | end 6 | -- POSIX 7 | return ffi.load('./target/release/libloverust.so') 8 | -------------------------------------------------------------------------------- /src/strings.lua: -------------------------------------------------------------------------------- 1 | local strings = { 2 | _DESCRIPTION = [[ 3 | Module for manipulating strings over FFI 4 | ]], 5 | _URL = 'https://github.com/Skeletonxf/rust2d', 6 | _LICENSE = 'MPL2' 7 | } 8 | 9 | local ffi = require 'ffi' 10 | local loverust = require 'src.loverust' 11 | 12 | ffi.cdef[[ 13 | void free_c_owned_string(char *string); 14 | ]] 15 | 16 | function strings.copy(c_string) 17 | return ffi.string(c_string) 18 | end 19 | 20 | function strings.free(c_string) 21 | loverust.free_c_owned_string(c_string) 22 | end 23 | 24 | -- Copies a C string to a Lua string, then frees 25 | -- the C string, leaving the Lua copy intact 26 | function strings.take(c_string) 27 | local luaString = strings.copy(c_string) 28 | strings.free(c_string) 29 | return luaString 30 | end 31 | 32 | return strings 33 | -------------------------------------------------------------------------------- /src/strings.rs: -------------------------------------------------------------------------------- 1 | extern crate libc; 2 | 3 | use std::ffi::CStr; 4 | use std::ffi::CString; 5 | use std::os::raw::c_char; 6 | 7 | /* 8 | * Functions for handling FFI and Strings on the Rust side. 9 | */ 10 | 11 | /** 12 | * Creates a Rust String from a C string pointer (ie originating from Lua) 13 | * 14 | * # Safety 15 | * 16 | * The string pointer must be valid. 17 | */ 18 | pub unsafe fn to_rust_string(c_string_pointer: *const c_char) -> String { 19 | assert!(!c_string_pointer.is_null()); 20 | 21 | CStr::from_ptr(c_string_pointer) 22 | .to_string_lossy() 23 | .into_owned() 24 | } 25 | 26 | /** 27 | * Creates a C string pointer from a Rust String and transfers ownership 28 | * so that the string can live long enough to be converted to a lua string 29 | * before Rust deallocates it and causes the pointer to be pointing 30 | * at nothing. The pointer must be retaken in Rust to free the memory afterwards. 31 | */ 32 | pub fn to_c_owned_string(rust_string: String) -> *mut c_char { 33 | let cstring = CString::new(rust_string).unwrap(); // todo avoid unwrap 34 | cstring.into_raw() 35 | } 36 | 37 | /* 38 | * Retakes the pointer created by to_c_owned_string 39 | * to free the memory 40 | */ 41 | #[no_mangle] 42 | pub unsafe extern "C" fn free_c_owned_string(pointer: *mut c_char) { 43 | if pointer.is_null() { 44 | eprintln!("Expected to recieve non null pointer to free"); 45 | return; 46 | } 47 | // retake pointer to free memory 48 | let _ = CString::from_raw(pointer); 49 | } 50 | -------------------------------------------------------------------------------- /src/tables.lua: -------------------------------------------------------------------------------- 1 | local tables = { 2 | _DESCRIPTION = [[ 3 | A utility to convert somewhat arbitrary lua tables into a format that 4 | can be manipulated in Rust and sent back. 5 | ]], 6 | _URL = 'https://github.com/Skeletonxf/rust2d', 7 | _LICENSE = 'MPL2' 8 | } 9 | 10 | local ffi = require 'ffi' 11 | local loverust = require 'src.loverust' 12 | 13 | -- Opaque object 14 | -- http://jakegoulding.com/rust-ffi-omnibus/objects/ 15 | ffi.cdef[[ 16 | typedef struct table_S table_t; 17 | table_t * tables_new_empty_table(); 18 | void tables_add_string(table_t *, const char *string); 19 | void tables_add_number(table_t *, double); 20 | void tables_add_nil(table_t *); 21 | void tables_add_table(table_t *, table_t *); 22 | void tables_put_string_string(table_t *, const char *string, const char *string); 23 | void tables_put_string_boolean(table_t *, const char *string, bool); 24 | void tables_put_string_number(table_t *, const char *string, double); 25 | void tables_put_string_table(table_t *, const char *string, table_t *); 26 | void tables_debug(table_t *); 27 | void tables_free_table(table_t *); 28 | ]] 29 | 30 | local arrays = require 'src.arrays' 31 | 32 | local Table = {} 33 | Table.__index = Table 34 | local table = {} 35 | 36 | local function export(lua_table, rust_table) 37 | -- First loop through numerical indexes 38 | -- in order and add to Rust Table array. 39 | for _, v in ipairs(lua_table) do 40 | -- This will turn the array into 1 indexed on the Rust side 41 | rust_table:add(v) 42 | lua_table[v] = nil 43 | end 44 | -- Now loop through other pairs and add to 45 | -- Rust Table hash map. 46 | for k, v in pairs(lua_table) do 47 | rust_table:put(k, v) 48 | end 49 | rust_table:debug() 50 | return rust_table 51 | end 52 | 53 | function tables.export(lua_table) 54 | return export(lua_table, table.new()) 55 | end 56 | 57 | function table.new() 58 | local o = {} 59 | o.table = loverust.tables_new_empty_table() 60 | setmetatable(o, Table) 61 | return o 62 | end 63 | 64 | -- Adds a value to the array part of the Rust Table 65 | function Table.add(self, value) 66 | if type(value) == 'number' then 67 | loverust.tables_add_number(self.table, value) 68 | end 69 | if type(value) == 'string' then 70 | loverust.tables_add_string(self.table, value) 71 | end 72 | if type(value) == 'nil' then 73 | loverust.tables_add_nil(self.table) 74 | end 75 | if type(value) == 'table' then 76 | -- subtable will be reclaimed by Rust code so does not need freeing 77 | local subtable = tables.export(value) 78 | loverust.tables_add_table(self.table, subtable.table) 79 | end 80 | end 81 | 82 | -- Adds a key - value pair to the hash map part of the Rust Table 83 | function Table.put(self, key, value) 84 | if type(key) == 'string' then 85 | if type(value) == 'string' then 86 | loverust.tables_put_string_string(self.table, key, value) 87 | end 88 | if type(value) == 'number' then 89 | loverust.tables_put_string_number(self.table, key, value) 90 | end 91 | if type(value) == 'boolean' then 92 | loverust.tables_put_string_boolean(self.table, key, value) 93 | end 94 | if type(value) == 'table' then 95 | -- subtable will be reclaimed by Rust code so does not need freeing 96 | local subtable = tables.export(value) 97 | loverust.tables_put_string_table(self.table, key, subtable.table) 98 | end 99 | end 100 | end 101 | 102 | function Table.debug(self) 103 | loverust.tables_debug(self.table) 104 | end 105 | 106 | -- Frees the reference to a Rust Table. 107 | function Table.free(self) 108 | loverust.tables_free_table(self.table) 109 | self = {} 110 | end 111 | 112 | return tables 113 | -------------------------------------------------------------------------------- /src/tables.rs: -------------------------------------------------------------------------------- 1 | extern crate libc; 2 | 3 | use std::collections::HashMap; 4 | use std::fmt; 5 | use std::os::raw::c_char; 6 | 7 | use strings; 8 | 9 | /** Same precision as Lua number (double) */ 10 | type LuaNumber = f64; 11 | 12 | /** Enumeration of lua table value types. 13 | * 14 | * Cannot hash because f64 is not hashable. 15 | */ 16 | #[derive(Debug, Clone)] 17 | pub enum LuaValue { 18 | Nil, 19 | Boolean(bool), 20 | Number(LuaNumber), 21 | String(String), 22 | Table(Table), 23 | // Userdata, Functions and Threads are not intended to be 24 | // passed through FFI 25 | } 26 | 27 | impl fmt::Display for LuaValue { 28 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 29 | match self { 30 | LuaValue::Nil => write!(f, "nil"), 31 | LuaValue::Boolean(boolean) => write!(f, "{}", boolean), 32 | LuaValue::Number(number) => write!(f, "{}", number), 33 | LuaValue::String(string) => write!(f, "{}", string), 34 | LuaValue::Table(table) => write!(f, "{}", table), 35 | } 36 | } 37 | } 38 | 39 | /** Enumeration of lua table key types. */ 40 | #[derive(Debug, Clone, Eq, PartialEq, Hash)] 41 | pub enum LuaKey { 42 | String(String), 43 | // Lua can hash other values but it is best to stick to Strings 44 | } 45 | 46 | impl fmt::Display for LuaKey { 47 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 48 | match self { 49 | LuaKey::String(s) => write!(f, "{}", s), 50 | } 51 | } 52 | } 53 | 54 | /// Rust representation of a Lua table 55 | #[derive(Debug, Clone)] 56 | pub struct Table { 57 | array: Vec, 58 | hash_map: HashMap, 59 | } 60 | 61 | impl PartialEq for Table { 62 | fn eq(&self, other: &Table) -> bool { 63 | // Lua tables are compared by pointer equality 64 | // and we cannot compare by contents here because f64 65 | // does not implement Eq so we do the same. 66 | std::ptr::eq(self, other) 67 | } 68 | } 69 | impl Eq for Table {} 70 | 71 | impl Table { 72 | fn new() -> Table { 73 | Table { 74 | array: Vec::new(), 75 | hash_map: HashMap::new(), 76 | } 77 | } 78 | 79 | fn add_value(&mut self, value: LuaValue) { 80 | self.array.push(value); 81 | } 82 | 83 | fn put_key_value(&mut self, key: LuaKey, value: LuaValue) { 84 | self.hash_map.insert(key, value); 85 | } 86 | } 87 | 88 | impl fmt::Display for Table { 89 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 90 | write!(f, "{{")?; // write literal { 91 | for (index, value) in self.array.iter().enumerate() { 92 | write!(f, "{}", value)?; 93 | if index < (self.array.len() - 1) { 94 | write!(f, ", ")?; 95 | } 96 | } 97 | if !self.array.is_empty() && !self.hash_map.is_empty() { 98 | write!(f, ", ")?; 99 | } 100 | for (index, (key, value)) in self.hash_map.iter().enumerate() { 101 | write!(f, "{}: {}", key, value)?; 102 | if index < (self.hash_map.len() - 1) { 103 | write!(f, ", ")?; 104 | } 105 | } 106 | write!(f, "}}") // write literal } 107 | } 108 | } 109 | 110 | /** 111 | * Gets a reference to the Table from a pointer (if it exists) 112 | * 113 | * # Safety 114 | * 115 | * The table pointer must be valid. 116 | */ 117 | unsafe fn get_table<'a>(pointer: *mut Table) -> Option<&'a mut Table> { 118 | if pointer.is_null() { 119 | return None; 120 | } 121 | Some(&mut *pointer) 122 | } 123 | 124 | // argument is boxed because it was heap allocated to give to lua and now we're unboxing it 125 | #[allow(clippy::boxed_local)] 126 | fn unbox(value: Box) -> T { 127 | *value 128 | } 129 | 130 | #[no_mangle] 131 | pub extern "C" fn tables_new_empty_table() -> *mut Table { 132 | Box::into_raw(Box::new(Table::new())) 133 | } 134 | 135 | #[no_mangle] 136 | pub unsafe extern "C" fn tables_debug(pointer: *mut Table) { 137 | match get_table(pointer) { 138 | Some(table) => println!("{:?}\n{}", table, table), 139 | None => eprintln!("Expected pointer to Table to not be null"), 140 | }; 141 | } 142 | 143 | #[no_mangle] 144 | pub unsafe extern "C" fn tables_add_number(pointer: *mut Table, value: LuaNumber) { 145 | match get_table(pointer) { 146 | Some(table) => table.add_value(LuaValue::Number(value)), 147 | None => eprintln!("Expected pointer to Table to not be null"), 148 | }; 149 | } 150 | 151 | #[no_mangle] 152 | pub unsafe extern "C" fn tables_add_string( 153 | pointer: *mut Table, 154 | c_string_pointer_value: *const c_char, 155 | ) { 156 | let value = strings::to_rust_string(c_string_pointer_value); 157 | match get_table(pointer) { 158 | Some(table) => table.add_value(LuaValue::String(value)), 159 | None => eprintln!("Expected pointer to Table to not be null"), 160 | }; 161 | } 162 | 163 | #[no_mangle] 164 | pub unsafe extern "C" fn tables_add_boolean(pointer: *mut Table, value: bool) { 165 | match get_table(pointer) { 166 | Some(table) => table.add_value(LuaValue::Boolean(value)), 167 | None => eprintln!("Expected pointer to Table to not be null"), 168 | }; 169 | } 170 | 171 | #[no_mangle] 172 | pub unsafe extern "C" fn tables_add_nil(pointer: *mut Table) { 173 | match get_table(pointer) { 174 | Some(table) => table.add_value(LuaValue::Nil), 175 | None => eprintln!("Expected pointer to Table to not be null"), 176 | }; 177 | } 178 | 179 | #[no_mangle] 180 | pub unsafe extern "C" fn tables_add_table(pointer: *mut Table, table_pointer_value: *mut Table) { 181 | match get_table(pointer) { 182 | Some(table) => { 183 | if table_pointer_value.is_null() { 184 | eprintln!("Expected pointer to Table value to not be null"); 185 | return; 186 | } 187 | // Take back ownership of the Table to move into the main Table 188 | // This means the Lua side does not need to free subtables 189 | // when constructing a Table 190 | let value = unbox(Box::from_raw(table_pointer_value)); 191 | table.add_value(LuaValue::Table(value)); 192 | } 193 | None => eprintln!("Expected pointer to Table to not be null"), 194 | }; 195 | } 196 | 197 | #[no_mangle] 198 | pub unsafe extern "C" fn tables_put_string_string( 199 | pointer: *mut Table, 200 | c_string_pointer_key: *const c_char, 201 | c_string_pointer_value: *const c_char, 202 | ) { 203 | match get_table(pointer) { 204 | Some(table) => { 205 | let key = strings::to_rust_string(c_string_pointer_key); 206 | let value = strings::to_rust_string(c_string_pointer_value); 207 | table.put_key_value(LuaKey::String(key), LuaValue::String(value)); 208 | } 209 | None => eprintln!("Expected pointer to Table to not be null"), 210 | }; 211 | } 212 | 213 | #[no_mangle] 214 | pub unsafe extern "C" fn tables_put_string_boolean( 215 | pointer: *mut Table, 216 | c_string_pointer_key: *const c_char, 217 | value: bool, 218 | ) { 219 | match get_table(pointer) { 220 | Some(table) => { 221 | let key = strings::to_rust_string(c_string_pointer_key); 222 | table.put_key_value(LuaKey::String(key), LuaValue::Boolean(value)); 223 | } 224 | None => eprintln!("Expected pointer to Table to not be null"), 225 | }; 226 | } 227 | 228 | #[no_mangle] 229 | pub unsafe extern "C" fn tables_put_string_number( 230 | pointer: *mut Table, 231 | c_string_pointer_key: *const c_char, 232 | value: LuaNumber, 233 | ) { 234 | match get_table(pointer) { 235 | Some(table) => { 236 | let key = strings::to_rust_string(c_string_pointer_key); 237 | table.put_key_value(LuaKey::String(key), LuaValue::Number(value)); 238 | } 239 | None => eprintln!("Expected pointer to Table to not be null"), 240 | }; 241 | } 242 | 243 | #[no_mangle] 244 | pub unsafe extern "C" fn tables_put_string_table( 245 | pointer: *mut Table, 246 | c_string_pointer_key: *const c_char, 247 | table_pointer_value: *mut Table, 248 | ) { 249 | match get_table(pointer) { 250 | Some(table) => { 251 | if table_pointer_value.is_null() { 252 | eprintln!("Expected pointer to Table value to not be null"); 253 | return; 254 | } 255 | let key = strings::to_rust_string(c_string_pointer_key); 256 | // Take back ownership of the Table to move into the main Table 257 | // This means the Lua side does not need to free subtables 258 | // when constructing a Table 259 | let value = unbox(Box::from_raw(table_pointer_value)); 260 | table.put_key_value(LuaKey::String(key), LuaValue::Table(value)); 261 | } 262 | None => eprintln!("Expected pointer to Table to not be null"), 263 | }; 264 | } 265 | 266 | #[no_mangle] 267 | pub unsafe extern "C" fn tables_free_table(pointer: *mut Table) { 268 | if pointer.is_null() { 269 | eprintln!("Expected pointer to Table to not be null"); 270 | return; 271 | } 272 | // take back to allow it to be freed when exiting this block 273 | Box::from_raw(pointer); 274 | } 275 | --------------------------------------------------------------------------------