[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Fast 32 bit ints in ruby ?

devesh

11/20/2006 8:40:00 PM

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
end
def & (other)
p = self.clone
p.magicCInt &= other.magicCInt
end
def == (other)
return (other.magicCInt == self.magicCInt)
end
alias_method :== :eql?
#.. And other methods
end

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#==)

Thanks,
-Devesh

1 Answer

Joel VanderWerf

11/20/2006 11:12:00 PM

0

devesh wrote:
> 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:

What about packing the 4 bytes in a string:

p "192.168.1.2".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:

http://raa.ruby-lang.org/proje...

never used it though...

--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407