Version française
Home     About     Download     Resources     Contact us    
Browse thread
[oliver: Re: [Caml-list] Strings as arrays or lists...]
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Xavier Leroy <xavier.leroy@i...>
Subject: Re: [Caml-list] [RANT] String representation (was: Strings as arrays or lists...)
> Unfortunately strings don't act like byte arrays (to the best of my
> knowledge anyway -- I'd love to find out I'm wrong).  If you want to do
> any low level operations on the bytes, you first need to convert the chars
> to ints (and by low level, I'm talking about shifts, rotates, ands, ors,
> xors, etc), perform your ops, then convert back to chars before
> re-inserting them into the string, and this is slooooow.

Actually, Char.code (the conversion from char to int) is a no-op, but
it's true that Char.chr (the conversion from int to char) is slower
because it checks that its argument lies within [0..255].

An alternative is Char.unsafe_chr, which is a no-op (but doesn't
perform the range check).

A better alternative is to declare

external get_byte: string -> int -> int = "%string_safe_get"
external set_byte: string -> int -> int -> unit = "%string_safe_set"

and use these two functions to access strings as if they were byte
arrays.  set_byte will store the low 8 bits of its third argument, so
you'd save on "land 0xFF" operations too.

> Since I do crypto for a living, I run into these problems all the time.

Sure.  The two declarations above should help both with performance
and legibility of your code.

- Xavier Leroy

-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners