1# repeat.tcl -- 2# 3# Emulation of string repeat for older 4# revisions of Tcl. 5# 6# Copyright (c) 2000 by Ajuba Solutions. 7# Copyright (c) 2001-2006 by Andreas Kupries <andreas_kupries@users.sourceforge.net> 8# 9# See the file "license.terms" for information on usage and redistribution 10# of this file, and for a DISCLAIMER OF ALL WARRANTIES. 11# 12# RCS: @(#) $Id: repeat.tcl,v 1.1 2006/04/21 04:42:28 andreas_kupries Exp $ 13 14# ### ### ### ######### ######### ######### 15## Requirements 16 17package require Tcl 8.2 18 19namespace eval ::textutil::repeat {} 20 21# ### ### ### ######### ######### ######### 22 23namespace eval ::textutil::repeat { 24 variable HaveBuiltin [expr {![catch {string repeat a 1}]}] 25} 26 27if {0} { 28 # Problems with the deactivated code: 29 # - Linear in 'num'. 30 # - Tests for 'string repeat' in every call! 31 # (Ok, just the variable, still a test every call) 32 # - Fails for 'num == 0' because of undefined 'str'. 33 34 proc textutil::repeat::StrRepeat { char num } { 35 variable HaveBuiltin 36 if { $HaveBuiltin == 0 } then { 37 for { set i 0 } { $i < $num } { incr i } { 38 append str $char 39 } 40 } else { 41 set str [ string repeat $char $num ] 42 } 43 return $str 44 } 45} 46 47if {$::textutil::repeat::HaveBuiltin} { 48 proc ::textutil::repeat::strRepeat {char num} { 49 return [string repeat $char $num] 50 } 51 52 proc ::textutil::repeat::blank {n} { 53 return [string repeat " " $n] 54 } 55} else { 56 proc ::textutil::repeat::strRepeat {char num} { 57 if {$num <= 0} { 58 # No replication required 59 return "" 60 } elseif {$num == 1} { 61 # Quick exit for recursion 62 return $char 63 } elseif {$num == 2} { 64 # Another quick exit for recursion 65 return $char$char 66 } elseif {0 == ($num % 2)} { 67 # Halving the problem results in O (log n) complexity. 68 set result [strRepeat $char [expr {$num / 2}]] 69 return "$result$result" 70 } else { 71 # Uneven length, reduce problem by one 72 return "$char[strRepeat $char [incr num -1]]" 73 } 74 } 75 76 proc ::textutil::repeat::blank {n} { 77 return [strRepeat " " $n] 78 } 79} 80 81# ### ### ### ######### ######### ######### 82## Data structures 83 84namespace eval ::textutil::repeat { 85 namespace export strRepeat blank 86} 87 88# ### ### ### ######### ######### ######### 89## Ready 90 91package provide textutil::repeat 0.7 92