File: repeat.tcl

package info (click to toggle)
tcllib 2.0%2Bdfsg-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 83,560 kB
  • sloc: tcl: 306,798; ansic: 14,272; sh: 3,035; xml: 1,766; yacc: 1,157; pascal: 881; makefile: 124; perl: 84; f90: 84; python: 33; ruby: 13; php: 11
file content (91 lines) | stat: -rw-r--r-- 2,285 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# repeat.tcl --
#
#	Emulation of string repeat for older
#	revisions of Tcl.
#
# Copyright (c) 2000      by Ajuba Solutions.
# Copyright (c) 2001-2006 by Andreas Kupries <andreas_kupries@users.sourceforge.net>
#
# See the file "license.terms" for information on usage and redistribution
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
#
# RCS: @(#) $Id: repeat.tcl,v 1.1 2006/04/21 04:42:28 andreas_kupries Exp $

# ### ### ### ######### ######### #########
## Requirements

package require Tcl 8.5 9

namespace eval ::textutil::repeat {}

# ### ### ### ######### ######### #########

namespace eval ::textutil::repeat {
    variable HaveBuiltin [expr {![catch {string repeat a 1}]}]
}

if {0} {
    # Problems with the deactivated code:
    # - Linear in 'num'.
    # - Tests for 'string repeat' in every call!
    #   (Ok, just the variable, still a test every call)
    # - Fails for 'num == 0' because of undefined 'str'.

    proc textutil::repeat::StrRepeat { char num } {
	variable HaveBuiltin
	if { $HaveBuiltin == 0 } then {
	    for { set i 0 } { $i < $num } { incr i } {
		append str $char
	    }
	} else {
	    set str [ string repeat $char $num ]
	}
	return $str
    }
}

if {$::textutil::repeat::HaveBuiltin} {
    proc ::textutil::repeat::strRepeat {char num} {
	return [string repeat $char $num]
    }

    proc ::textutil::repeat::blank {n} {
	return [string repeat " " $n]
    }
} else {
    proc ::textutil::repeat::strRepeat {char num} {
	if {$num <= 0} {
	    # No replication required
	    return ""
	} elseif {$num == 1} {
	    # Quick exit for recursion
	    return $char
	} elseif {$num == 2} {
	    # Another quick exit for recursion
	    return $char$char
	} elseif {0 == ($num % 2)} {
	    # Halving the problem results in O (log n) complexity.
	    set result [strRepeat $char [expr {$num / 2}]]
	    return "$result$result"
	} else {
	    # Uneven length, reduce problem by one
	    return "$char[strRepeat $char [incr num -1]]"
	}
    }

    proc ::textutil::repeat::blank {n} {
	return [strRepeat " " $n]
    }
}

# ### ### ### ######### ######### #########
## Data structures

namespace eval ::textutil::repeat {
    namespace export strRepeat blank
}

# ### ### ### ######### ######### #########
## Ready

package provide textutil::repeat 0.8