From ccece4ef5765e85f9a3d7ba0c795a1d0ce3dd7fd Mon Sep 17 00:00:00 2001 From: "Richard W.M. Jones" Date: Tue, 15 Apr 2008 13:40:51 +0000 Subject: [PATCH] string_of_bitstring. --- bitmatch.ml | 27 ++++++++++++++++++++++++++- bitmatch.mli | 14 +++++++++++++- 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/bitmatch.ml b/bitmatch.ml index c1d6cd1..861cd5a 100644 --- a/bitmatch.ml +++ b/bitmatch.ml @@ -15,7 +15,7 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * - * $Id: bitmatch.ml,v 1.8 2008-04-02 11:06:07 rjones Exp $ + * $Id: bitmatch.ml,v 1.9 2008-04-15 13:40:51 rjones Exp $ *) open Printf @@ -601,6 +601,31 @@ let construct_int64_be_unsigned buf v flen exn = I64.map_bytes_be (Buffer._add_bits buf) (Buffer.add_byte buf) v flen (*----------------------------------------------------------------------*) +(* Extract a string from a bitstring. *) + +let string_of_bitstring (data, off, len) = + if off land 7 = 0 && len land 7 = 0 then + (* Easy case: everything is byte-aligned. *) + String.sub data (off lsr 3) (len lsr 3) + else ( + (* Bit-twiddling case. *) + let strlen = (len + 7) lsr 3 in + let str = String.make strlen '\000' in + let rec loop data off len i = + if len >= 8 then ( + let c, off, len = extract_char_unsigned data off len 8 in + str.[i] <- Char.chr c; + loop data off len (i+1) + ) else if len > 0 then ( + let c, off, len = extract_char_unsigned data off len len in + str.[i] <- Char.chr c + ) + in + loop data off len 0; + str + ) + +(*----------------------------------------------------------------------*) (* Display functions. *) let isprint c = diff --git a/bitmatch.mli b/bitmatch.mli index 9a38808..b700f2b 100644 --- a/bitmatch.mli +++ b/bitmatch.mli @@ -15,7 +15,7 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * - * $Id: bitmatch.mli,v 1.12 2008-04-02 13:59:37 rjones Exp $ + * $Id: bitmatch.mli,v 1.13 2008-04-15 13:40:51 rjones Exp $ *) (** @@ -577,6 +577,18 @@ val bitstring_length : bitstring -> int (** [bitstring_length bitstring] returns the length of the bitstring in bits. *) +val string_of_bitstring : bitstring -> string +(** [string_of_bitstring bitstring] converts a bitstring to a string + (eg. to allow comparison). + + This function is inefficient. In the best case when the bitstring + is nicely byte-aligned we do a [String.sub] operation. If the + bitstring isn't aligned then this involves a lot of bit twiddling + and is particularly inefficient. + + XXX This function wouldn't be needed so much if the [bitmatch] + operator allowed us to pattern-match on strings. *) + (** {3 Bitstring buffer} *) module Buffer : sig -- 1.8.3.1