;; -*- Scheme -*-
;;
;; $Id: string31.scm,v 1.1 1998/03/16 07:59:48 foner Exp $

;;+doc
;; procedure: substring:prefix?
;; arguments: prefix prefix-start prefix-end source source-start source-end
;; signature: string x int x int x string x int x int -> (int|#f)
;; pre:       (and (< 0 prefix-start prefix-end) 
;;                 (<= prefix-end (string-length prefix))
;;                 (< 0 source-start source-end) 
;;                 (<= source-end (string-length source)))
;;
;; If (STRING=? (SUBSTRING PREFIX PREFIX-START PREFIX-END)
;;              (SUBSTRING SOURCE SOURCE-START SOURCE-END))
;; then returns (+ SOURCE-START (- PREFIX-END PREFIX-START))
;; else returns #f
;;
;; > (substring:prefix? "abc" 0 3 "abcdefg" 0 7)
;; 3
;; > (substring:prefix? "abc" 0 3 "zabcdefg" 0 8)
;; #f
;; > (substring:prefix? "abc" 0 3 "zabcdefg" 1 7)
;; 4
;;-doc

(define substring:prefix?
  (lambda (p ps pe s ss se)
    (let ((pl (- pe ps)) (sl (- se ss)))
      (and (<= pl sl)
	   (let loop ((i ps) (j ss))
	     (cond ((= i pe) (+ ss pl))
		   ((char=? (string-ref p i) (string-ref s j))
		    (loop (+ i 1) (+ j 1)))
		   (else #f)))))))

;; This is a loose translation of the following C by Karl Heuer.
;;
;; char *strpref(char const *s, char const *t) {
;;   while (*t != '\0') if (*s++ != *t++) return (NULL);
;;   return ((char *)s);
;; }


;;+doc
;; procedure: string:prefix?
;; arguments: prefix source
;; signature: string x string -> (int|#f)
;;
;; Returns the  if PREFIX is a prefix of SOURCE.
;;
;; > (string:prefix? "abc" "abcdefg")
;; 3
;; > (string:prefix? "abc" "zabcdefg")
;; #f
;;-doc

(define string:prefix?
  (lambda (p s)
    (substring:prefix? p 0 (string-length p) s 0 (string-length s))))

;; eof
