Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,34 @@
/* rc_strdup.c */
#include <stdlib.h> /* free() */
#include <string.h> /* strdup() */
#include <ruby.h>
static VALUE
rc_strdup(VALUE obj, VALUE str_in)
{
VALUE str_out;
char *c, *d;
/*
* Convert Ruby value to C string. May raise TypeError if the
* value isn't a string, or ArgumentError if it contains '\0'.
*/
c = StringValueCStr(str_in);
/* Call strdup() and perhaps raise Errno::ENOMEM. */
d = strdup(c);
if (d == NULL)
rb_sys_fail(NULL);
/* Convert C string to Ruby string. */
str_out = rb_str_new_cstr(d);
free(d);
return str_out;
}
void
Init_rc_strdup(void)
{
VALUE mRosettaCode = rb_define_module("RosettaCode");
rb_define_module_function(mRosettaCode, "strdup", rc_strdup, 1);
}

View file

@ -0,0 +1,3 @@
# extconf.rb
require 'mkmf'
create_makefile('rc_strdup')

View file

@ -0,0 +1,3 @@
# demo.rb
require 'rc_strdup'
puts RosettaCode.strdup('This string gets duplicated.')

View file

@ -0,0 +1,14 @@
require 'ffi'
module LibC
extend FFI::Library
ffi_lib FFI::Platform::LIBC
attach_function :strdup, [:string], :pointer
attach_function :free, [:pointer], :void
end
string = "Hello, World!"
duplicate = LibC.strdup(string)
puts duplicate.get_string(0)
LibC.free(duplicate)

View file

@ -0,0 +1,13 @@
require 'fiddle'
# Find strdup(). It takes a pointer and returns a pointer.
strdup = Fiddle::Function
.new(Fiddle::Handle['strdup'],
[Fiddle::TYPE_VOIDP], Fiddle::TYPE_VOIDP)
# Call strdup().
# - It converts our Ruby string to a C string.
# - It returns a Fiddle::Pointer.
duplicate = strdup.call("This is a string!")
puts duplicate.to_s # Convert the C string to a Ruby string.
Fiddle.free duplicate # free() the memory that strdup() allocated.

View file

@ -0,0 +1,12 @@
require 'fiddle'
require 'fiddle/import'
module C
extend Fiddle::Importer
dlload Fiddle::Handle::DEFAULT
extern 'char *strdup(char *)'
end
duplicate = C.strdup("This is a string!")
puts duplicate.to_s
Fiddle.free duplicate

View file

@ -0,0 +1,33 @@
require 'rubygems'
require 'inline'
class InlineTester
def factorial_ruby(n)
(1..n).inject(1, :*)
end
inline do |builder|
builder.c <<-'END_C'
long factorial_c(int max) {
long result = 1;
int i;
for (i = 1; i <= max; ++i)
result *= i;
return result;
}
END_C
end
inline do |builder|
builder.include %q("math.h")
builder.c <<-'END_C'
int my_ilogb(double value) {
return ilogb(value);
}
END_C
end
end
t = InlineTester.new
11.upto(14) {|n| p [n, t.factorial_ruby(n), t.factorial_c(n)]}
p t.my_ilogb(1000)