Skip to content

Commit

Permalink
Merge pull request #9 from motemen/circular
Browse files Browse the repository at this point in the history
Handle circular structures
  • Loading branch information
k0kubun committed Feb 14, 2015
2 parents f8686b0 + 9f6de06 commit 8457b11
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 7 deletions.
37 changes: 30 additions & 7 deletions printer.go
Expand Up @@ -23,18 +23,20 @@ func newPrinter(object interface{}) *printer {
tw.Init(buffer, indentWidth, 0, 1, ' ', 0)

return &printer{
Buffer: buffer,
tw: tw,
depth: 0,
value: reflect.ValueOf(object),
Buffer: buffer,
tw: tw,
depth: 0,
value: reflect.ValueOf(object),
visited: map[uintptr]bool{},
}
}

type printer struct {
*bytes.Buffer
tw *tabwriter.Writer
depth int
value reflect.Value
tw *tabwriter.Writer
depth int
value reflect.Value
visited map[uintptr]bool
}

func (p *printer) String() string {
Expand Down Expand Up @@ -113,6 +115,12 @@ func (p *printer) printMap() {
return
}

if p.visited[p.value.Pointer()] {
p.printf("%s{...}", p.typeString())
return
}
p.visited[p.value.Pointer()] = true

p.println("{")
p.indented(func() {
keys := p.value.MapKeys()
Expand Down Expand Up @@ -142,6 +150,14 @@ func (p *printer) printSlice() {
return
}

if p.value.Kind() == reflect.Slice {
if p.visited[p.value.Pointer()] {
p.printf("%s{...}", p.typeString())
return
}
p.visited[p.value.Pointer()] = true
}

p.println(p.typeString() + "{")
p.indented(func() {
for i := 0; i < p.value.Len(); i++ {
Expand All @@ -163,6 +179,12 @@ func (p *printer) printInterface() {
}

func (p *printer) printPtr() {
if p.visited[p.value.Pointer()] {
p.printf("...")
return
}
p.visited[p.value.Pointer()] = true

if p.value.Elem().IsValid() {
p.printf("&%s", p.format(p.value.Elem()))
} else {
Expand Down Expand Up @@ -231,6 +253,7 @@ func (p *printer) nil() string {
func (p *printer) format(object interface{}) string {
pp := newPrinter(object)
pp.depth = p.depth
pp.visited = p.visited
if value, ok := object.(reflect.Value); ok {
pp.value = value
}
Expand Down
11 changes: 11 additions & 0 deletions printer_test.go
Expand Up @@ -38,6 +38,16 @@ type HogeHoge struct {
A interface{}
}

type Circular struct {
C *Circular
}

var c Circular = Circular{}

func init() {
c.C = &c
}

var (
testCases = []testCase{
{nil, boldCyan("nil")},
Expand Down Expand Up @@ -80,6 +90,7 @@ var (
FooPri{Public: "hello", private: "world"},
new(regexp.Regexp),
unsafe.Pointer(new(regexp.Regexp)),
&c,
}
)

Expand Down

0 comments on commit 8457b11

Please sign in to comment.