Fast 32 bit ints in ruby?

Hi Folks,

I want an efficient implementation of an Ipaddress class. The ones I
have seen (for eg: lib/ipaddr.rb) all represent things internally in
the form of a Bignum. And that is turning out to be a bottleneck for
me. Ideally I would want to create some kind of a class, in which I can
wrap in a normal C int and then operate with it directly. Does anyone
know of how to do this ?. Another way would be to create a struct
wrapping this int and then access that from my C extension (Like it is
done with the Jukebox example in the Pickaxe book). I am new to ruby
and to mixing C and ruby. What would be a good way to achieve the
following interface:

class IPAddress

# Some code to declare @magicCInt as a C type int
# magicCInt is a good'ol C type int (of full 32 bits)
# It is not a Bignum/Fixnum

def initizialize
	@magicCInt = 0
def & (other)
	p = self.clone
	p.magicCInt &= other.magicCInt
def == (other)
	return (other.magicCInt == self.magicCInt)
alias_method :== :eql?
#.. And other methods


Can I achieve this using RubyInline. It would be great if the more
experienced of you could provide me with a code sketch to get me
started ?

PS: My apologies if this question has been asked before, I would be
grateful if you could point me to some other thread which seeks to
answer this.

PPS: I am writing some networkingish code and comparing two ipaddress’s
is sadly my biggest bottleneck (Bignum#==)


devesh wrote:

and to mixing C and ruby. What would be a good way to achieve the
following interface:

What about packing the 4 bytes in a string:

p “”.split(".").map{|d|Integer(d)}.pack(“C*”)

==> “\300\250\001\002”

Unfortunately, there’s no fast way to do & on strings of bits in pure
ruby, AFAIK. Now, that might be a nice extension: bit operations on
strings, including reading and writing bits n1 through n2 as a substring
of bits, & ^ | on substrings of bits, etc.

Actually, maybe this will help:

never used it though…

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs