summaryrefslogtreecommitdiff
path: root/src/mongo/gotools/src/github.com/mongodb/mongo-tools/legacy/json/csv_format.go
blob: ab6c30cc8530442ab3ff0f44b1e05800bbc49c29 (plain)
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
// Copyright (C) MongoDB, Inc. 2014-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0

package json

import (
	"encoding/base64"
	"fmt"
	"time"
)

const CSV_DATE_FORMAT = "2006-01-02T15:04:05.000Z"

func (b BinData) String() string {
	data, err := base64.StdEncoding.DecodeString(b.Base64)
	if err != nil {
		return "" // XXX: panic?
	}
	if b.Type == 0x02 {
		data = data[4:] // skip the first 4 bytes
	}
	return fmt.Sprintf("%X", data) // use uppercase hexadecimal
}

func (js JavaScript) String() string {
	return js.Code
}

func (d Date) String() string {
	if d.isFormatable() {
		n := int64(d)
		t := time.Unix(n/1e3, n%1e3*1e6)
		return t.UTC().Format(JSON_DATE_FORMAT)
	}
	// date.MarshalJSON always returns a nil err.
	data, _ := d.MarshalJSON()
	return string(data)
}

func (d DBRef) String() string {
	return fmt.Sprintf(`{ "$ref": "%v", "$id": %v, "$db": "%v" }`,
		d.Collection, d.Id, d.Database)
}

func (d DBPointer) String() string {
	return fmt.Sprintf(`{ "$ref": "%v", "$id": %v }`,
		d.Namespace, d.Id)
}

func (f Float) String() string {
	return fmt.Sprintf("%v", float64(f))
}

func (_ MinKey) String() string {
	return "$MinKey"
}

func (_ MaxKey) String() string {
	return "$MaxKey"
}

func (n NumberInt) String() string {
	return fmt.Sprintf("%v", int32(n))
}

func (n NumberLong) String() string {
	return fmt.Sprintf("%v", int64(n))
}

// Assumes that o represents a valid ObjectId
// (composed of 24 hexadecimal characters).
func (o ObjectId) String() string {
	return fmt.Sprintf("ObjectId(%v)", string(o))
}

func (r RegExp) String() string {
	return fmt.Sprintf("/%v/%v", r.Pattern, r.Options)
}

func (t Timestamp) String() string {
	return fmt.Sprintf(`{ "$timestamp": { "t": %v, "i": %v } }`,
		t.Seconds, t.Increment)
}

func (_ Undefined) String() string {
	return `{ "$undefined": true }`
}