添加vendor
parent
edd5a83d3d
commit
2a1c947808
|
@ -0,0 +1,21 @@
|
|||
package _const
|
||||
|
||||
var RespCode map[int]string
|
||||
|
||||
const (
|
||||
RESP_ERR_COMON = 101
|
||||
RESP_ERR_OK = 0
|
||||
)
|
||||
|
||||
func init() {
|
||||
RespCode[RESP_ERR_OK] = "OK"
|
||||
RespCode[RESP_ERR_COMON] = "Err"
|
||||
}
|
||||
func M(key int) string{
|
||||
v,ok := RespCode[key]
|
||||
if ok{
|
||||
return v
|
||||
}else {
|
||||
return ""
|
||||
}
|
||||
}
|
|
@ -74,14 +74,29 @@ func Auth(c *gin.Context) {
|
|||
// @Produce json
|
||||
// @Param q query string false "name search by q"
|
||||
// @Success 200 {array} util.RespBase
|
||||
// @Failure 400 {object} util.RespBase
|
||||
// @Failure 404 {object} util.RespBase
|
||||
// @Failure 500 {object} util.RespBase
|
||||
// @Router /accounts [get]
|
||||
func SetUser(c *gin.Context){
|
||||
|
||||
var req model.Users
|
||||
var resp RespBase
|
||||
resp.Msg = "操作失败"
|
||||
resp.Status = 20
|
||||
defer func() {
|
||||
c.JSON(200,resp)
|
||||
}()
|
||||
e := c.BindJSON(&req)
|
||||
if nil != e{
|
||||
logs.Error(e.Error())
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
func DelUser(c *gin.Context){
|
||||
var resp RespBase
|
||||
resp.Msg = "操作失败"
|
||||
resp.Status = 20
|
||||
defer func() {
|
||||
c.JSON(200,resp)
|
||||
}()
|
||||
|
||||
}
|
||||
|
||||
|
|
|
@ -0,0 +1,201 @@
|
|||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
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
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
|
@ -0,0 +1,277 @@
|
|||
// Copyright 2016 Google Inc. All Rights Reserved.
|
||||
//
|
||||
// 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
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
// Package civil implements types for civil time, a time-zone-independent
|
||||
// representation of time that follows the rules of the proleptic
|
||||
// Gregorian calendar with exactly 24-hour days, 60-minute hours, and 60-second
|
||||
// minutes.
|
||||
//
|
||||
// Because they lack location information, these types do not represent unique
|
||||
// moments or intervals of time. Use time.Time for that purpose.
|
||||
package civil
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A Date represents a date (year, month, day).
|
||||
//
|
||||
// This type does not include location information, and therefore does not
|
||||
// describe a unique 24-hour timespan.
|
||||
type Date struct {
|
||||
Year int // Year (e.g., 2014).
|
||||
Month time.Month // Month of the year (January = 1, ...).
|
||||
Day int // Day of the month, starting at 1.
|
||||
}
|
||||
|
||||
// DateOf returns the Date in which a time occurs in that time's location.
|
||||
func DateOf(t time.Time) Date {
|
||||
var d Date
|
||||
d.Year, d.Month, d.Day = t.Date()
|
||||
return d
|
||||
}
|
||||
|
||||
// ParseDate parses a string in RFC3339 full-date format and returns the date value it represents.
|
||||
func ParseDate(s string) (Date, error) {
|
||||
t, err := time.Parse("2006-01-02", s)
|
||||
if err != nil {
|
||||
return Date{}, err
|
||||
}
|
||||
return DateOf(t), nil
|
||||
}
|
||||
|
||||
// String returns the date in RFC3339 full-date format.
|
||||
func (d Date) String() string {
|
||||
return fmt.Sprintf("%04d-%02d-%02d", d.Year, d.Month, d.Day)
|
||||
}
|
||||
|
||||
// IsValid reports whether the date is valid.
|
||||
func (d Date) IsValid() bool {
|
||||
return DateOf(d.In(time.UTC)) == d
|
||||
}
|
||||
|
||||
// In returns the time corresponding to time 00:00:00 of the date in the location.
|
||||
//
|
||||
// In is always consistent with time.Date, even when time.Date returns a time
|
||||
// on a different day. For example, if loc is America/Indiana/Vincennes, then both
|
||||
// time.Date(1955, time.May, 1, 0, 0, 0, 0, loc)
|
||||
// and
|
||||
// civil.Date{Year: 1955, Month: time.May, Day: 1}.In(loc)
|
||||
// return 23:00:00 on April 30, 1955.
|
||||
//
|
||||
// In panics if loc is nil.
|
||||
func (d Date) In(loc *time.Location) time.Time {
|
||||
return time.Date(d.Year, d.Month, d.Day, 0, 0, 0, 0, loc)
|
||||
}
|
||||
|
||||
// AddDays returns the date that is n days in the future.
|
||||
// n can also be negative to go into the past.
|
||||
func (d Date) AddDays(n int) Date {
|
||||
return DateOf(d.In(time.UTC).AddDate(0, 0, n))
|
||||
}
|
||||
|
||||
// DaysSince returns the signed number of days between the date and s, not including the end day.
|
||||
// This is the inverse operation to AddDays.
|
||||
func (d Date) DaysSince(s Date) (days int) {
|
||||
// We convert to Unix time so we do not have to worry about leap seconds:
|
||||
// Unix time increases by exactly 86400 seconds per day.
|
||||
deltaUnix := d.In(time.UTC).Unix() - s.In(time.UTC).Unix()
|
||||
return int(deltaUnix / 86400)
|
||||
}
|
||||
|
||||
// Before reports whether d1 occurs before d2.
|
||||
func (d1 Date) Before(d2 Date) bool {
|
||||
if d1.Year != d2.Year {
|
||||
return d1.Year < d2.Year
|
||||
}
|
||||
if d1.Month != d2.Month {
|
||||
return d1.Month < d2.Month
|
||||
}
|
||||
return d1.Day < d2.Day
|
||||
}
|
||||
|
||||
// After reports whether d1 occurs after d2.
|
||||
func (d1 Date) After(d2 Date) bool {
|
||||
return d2.Before(d1)
|
||||
}
|
||||
|
||||
// MarshalText implements the encoding.TextMarshaler interface.
|
||||
// The output is the result of d.String().
|
||||
func (d Date) MarshalText() ([]byte, error) {
|
||||
return []byte(d.String()), nil
|
||||
}
|
||||
|
||||
// UnmarshalText implements the encoding.TextUnmarshaler interface.
|
||||
// The date is expected to be a string in a format accepted by ParseDate.
|
||||
func (d *Date) UnmarshalText(data []byte) error {
|
||||
var err error
|
||||
*d, err = ParseDate(string(data))
|
||||
return err
|
||||
}
|
||||
|
||||
// A Time represents a time with nanosecond precision.
|
||||
//
|
||||
// This type does not include location information, and therefore does not
|
||||
// describe a unique moment in time.
|
||||
//
|
||||
// This type exists to represent the TIME type in storage-based APIs like BigQuery.
|
||||
// Most operations on Times are unlikely to be meaningful. Prefer the DateTime type.
|
||||
type Time struct {
|
||||
Hour int // The hour of the day in 24-hour format; range [0-23]
|
||||
Minute int // The minute of the hour; range [0-59]
|
||||
Second int // The second of the minute; range [0-59]
|
||||
Nanosecond int // The nanosecond of the second; range [0-999999999]
|
||||
}
|
||||
|
||||
// TimeOf returns the Time representing the time of day in which a time occurs
|
||||
// in that time's location. It ignores the date.
|
||||
func TimeOf(t time.Time) Time {
|
||||
var tm Time
|
||||
tm.Hour, tm.Minute, tm.Second = t.Clock()
|
||||
tm.Nanosecond = t.Nanosecond()
|
||||
return tm
|
||||
}
|
||||
|
||||
// ParseTime parses a string and returns the time value it represents.
|
||||
// ParseTime accepts an extended form of the RFC3339 partial-time format. After
|
||||
// the HH:MM:SS part of the string, an optional fractional part may appear,
|
||||
// consisting of a decimal point followed by one to nine decimal digits.
|
||||
// (RFC3339 admits only one digit after the decimal point).
|
||||
func ParseTime(s string) (Time, error) {
|
||||
t, err := time.Parse("15:04:05.999999999", s)
|
||||
if err != nil {
|
||||
return Time{}, err
|
||||
}
|
||||
return TimeOf(t), nil
|
||||
}
|
||||
|
||||
// String returns the date in the format described in ParseTime. If Nanoseconds
|
||||
// is zero, no fractional part will be generated. Otherwise, the result will
|
||||
// end with a fractional part consisting of a decimal point and nine digits.
|
||||
func (t Time) String() string {
|
||||
s := fmt.Sprintf("%02d:%02d:%02d", t.Hour, t.Minute, t.Second)
|
||||
if t.Nanosecond == 0 {
|
||||
return s
|
||||
}
|
||||
return s + fmt.Sprintf(".%09d", t.Nanosecond)
|
||||
}
|
||||
|
||||
// IsValid reports whether the time is valid.
|
||||
func (t Time) IsValid() bool {
|
||||
// Construct a non-zero time.
|
||||
tm := time.Date(2, 2, 2, t.Hour, t.Minute, t.Second, t.Nanosecond, time.UTC)
|
||||
return TimeOf(tm) == t
|
||||
}
|
||||
|
||||
// MarshalText implements the encoding.TextMarshaler interface.
|
||||
// The output is the result of t.String().
|
||||
func (t Time) MarshalText() ([]byte, error) {
|
||||
return []byte(t.String()), nil
|
||||
}
|
||||
|
||||
// UnmarshalText implements the encoding.TextUnmarshaler interface.
|
||||
// The time is expected to be a string in a format accepted by ParseTime.
|
||||
func (t *Time) UnmarshalText(data []byte) error {
|
||||
var err error
|
||||
*t, err = ParseTime(string(data))
|
||||
return err
|
||||
}
|
||||
|
||||
// A DateTime represents a date and time.
|
||||
//
|
||||
// This type does not include location information, and therefore does not
|
||||
// describe a unique moment in time.
|
||||
type DateTime struct {
|
||||
Date Date
|
||||
Time Time
|
||||
}
|
||||
|
||||
// Note: We deliberately do not embed Date into DateTime, to avoid promoting AddDays and Sub.
|
||||
|
||||
// DateTimeOf returns the DateTime in which a time occurs in that time's location.
|
||||
func DateTimeOf(t time.Time) DateTime {
|
||||
return DateTime{
|
||||
Date: DateOf(t),
|
||||
Time: TimeOf(t),
|
||||
}
|
||||
}
|
||||
|
||||
// ParseDateTime parses a string and returns the DateTime it represents.
|
||||
// ParseDateTime accepts a variant of the RFC3339 date-time format that omits
|
||||
// the time offset but includes an optional fractional time, as described in
|
||||
// ParseTime. Informally, the accepted format is
|
||||
// YYYY-MM-DDTHH:MM:SS[.FFFFFFFFF]
|
||||
// where the 'T' may be a lower-case 't'.
|
||||
func ParseDateTime(s string) (DateTime, error) {
|
||||
t, err := time.Parse("2006-01-02T15:04:05.999999999", s)
|
||||
if err != nil {
|
||||
t, err = time.Parse("2006-01-02t15:04:05.999999999", s)
|
||||
if err != nil {
|
||||
return DateTime{}, err
|
||||
}
|
||||
}
|
||||
return DateTimeOf(t), nil
|
||||
}
|
||||
|
||||
// String returns the date in the format described in ParseDate.
|
||||
func (dt DateTime) String() string {
|
||||
return dt.Date.String() + "T" + dt.Time.String()
|
||||
}
|
||||
|
||||
// IsValid reports whether the datetime is valid.
|
||||
func (dt DateTime) IsValid() bool {
|
||||
return dt.Date.IsValid() && dt.Time.IsValid()
|
||||
}
|
||||
|
||||
// In returns the time corresponding to the DateTime in the given location.
|
||||
//
|
||||
// If the time is missing or ambigous at the location, In returns the same
|
||||
// result as time.Date. For example, if loc is America/Indiana/Vincennes, then
|
||||
// both
|
||||
// time.Date(1955, time.May, 1, 0, 30, 0, 0, loc)
|
||||
// and
|
||||
// civil.DateTime{
|
||||
// civil.Date{Year: 1955, Month: time.May, Day: 1}},
|
||||
// civil.Time{Minute: 30}}.In(loc)
|
||||
// return 23:30:00 on April 30, 1955.
|
||||
//
|
||||
// In panics if loc is nil.
|
||||
func (dt DateTime) In(loc *time.Location) time.Time {
|
||||
return time.Date(dt.Date.Year, dt.Date.Month, dt.Date.Day, dt.Time.Hour, dt.Time.Minute, dt.Time.Second, dt.Time.Nanosecond, loc)
|
||||
}
|
||||
|
||||
// Before reports whether dt1 occurs before dt2.
|
||||
func (dt1 DateTime) Before(dt2 DateTime) bool {
|
||||
return dt1.In(time.UTC).Before(dt2.In(time.UTC))
|
||||
}
|
||||
|
||||
// After reports whether dt1 occurs after dt2.
|
||||
func (dt1 DateTime) After(dt2 DateTime) bool {
|
||||
return dt2.Before(dt1)
|
||||
}
|
||||
|
||||
// MarshalText implements the encoding.TextMarshaler interface.
|
||||
// The output is the result of dt.String().
|
||||
func (dt DateTime) MarshalText() ([]byte, error) {
|
||||
return []byte(dt.String()), nil
|
||||
}
|
||||
|
||||
// UnmarshalText implements the encoding.TextUnmarshaler interface.
|
||||
// The datetime is expected to be a string in a format accepted by ParseDateTime
|
||||
func (dt *DateTime) UnmarshalText(data []byte) error {
|
||||
var err error
|
||||
*dt, err = ParseDateTime(string(data))
|
||||
return err
|
||||
}
|
|
@ -0,0 +1,148 @@
|
|||
package logs
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
LOG_ERROR = iota
|
||||
LOG_WARING
|
||||
LOG_INFO
|
||||
LOG_DEBUG
|
||||
)
|
||||
|
||||
var log *mylog
|
||||
|
||||
/*
|
||||
* 初始化
|
||||
*/
|
||||
func init() {
|
||||
log = newMylog()
|
||||
}
|
||||
|
||||
func Init(dir string, file string, level int, savefile bool) {
|
||||
log.setDir(dir)
|
||||
log.setFile(file)
|
||||
log.setLevel(level)
|
||||
log.setSavefile(savefile)
|
||||
}
|
||||
|
||||
func Error(err ...interface{}) {
|
||||
log.write(LOG_ERROR, fmt.Sprint(err...))
|
||||
}
|
||||
|
||||
func Waring(war ...interface{}) {
|
||||
log.write(LOG_WARING, fmt.Sprint(war...))
|
||||
}
|
||||
func SetLevel(level int) {
|
||||
log.setLevel(level)
|
||||
}
|
||||
func Info(info ...interface{}) {
|
||||
log.write(LOG_INFO, fmt.Sprint(info...))
|
||||
}
|
||||
|
||||
func Debug(deb ...interface{}) {
|
||||
log.write(LOG_DEBUG, fmt.Sprint(deb...))
|
||||
}
|
||||
|
||||
/*
|
||||
* 日志执行函数
|
||||
*/
|
||||
type mylog struct {
|
||||
log chan string // 日志chan
|
||||
dir string // 日志存放目录
|
||||
file string // 日志文件名
|
||||
savefile bool // 是否保存到文件
|
||||
level int // 日志级别
|
||||
}
|
||||
|
||||
func newMylog() *mylog {
|
||||
log := &mylog{}
|
||||
|
||||
log.log = make(chan string, 100)
|
||||
log.dir = "/opt/logs"
|
||||
log.file = "out"
|
||||
log.savefile = false
|
||||
|
||||
go log.run()
|
||||
return log
|
||||
}
|
||||
|
||||
func (l *mylog) setDir(dir string) {
|
||||
l.dir = dir
|
||||
}
|
||||
|
||||
func (l *mylog) setFile(file string) {
|
||||
l.file = file
|
||||
}
|
||||
|
||||
func (l *mylog) setSavefile(b bool) {
|
||||
l.savefile = b
|
||||
}
|
||||
|
||||
func (l *mylog) setLevel(level int) {
|
||||
l.level = level
|
||||
}
|
||||
|
||||
func (l *mylog) getLevelString(level int) string {
|
||||
switch level {
|
||||
case LOG_ERROR:
|
||||
return "ERROR"
|
||||
case LOG_WARING:
|
||||
return "WARING"
|
||||
case LOG_INFO:
|
||||
return "INFO"
|
||||
case LOG_DEBUG:
|
||||
return "DEBUG"
|
||||
}
|
||||
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
func (l *mylog) write(level int, str string) {
|
||||
// 判断级别
|
||||
if level > l.level {
|
||||
return
|
||||
}
|
||||
|
||||
// 输出日志
|
||||
pc, _, line, _ := runtime.Caller(2)
|
||||
p := runtime.FuncForPC(pc)
|
||||
t := time.Now()
|
||||
str = fmt.Sprintf("[%04d-%02d-%02d %02d:%02d:%02d] [%s] %s(%d): %s\n",
|
||||
t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(),
|
||||
l.getLevelString(level), p.Name(), line, str)
|
||||
// 输出到控制台
|
||||
if false == l.savefile {
|
||||
fmt.Print(str)
|
||||
return
|
||||
}
|
||||
|
||||
// 输出到文件
|
||||
l.log <- str
|
||||
}
|
||||
|
||||
func (l *mylog) run() {
|
||||
for {
|
||||
str := <-l.log
|
||||
|
||||
// 判断文件夹是否存在
|
||||
_, err := os.Stat(l.dir)
|
||||
if nil != err {
|
||||
os.MkdirAll(l.dir, os.ModePerm)
|
||||
}
|
||||
|
||||
// 获取时间
|
||||
t := time.Now()
|
||||
path := fmt.Sprintf("%s/%s-%04d-%02d-%02d.log", l.dir, l.file,
|
||||
t.Year(), t.Month(), t.Day())
|
||||
fp, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, os.ModePerm)
|
||||
if nil == err {
|
||||
fp.WriteString(str)
|
||||
fp.Close()
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,87 @@
|
|||
package utils
|
||||
|
||||
// 加入8字节
|
||||
func Put8bit(buf []byte, n byte) []byte {
|
||||
return append(buf, n)
|
||||
}
|
||||
|
||||
// 加入16字节
|
||||
func Put16bit(buf []byte, n uint16) []byte {
|
||||
var by [2]byte
|
||||
|
||||
by[0] = byte((n >> 8) & 0xff)
|
||||
by[1] = byte(n & 0xff)
|
||||
|
||||
return append(buf, by[:]...)
|
||||
}
|
||||
|
||||
// 加入32字节
|
||||
func Put32bit(buf []byte, n uint32) []byte {
|
||||
var by [4]byte
|
||||
|
||||
by[0] = byte((n >> 24) & 0xff)
|
||||
by[1] = byte((n >> 16) & 0xff)
|
||||
by[2] = byte((n >> 8) & 0xff)
|
||||
by[3] = byte(n & 0xff)
|
||||
|
||||
return append(buf, by[:]...)
|
||||
}
|
||||
|
||||
// 加入64字节
|
||||
func Put64bit(buf []byte, n uint64) []byte {
|
||||
var by [8]byte
|
||||
|
||||
by[0] = byte((n >> 56) & 0xff)
|
||||
by[1] = byte((n >> 48) & 0xff)
|
||||
by[2] = byte((n >> 40) & 0xff)
|
||||
by[3] = byte((n >> 32) & 0xff)
|
||||
by[4] = byte((n >> 24) & 0xff)
|
||||
by[5] = byte((n >> 16) & 0xff)
|
||||
by[6] = byte((n >> 8) & 0xff)
|
||||
by[7] = byte(n & 0xff)
|
||||
|
||||
return append(buf, by[:]...)
|
||||
}
|
||||
|
||||
// 获取8bit
|
||||
func Get8bit(buf []byte, start int) byte {
|
||||
return buf[start]
|
||||
}
|
||||
|
||||
// 获取16bit
|
||||
func Get16bit(buf []byte, start int) uint16 {
|
||||
var ret uint16
|
||||
|
||||
ret = uint16(buf[start]) << 8
|
||||
ret |= uint16(buf[start+1])
|
||||
|
||||
return ret
|
||||
}
|
||||
|
||||
// 获取32big
|
||||
func Get32bit(buf []byte, start int) uint32 {
|
||||
var ret uint32
|
||||
|
||||
ret = uint32(buf[start]) << 24
|
||||
ret |= uint32(buf[start+1]) << 16
|
||||
ret |= uint32(buf[start+2]) << 8
|
||||
ret |= uint32(buf[start+3])
|
||||
|
||||
return ret
|
||||
}
|
||||
|
||||
// 获取64bit
|
||||
func Get64bit(buf []byte, start int) uint64 {
|
||||
var ret uint64
|
||||
|
||||
ret = uint64(buf[start]) << 56
|
||||
ret |= uint64(buf[start+1]) << 48
|
||||
ret |= uint64(buf[start+2]) << 40
|
||||
ret |= uint64(buf[start+3]) << 32
|
||||
ret |= uint64(buf[start+4]) << 24
|
||||
ret |= uint64(buf[start+5]) << 16
|
||||
ret |= uint64(buf[start+6]) << 8
|
||||
ret |= uint64(buf[start+7])
|
||||
|
||||
return ret
|
||||
}
|
|
@ -0,0 +1,289 @@
|
|||
package utils
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"log"
|
||||
"time"
|
||||
"fmt"
|
||||
"encoding/pem"
|
||||
"crypto/x509"
|
||||
"crypto/rsa"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"io"
|
||||
"net/url"
|
||||
"hash/crc32"
|
||||
crand "crypto/rand"
|
||||
"crypto/hmac"
|
||||
"crypto/sha1"
|
||||
"crypto/md5"
|
||||
)
|
||||
|
||||
// md5
|
||||
func Md5Sum(text string) string {
|
||||
h := md5.New()
|
||||
io.WriteString(h, text)
|
||||
return fmt.Sprintf("%x", h.Sum(nil))
|
||||
}
|
||||
|
||||
// 加解密函数 根据dz的Authcode改写的go版本
|
||||
// params[0] 加密or解密 bool true:加密 false:解密 默认false
|
||||
// params[1] 秘钥
|
||||
// params[2] 加密:过期时间
|
||||
// params[3] 动态秘钥长度 默认:4位 不能大于32位
|
||||
func Authcode(text string, params ...interface{}) string {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
log.Printf("authcode error:%#v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
l := len(params)
|
||||
|
||||
isEncode := false
|
||||
key := "DH-Framework"
|
||||
expiry := 0
|
||||
cKeyLen := 10
|
||||
|
||||
if l > 0 {
|
||||
isEncode = params[0].(bool)
|
||||
}
|
||||
|
||||
if l > 1 {
|
||||
key = params[1].(string)
|
||||
}
|
||||
|
||||
if l > 2 {
|
||||
expiry = params[2].(int)
|
||||
if expiry < 0 {
|
||||
expiry = 0
|
||||
}
|
||||
}
|
||||
|
||||
if l > 3 {
|
||||
cKeyLen = params[3].(int)
|
||||
if cKeyLen < 0 {
|
||||
cKeyLen = 0
|
||||
}
|
||||
}
|
||||
if cKeyLen > 32 {
|
||||
cKeyLen = 32
|
||||
}
|
||||
|
||||
timestamp := time.Now().Unix()
|
||||
|
||||
// md5加密key
|
||||
mKey := Md5Sum(key)
|
||||
|
||||
// 参与加密的
|
||||
keyA := Md5Sum(mKey[0:16])
|
||||
// 用于验证数据有效性的
|
||||
keyB := Md5Sum(mKey[16:])
|
||||
// 动态部分
|
||||
var keyC string
|
||||
if cKeyLen > 0 {
|
||||
if isEncode {
|
||||
// 加密的时候,动态获取一个秘钥
|
||||
keyC = Md5Sum(fmt.Sprint(timestamp))[32 - cKeyLen:]
|
||||
} else {
|
||||
// 解密的时候从头部获取动态秘钥部分
|
||||
keyC = text[0:cKeyLen]
|
||||
}
|
||||
}
|
||||
|
||||
// 加入了动态的秘钥
|
||||
cryptKey := keyA + Md5Sum(keyA + keyC)
|
||||
// 秘钥长度
|
||||
keyLen := len(cryptKey)
|
||||
if isEncode {
|
||||
// 加密 前10位是过期验证字符串 10-26位字符串验证
|
||||
var d int64
|
||||
if expiry > 0 {
|
||||
d = timestamp + int64(expiry)
|
||||
}
|
||||
text = fmt.Sprintf("%010d%s%s", d, Md5Sum(text + keyB)[0:16], text)
|
||||
} else {
|
||||
// 解密
|
||||
text = string(Base64Decode(text[cKeyLen:]))
|
||||
}
|
||||
|
||||
// 字符串长度
|
||||
textLen := len(text)
|
||||
if textLen <= 0 {
|
||||
panic(fmt.Sprintf("auth[%s]textLen<=0", text))
|
||||
}
|
||||
|
||||
// 密匙簿
|
||||
box := Range(0, 256)
|
||||
// 对称算法
|
||||
var rndKey []int
|
||||
cryptKeyB := []byte(cryptKey)
|
||||
for i := 0; i < 256; i++ {
|
||||
pos := i % keyLen
|
||||
rndKey = append(rndKey, int(cryptKeyB[pos]))
|
||||
}
|
||||
|
||||
j := 0
|
||||
for i := 0; i < 256; i++ {
|
||||
j = (j + box[i] + rndKey[i]) % 256
|
||||
box[i], box[j] = box[j], box[i]
|
||||
}
|
||||
|
||||
textB := []byte(text)
|
||||
a := 0
|
||||
j = 0
|
||||
var result []byte
|
||||
for i := 0; i < textLen; i++ {
|
||||
a = (a + 1) % 256
|
||||
j = (j + box[a]) % 256
|
||||
box[a], box[j] = box[j], box[a]
|
||||
result = append(result, byte(int(textB[i]) ^ (box[(box[a] + box[j]) % 256])))
|
||||
}
|
||||
|
||||
if isEncode {
|
||||
return keyC + strings.Replace(Base64Encode(result), "=", "", -1)
|
||||
}
|
||||
|
||||
// 获取前10位,判断过期时间
|
||||
d := Atoi64(string(result[0:10]), 0)
|
||||
if (d == 0 || d - timestamp > 0) && string(result[10:26]) == Md5Sum(string(result[26:]) + keyB)[0:16] {
|
||||
return string(result[26:])
|
||||
}
|
||||
|
||||
panic(fmt.Sprintf("auth[%s]", text))
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
// AuthcodeUrl 处理Authcode函数的加密解密结果以便url传输
|
||||
func AuthcodeUrl(text string, params ...interface{}) string {
|
||||
isEncode := false
|
||||
if len(params) > 0 {
|
||||
isEncode = params[0].(bool)
|
||||
}
|
||||
if isEncode { //加密
|
||||
return strings.Replace(strings.Replace(Authcode(text, params...), "+", ",", -1), "/", "-", -1)
|
||||
} else {
|
||||
return Authcode(strings.Replace(strings.Replace(text, ",", "+", -1), "-", "/", -1), params...)
|
||||
}
|
||||
}
|
||||
|
||||
// JsonEncode 编码JSON
|
||||
func JsonEncode(m interface{}) string {
|
||||
b, err := json.Marshal(m)
|
||||
if err != nil {
|
||||
log.Printf("Json Encode[%#v] Error:%s", m, err.Error())
|
||||
return ""
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// JsonDecode 解码JSON
|
||||
func JsonDecode(str string, v ...interface{}) (interface{}, error) {
|
||||
var m interface{}
|
||||
if len(v) > 0 {
|
||||
m = v[0]
|
||||
} else {
|
||||
m = make(map[string]interface{})
|
||||
}
|
||||
|
||||
err := json.Unmarshal([]byte(str), &m)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func Crc32(text string) string {
|
||||
h := crc32.NewIEEE()
|
||||
io.WriteString(h, text)
|
||||
return fmt.Sprintf("%d", h.Sum32())
|
||||
}
|
||||
|
||||
// RsaEncode rsa加密
|
||||
func RsaEncode(b, rsaKey []byte) ([]byte, error) {
|
||||
block, _ := pem.Decode(rsaKey)
|
||||
if block == nil {
|
||||
return b, errors.New("key error")
|
||||
}
|
||||
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
|
||||
if err != nil {
|
||||
return b, err
|
||||
}
|
||||
return rsa.EncryptPKCS1v15(crand.Reader, pub.(*rsa.PublicKey), b)
|
||||
}
|
||||
|
||||
// RsaDecode rsa解密
|
||||
func RsaDecode(b, rsaKey []byte) ([]byte, error) {
|
||||
block, _ := pem.Decode(rsaKey)
|
||||
if block == nil {
|
||||
return b, errors.New("key error")
|
||||
}
|
||||
priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
|
||||
if err != nil {
|
||||
return b, err
|
||||
}
|
||||
return rsa.DecryptPKCS1v15(crand.Reader, priv, b)
|
||||
}
|
||||
|
||||
func HashHmac(data, key string) string {
|
||||
mac := hmac.New(sha1.New, []byte(key))
|
||||
mac.Write([]byte(data))
|
||||
return fmt.Sprintf("%x", mac.Sum(nil))
|
||||
}
|
||||
|
||||
func HashHmacRaw(data, key string) string {
|
||||
mac := hmac.New(sha1.New, []byte(key))
|
||||
mac.Write([]byte(data))
|
||||
return fmt.Sprintf("%s", mac.Sum(nil))
|
||||
}
|
||||
|
||||
// Base64Encode Base64编码
|
||||
func Base64Encode(b []byte) string {
|
||||
return base64.StdEncoding.EncodeToString(b)
|
||||
}
|
||||
|
||||
// Base64Decode Base64解码
|
||||
func Base64Decode(str string) []byte {
|
||||
var b []byte
|
||||
var err error
|
||||
x := len(str) * 3 % 4
|
||||
switch {
|
||||
case x == 2:
|
||||
str += "=="
|
||||
case x == 1:
|
||||
str += "="
|
||||
}
|
||||
if b, err = base64.StdEncoding.DecodeString(str); err != nil {
|
||||
return b
|
||||
}
|
||||
|
||||
return b
|
||||
}
|
||||
|
||||
// UrlEncode 编码
|
||||
func UrlEncode(str string) string {
|
||||
return url.QueryEscape(str)
|
||||
}
|
||||
|
||||
// UrlDecode 解码
|
||||
func UrlDecode(str string) string {
|
||||
ret, _ := url.QueryUnescape(str)
|
||||
return ret
|
||||
}
|
||||
|
||||
/*func Urlencode(str string) string {
|
||||
return base64.URLEncoding.EncodeToString([]byte(str))
|
||||
}
|
||||
|
||||
func Urldecode(str string) string {
|
||||
b, e := base64.URLEncoding.DecodeString(str)
|
||||
if e != nil {
|
||||
log.Printf("urldecode error:%s", e.Error())
|
||||
return ""
|
||||
}
|
||||
|
||||
return string(b)
|
||||
}*/
|
|
@ -0,0 +1,80 @@
|
|||
package utils
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
const (
|
||||
FILE_OPEN_TYPE_READ int = 0
|
||||
FILE_OPEN_TYPE_WRITE int = 1
|
||||
FILE_OPEN_TYPE_APPEND int = 2
|
||||
)
|
||||
|
||||
// ReadTextFile 读取文件
|
||||
func ReadTextFile(path string) string {
|
||||
fp, err := os.Open(path)
|
||||
if nil != err {
|
||||
return ""
|
||||
}
|
||||
defer fp.Close()
|
||||
d, err := ioutil.ReadAll(fp)
|
||||
if nil != err {
|
||||
return ""
|
||||
}
|
||||
return string(d)
|
||||
}
|
||||
|
||||
/*
|
||||
* 读取配置文件
|
||||
*/
|
||||
func ReadConfFile(file string) string {
|
||||
return ReadTextFile(GetConfPath(file))
|
||||
}
|
||||
|
||||
// 获取配置文件路径
|
||||
func GetConfPath(fname string) string {
|
||||
// 绝对路径
|
||||
if len(fname) > 2 && ('/' == fname[0] || ':' == fname[1]) {
|
||||
return fname
|
||||
}
|
||||
return GetFilePathBaseExe("./" + fname)
|
||||
}
|
||||
|
||||
// 以exe为根节点获取文件路径
|
||||
func GetFilePathBaseExe(fname string) string {
|
||||
// 绝对路径
|
||||
if len(fname) > 2 && ('/' == fname[0] || ':' == fname[1]) {
|
||||
return fname
|
||||
}
|
||||
// 相对路径
|
||||
file, _ := exec.LookPath(os.Args[0])
|
||||
return filepath.Join(filepath.Dir(file), fname)
|
||||
}
|
||||
|
||||
// 创建目录
|
||||
func CreateDir(dirName string) error {
|
||||
// 判断目录是否存在
|
||||
if _, err := os.Stat(dirName); false == os.IsNotExist(err) {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 分解上层目录
|
||||
pdir := filepath.Dir(dirName)
|
||||
if "" == pdir {
|
||||
return errors.New("error dir format")
|
||||
}
|
||||
|
||||
// 判断目录是否存在
|
||||
if _, err := os.Stat(pdir); os.IsNotExist(err) {
|
||||
err = CreateDir(pdir)
|
||||
if nil != err {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return os.Mkdir(dirName, 0755)
|
||||
}
|
|
@ -0,0 +1,329 @@
|
|||
package utils
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/text/encoding/simplifiedchinese"
|
||||
"golang.org/x/text/transform"
|
||||
)
|
||||
|
||||
// GetTypeName 获取参数类型
|
||||
func GetTypeName(v interface{}) string {
|
||||
return reflect.TypeOf(v).String()
|
||||
}
|
||||
|
||||
// Btoi 布尔值转整形
|
||||
func Btoi(b bool) int {
|
||||
if b {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// Itoa 整型转字符串
|
||||
func Itoa(i int) string {
|
||||
return strconv.Itoa(i)
|
||||
}
|
||||
|
||||
// Atoi 转换成整型
|
||||
func Atoi(s string, d ...int) int {
|
||||
i, err := strconv.Atoi(s)
|
||||
if err != nil {
|
||||
if len(d) > 0 {
|
||||
return d[0]
|
||||
} else {
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
return i
|
||||
}
|
||||
|
||||
// AtoUi 转换成无符号整型
|
||||
func AtoUi(s string) uint {
|
||||
return uint(Atoi64(s))
|
||||
}
|
||||
|
||||
// Atoi64 转换成整型int64
|
||||
func Atoi64(s string, d ...int64) int64 {
|
||||
i, err := strconv.ParseInt(s, 10, 64)
|
||||
if err != nil {
|
||||
if len(d) > 0 {
|
||||
return d[0]
|
||||
} else {
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
return i
|
||||
}
|
||||
|
||||
// AtoUi64 转换成整型float64
|
||||
func AtoUi64(s string, d ...uint64) uint64 {
|
||||
i, err := strconv.ParseUint(s, 10, 64)
|
||||
if err != nil {
|
||||
if len(d) > 0 {
|
||||
return d[0]
|
||||
} else {
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
return i
|
||||
}
|
||||
|
||||
// Atof 转换成float32整型
|
||||
func Atof(s string, d ...float32) float32 {
|
||||
f, err := strconv.ParseFloat(s, 32)
|
||||
if err != nil {
|
||||
if len(d) > 0 {
|
||||
return d[0]
|
||||
} else {
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
return float32(f)
|
||||
}
|
||||
|
||||
// Atof64 转换成整型float64
|
||||
func Atof64(s string, d ...float64) float64 {
|
||||
f, err := strconv.ParseFloat(s, 64)
|
||||
if err != nil {
|
||||
if len(d) > 0 {
|
||||
return d[0]
|
||||
} else {
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
return f
|
||||
}
|
||||
|
||||
// UitoA 32位无符号整形转字符串
|
||||
func UitoA(i uint) string {
|
||||
return strconv.FormatUint(uint64(i), 10)
|
||||
}
|
||||
|
||||
// Ui32toA 32位无符号整形转字符串
|
||||
func Ui32toA(i uint32) string {
|
||||
return strconv.FormatUint(uint64(i), 10)
|
||||
}
|
||||
|
||||
// Ui64toA 64位无符号整形转字符串
|
||||
func Ui64toA(i uint64) string {
|
||||
return strconv.FormatUint(i, 10)
|
||||
}
|
||||
|
||||
// I64toA 64位整形转字符串
|
||||
func I64toA(i int64) string {
|
||||
return strconv.FormatInt(i, 10)
|
||||
}
|
||||
|
||||
// F32toA 32位浮点数转字符串
|
||||
func F32toA(f float32) string {
|
||||
return F64toA(float64(f))
|
||||
}
|
||||
|
||||
// F64toA 64位浮点数转字符串
|
||||
func F64toA(f float64) string {
|
||||
return strconv.FormatFloat(f, 'f', -1, 64)
|
||||
}
|
||||
|
||||
// DateFormat 日期格式化
|
||||
func DateFormat(format string, t time.Time) string {
|
||||
patterns := []string{
|
||||
// 年
|
||||
"Y", "2006", // 4 位数字完整表示的年份
|
||||
"y", "06", // 2 位数字表示的年份
|
||||
|
||||
// 月
|
||||
"m", "01", // 数字表示的月份,有前导零
|
||||
"n", "1", // 数字表示的月份,没有前导零
|
||||
"M", "Jan", // 三个字母缩写表示的月份
|
||||
"F", "January", // 月份,完整的文本格式,例如 January 或者 March
|
||||
|
||||
// 日
|
||||
"d", "02", // 月份中的第几天,有前导零的 2 位数字
|
||||
"j", "2", // 月份中的第几天,没有前导零
|
||||
|
||||
"D", "Mon", // 星期几,文本表示,3 个字母
|
||||
"l", "Monday", // 星期几,完整的文本格式;L的小写字母
|
||||
|
||||
// 时间
|
||||
"g", "3", // 小时,12 小时格式,没有前导零
|
||||
"G", "15", // 小时,24 小时格式,没有前导零
|
||||
"h", "03", // 小时,12 小时格式,有前导零
|
||||
"H", "15", // 小时,24 小时格式,有前导零
|
||||
|
||||
"a", "pm", // 小写的上午和下午值
|
||||
"A", "PM", // 小写的上午和下午值
|
||||
|
||||
"i", "04", // 有前导零的分钟数
|
||||
"s", "05", // 秒数,有前导零
|
||||
}
|
||||
replacer := strings.NewReplacer(patterns...)
|
||||
format = replacer.Replace(format)
|
||||
return t.Format(format)
|
||||
}
|
||||
|
||||
// StrToLocalTime 字符串转本地时间
|
||||
func StrToLocalTime(value string) (time.Time, error) {
|
||||
if value == "" {
|
||||
return time.Time{}, nil
|
||||
}
|
||||
zoneName, offset := time.Now().Zone()
|
||||
|
||||
zoneValue := offset / 3600 * 100
|
||||
if zoneValue > 0 {
|
||||
value += fmt.Sprintf(" +%04d", zoneValue)
|
||||
} else {
|
||||
value += fmt.Sprintf(" -%04d", zoneValue)
|
||||
}
|
||||
|
||||
if zoneName != "" {
|
||||
value += " " + zoneName
|
||||
}
|
||||
return StrToTime(value)
|
||||
}
|
||||
|
||||
// StrToTime 字符串转时间
|
||||
func StrToTime(value string) (time.Time, error) {
|
||||
if value == "" {
|
||||
return time.Time{}, nil
|
||||
}
|
||||
layouts := []string{
|
||||
"2006-01-02 15:04:05 -0700 MST",
|
||||
"2006-01-02 15:04:05 -0700",
|
||||
"2006-01-02 15:04:05",
|
||||
"2006/01/02 15:04:05 -0700 MST",
|
||||
"2006/01/02 15:04:05 -0700",
|
||||
"2006/01/02 15:04:05",
|
||||
"2006-01-02 -0700 MST",
|
||||
"2006-01-02 -0700",
|
||||
"2006-01-02",
|
||||
"2006/01/02 -0700 MST",
|
||||
"2006/01/02 -0700",
|
||||
"2006/01/02",
|
||||
"2006-01-02 15:04:05 -0700 -0700",
|
||||
"2006/01/02 15:04:05 -0700 -0700",
|
||||
"2006-01-02 -0700 -0700",
|
||||
"2006/01/02 -0700 -0700",
|
||||
time.ANSIC,
|
||||
time.UnixDate,
|
||||
time.RubyDate,
|
||||
time.RFC822,
|
||||
time.RFC822Z,
|
||||
time.RFC850,
|
||||
time.RFC1123,
|
||||
time.RFC1123Z,
|
||||
time.RFC3339,
|
||||
time.RFC3339Nano,
|
||||
time.Kitchen,
|
||||
time.Stamp,
|
||||
time.StampMilli,
|
||||
time.StampMicro,
|
||||
time.StampNano,
|
||||
}
|
||||
|
||||
var t time.Time
|
||||
var err error
|
||||
for _, layout := range layouts {
|
||||
t, err = time.ParseInLocation(layout, value, time.Local)
|
||||
if err == nil {
|
||||
return t, nil
|
||||
}
|
||||
}
|
||||
return time.Time{}, err
|
||||
}
|
||||
|
||||
// StructToMap 结构转map
|
||||
func StructToMap(data interface{}) map[string]interface{} {
|
||||
result := make(map[string]interface{})
|
||||
elem := reflect.ValueOf(data).Elem()
|
||||
size := elem.NumField()
|
||||
|
||||
for i := 0; i < size; i++ {
|
||||
field := elem.Type().Field(i).Name
|
||||
value := elem.Field(i).Interface()
|
||||
result[field] = value
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// 带xml标签的Struct结构转map,用xml标注做key
|
||||
func XMLStructToMap(data interface{}) map[string]interface{} {
|
||||
result := make(map[string]interface{})
|
||||
elem := reflect.ValueOf(data).Elem()
|
||||
size := elem.NumField()
|
||||
|
||||
for i := 0; i < size; i++ {
|
||||
field := elem.Type().Field(i).Tag.Get("xml")
|
||||
value := elem.Field(i).Interface()
|
||||
result[field] = value
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// Ip2long IP转长整型
|
||||
func Ip2long(ipstr string) (ip uint32) {
|
||||
r := `^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})`
|
||||
reg, err := regexp.Compile(r)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ips := reg.FindStringSubmatch(ipstr)
|
||||
if ips == nil {
|
||||
return
|
||||
}
|
||||
|
||||
ip1, _ := strconv.Atoi(ips[1])
|
||||
ip2, _ := strconv.Atoi(ips[2])
|
||||
ip3, _ := strconv.Atoi(ips[3])
|
||||
ip4, _ := strconv.Atoi(ips[4])
|
||||
|
||||
if ip1 > 255 || ip2 > 255 || ip3 > 255 || ip4 > 255 {
|
||||
return
|
||||
}
|
||||
|
||||
ip += uint32(ip1 * 0x1000000)
|
||||
ip += uint32(ip2 * 0x10000)
|
||||
ip += uint32(ip3 * 0x100)
|
||||
ip += uint32(ip4)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Long2ip 长整型转IP
|
||||
func Long2ip(ip uint32) string {
|
||||
return fmt.Sprintf("%d.%d.%d.%d", ip>>24, ip<<8>>24, ip<<16>>24, ip<<24>>24)
|
||||
}
|
||||
|
||||
// GbkToUtf8 GBK转UTF-8
|
||||
func GbkToUtf8(s []byte) ([]byte, error) {
|
||||
reader := transform.NewReader(bytes.NewReader(s), simplifiedchinese.GBK.NewDecoder())
|
||||
d, e := ioutil.ReadAll(reader)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// Utf8ToGbk UTF-8转GBK
|
||||
func Utf8ToGbk(s []byte) ([]byte, error) {
|
||||
reader := transform.NewReader(bytes.NewReader(s), simplifiedchinese.GBK.NewEncoder())
|
||||
d, e := ioutil.ReadAll(reader)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
return d, nil
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package utils
|
||||
|
||||
import (
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
// Counter 原子计数器
|
||||
type Counter struct {
|
||||
v int64
|
||||
}
|
||||
|
||||
// Add 计数加
|
||||
func (c *Counter) Add(i int64) {
|
||||
atomic.AddInt64(&c.v, i)
|
||||
}
|
||||
|
||||
// Get 取计数
|
||||
func (c *Counter) Get() int64 {
|
||||
return c.v
|
||||
}
|
||||
|
||||
// Reset 重置计数器
|
||||
func (c *Counter) Reset() {
|
||||
c.Add(c.v * -1)
|
||||
}
|
|
@ -0,0 +1,75 @@
|
|||
package utils
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
// FileIsExist 检查文件是否存在
|
||||
func FileIsExist(path string) bool {
|
||||
_, err := os.Stat(path)
|
||||
if err != nil && os.IsNotExist(err) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// GetFileContents 读取文件内容
|
||||
func GetFileContents(path string) string {
|
||||
fi, err := os.Open(path)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
defer fi.Close()
|
||||
fd, err := ioutil.ReadAll(fi)
|
||||
return string(bytes.Trim(fd, "\xef\xbb\xbf"))
|
||||
}
|
||||
|
||||
// DirIsExist 检查目录是否存在
|
||||
func DirIsExist(path string) bool {
|
||||
fileinfo, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return os.IsExist(err)
|
||||
} else {
|
||||
return fileinfo.IsDir()
|
||||
}
|
||||
}
|
||||
|
||||
// 打开文件
|
||||
func OpenFile(path string, fileName string, openType int) (*os.File, error) {
|
||||
|
||||
fileFullPath := path + "/" + fileName
|
||||
if runtime.GOOS == "windows" {
|
||||
fileFullPath = path + "\\" + fileName
|
||||
}
|
||||
isFileExist := FileIsExist(fileFullPath)
|
||||
|
||||
switch openType {
|
||||
case FILE_OPEN_TYPE_READ:
|
||||
if isFileExist {
|
||||
f, err := os.OpenFile(fileFullPath, os.O_RDONLY, 0644)
|
||||
return f, err
|
||||
} else {
|
||||
return nil, errors.New("file not exist")
|
||||
}
|
||||
case FILE_OPEN_TYPE_WRITE:
|
||||
if isFileExist {
|
||||
return nil, errors.New("file already existed")
|
||||
} else {
|
||||
f, err := os.OpenFile(fileFullPath, os.O_CREATE|os.O_WRONLY, 0644)
|
||||
return f, err
|
||||
}
|
||||
case FILE_OPEN_TYPE_APPEND:
|
||||
if !isFileExist {
|
||||
f, err := os.OpenFile(fileFullPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
|
||||
return f, err
|
||||
} else {
|
||||
f, err := os.OpenFile(fileFullPath, os.O_APPEND|os.O_WRONLY, 0644)
|
||||
return f, err
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
|
@ -0,0 +1,144 @@
|
|||
package utils
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strings"
|
||||
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
// Get
|
||||
func Get(apiUrl string, parm map[string]string, header map[string]string, isHttps bool) ([]byte, error) {
|
||||
|
||||
if len(parm) > 0 {
|
||||
apiUrl = fmt.Sprintf("%s%s", apiUrl, "?")
|
||||
p := ""
|
||||
for k, v := range parm {
|
||||
if p == "" {
|
||||
p = fmt.Sprintf("%s=%s", k, v)
|
||||
} else {
|
||||
p = fmt.Sprintf("%s&%s=%s", p, k, v)
|
||||
}
|
||||
}
|
||||
apiUrl = fmt.Sprintf("%s%s", apiUrl, p)
|
||||
}
|
||||
|
||||
client := &http.Client{}
|
||||
|
||||
if isHttps {
|
||||
client.Transport = &http.Transport{
|
||||
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
|
||||
}
|
||||
}
|
||||
reqest, _ := http.NewRequest("GET", apiUrl, nil)
|
||||
|
||||
for k, v := range header {
|
||||
reqest.Header.Set(k, v)
|
||||
}
|
||||
|
||||
response, err := client.Do(reqest)
|
||||
if nil != err {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != 200 {
|
||||
return nil, errors.New(response.Status)
|
||||
}
|
||||
|
||||
body, err := ioutil.ReadAll(response.Body)
|
||||
if nil != err {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return body, nil
|
||||
}
|
||||
|
||||
// post
|
||||
func Post(apiUrl string, data []byte, header map[string]string, isHttps bool) ([]byte, error) {
|
||||
|
||||
client := &http.Client{}
|
||||
|
||||
if isHttps {
|
||||
client.Transport = &http.Transport{
|
||||
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
|
||||
}
|
||||
}
|
||||
reqest, _ := http.NewRequest("POST", apiUrl, bytes.NewReader(data))
|
||||
|
||||
for k, v := range header {
|
||||
reqest.Header.Set(k, v)
|
||||
}
|
||||
|
||||
response, err := client.Do(reqest)
|
||||
if nil != err {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != 200 {
|
||||
return nil, errors.New(response.Status)
|
||||
}
|
||||
|
||||
body, err := ioutil.ReadAll(response.Body)
|
||||
if nil != err {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return body, nil
|
||||
}
|
||||
|
||||
// post
|
||||
func PostMap(apiUrl string, parm map[string]string, header map[string]string, isHttps bool) ([]byte, error) {
|
||||
|
||||
data := url.Values{}
|
||||
for k, v := range parm {
|
||||
data.Set(k, v)
|
||||
}
|
||||
|
||||
reqParams := ioutil.NopCloser(strings.NewReader(data.Encode()))
|
||||
client := &http.Client{}
|
||||
|
||||
if isHttps {
|
||||
client.Transport = &http.Transport{
|
||||
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
|
||||
}
|
||||
}
|
||||
reqest, _ := http.NewRequest("POST", apiUrl, reqParams)
|
||||
|
||||
for k, v := range header {
|
||||
reqest.Header.Set(k, v)
|
||||
}
|
||||
|
||||
response, err := client.Do(reqest)
|
||||
if nil != err {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != 200 {
|
||||
return nil, errors.New(response.Status)
|
||||
}
|
||||
|
||||
body, err := ioutil.ReadAll(response.Body)
|
||||
if nil != err {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return body, nil
|
||||
}
|
||||
|
||||
// 获取远程ip
|
||||
func GetRemoteIP(r *http.Request) string {
|
||||
addr := r.Header.Get("Remote_addr")
|
||||
if addr == "" {
|
||||
addr = r.RemoteAddr
|
||||
}
|
||||
|
||||
return strings.Split(addr, ":")[0]
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package utils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// HumanTimeSecond 格式化秒数
|
||||
func HumanTimeSecond(s int64, separator ...string) string {
|
||||
const (
|
||||
Minute = 60
|
||||
Hour = 60 * Minute
|
||||
Day = 24 * Hour
|
||||
)
|
||||
var d, h, m int64
|
||||
|
||||
d = s / Day
|
||||
s = s % Day
|
||||
h = s / Hour
|
||||
s = s % Hour
|
||||
m = s / Minute
|
||||
s = s % Minute
|
||||
|
||||
var sep string
|
||||
if len(separator) == 1 {
|
||||
sep = separator[0]
|
||||
}
|
||||
|
||||
if d > 0 {
|
||||
return fmt.Sprintf("%dd%s%dh%s%dm%s%ds", d, sep, h, sep, m, sep, s)
|
||||
} else if h > 0 {
|
||||
return fmt.Sprintf("%dh%s%dm%s%ds", h, sep, m, sep, s)
|
||||
} else if m > 0 {
|
||||
return fmt.Sprintf("%dm%s%ds", m, sep, s)
|
||||
}
|
||||
return fmt.Sprintf("%ds", s)
|
||||
}
|
|
@ -0,0 +1,118 @@
|
|||
package utils
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
"path"
|
||||
"io"
|
||||
"strings"
|
||||
"errors"
|
||||
"github.com/dustin/go-humanize"
|
||||
"github.com/disintegration/imaging"
|
||||
)
|
||||
|
||||
type Size interface {
|
||||
Size() int64 //字节
|
||||
}
|
||||
|
||||
// 图片上传器
|
||||
type ImageUploader struct {
|
||||
UploadPath string //图片保存的磁盘目录
|
||||
UrlPath string //上传图片的URL路径
|
||||
FileName string //文件名(不含扩展名)
|
||||
AllowExtName string //允许的扩展名
|
||||
Rename bool //是否重命名文件
|
||||
Cut bool //是否裁剪图片
|
||||
Resize bool //是否重新调整大小
|
||||
ToWidth int //要操作的图片宽度
|
||||
ToHeight int //要操作的图片高度
|
||||
MaxSize uint64 //图片大小,字节
|
||||
}
|
||||
|
||||
// 创建一个新的图片上传器
|
||||
func NewImageUploader(path string) *ImageUploader {
|
||||
return &ImageUploader{
|
||||
UploadPath: path,
|
||||
UrlPath: "/upload",
|
||||
AllowExtName: "gif,jpg,png,jpeg",
|
||||
Rename: true,
|
||||
MaxSize: 2000000, //2M
|
||||
}
|
||||
}
|
||||
|
||||
// 上传图片
|
||||
func (this *ImageUploader) Upload(r *http.Request) (string, error) {
|
||||
r.ParseMultipartForm(32 << 20)
|
||||
if r.MultipartForm != nil && r.MultipartForm.File != nil {
|
||||
file, handler, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
//检查图片大小
|
||||
if sizeInterface, ok := file.(Size); ok {
|
||||
size := uint64(sizeInterface.Size())
|
||||
if size > this.MaxSize {
|
||||
return "", errors.New("图片过大,请换一张小于 " + humanize.Bytes(size) + " 的图片重新上传")
|
||||
}
|
||||
} else {
|
||||
return "", errors.New("图片尺寸超限或未能取得图片大小,请尝试换一张图片")
|
||||
}
|
||||
|
||||
if !DirIsExist(this.UploadPath) {
|
||||
err := os.MkdirAll(this.UploadPath, os.ModePerm)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
|
||||
extname := strings.ToLower(path.Ext(handler.Filename))
|
||||
allowExt := strings.Split(this.AllowExtName, ",")
|
||||
if InArray(Substr(extname, 1), allowExt) == -1 {
|
||||
return "", errors.New("不允许上传该格式的文件")
|
||||
}
|
||||
|
||||
filename := this.FileName
|
||||
if filename == "" {
|
||||
filename = path.Base(handler.Filename)
|
||||
//唯一文件名
|
||||
if this.Rename {
|
||||
filename = Md5Sum(strconv.FormatInt(time.Now().UnixNano(), 10))
|
||||
}
|
||||
}
|
||||
|
||||
if (this.Cut || this.Resize) && this.ToWidth > 0 && this.ToHeight > 0 {
|
||||
srcImg, err := imaging.Decode(file)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if this.Cut {
|
||||
srcImg = imaging.CropAnchor(srcImg, this.ToWidth, this.ToHeight, imaging.Center)
|
||||
}
|
||||
|
||||
if this.Resize {
|
||||
srcImg = imaging.Resize(srcImg, this.ToWidth, this.ToHeight, imaging.Lanczos)
|
||||
}
|
||||
err = imaging.Save(srcImg, this.UploadPath + filename + extname)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
} else {
|
||||
f, err := os.OpenFile(this.UploadPath + filename + extname, os.O_WRONLY|os.O_CREATE, 0666)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer f.Close()
|
||||
_, err = io.Copy(f, file)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
return filename + extname, nil;
|
||||
}
|
||||
return "", errors.New("没有发现上传的图片")
|
||||
}
|
|
@ -0,0 +1,107 @@
|
|||
package utils
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// buildLuaResponse构造Lua响应结果
|
||||
func BuildLuaResponse(m interface{}) string {
|
||||
var ret string
|
||||
if mm, ok := m.(map[interface{}]interface{}); ok {
|
||||
for k, i := range mm {
|
||||
vStr := ""
|
||||
switch v := i.(type) {
|
||||
case int:
|
||||
vStr = strconv.Itoa(v)
|
||||
case int8:
|
||||
vStr = strconv.Itoa(int(v))
|
||||
case int16:
|
||||
vStr = strconv.Itoa(int(v))
|
||||
case int32:
|
||||
vStr = I64toA(int64(v))
|
||||
case int64:
|
||||
vStr = I64toA(v)
|
||||
case uint:
|
||||
vStr = UitoA(v)
|
||||
case uint8:
|
||||
vStr = UitoA(uint(v))
|
||||
case uint16:
|
||||
vStr = UitoA(uint(v))
|
||||
case uint32:
|
||||
vStr = Ui32toA(v)
|
||||
case uint64:
|
||||
vStr = Ui64toA(v)
|
||||
case bool:
|
||||
if v {
|
||||
vStr = "true"
|
||||
}
|
||||
case []interface{}:
|
||||
tmp := make(map[interface{}]interface{})
|
||||
for kk, vv := range v {
|
||||
tmp[kk] = vv
|
||||
}
|
||||
vStr = BuildLuaResponse(tmp)
|
||||
case map[interface{}]interface{}:
|
||||
vStr = BuildLuaResponse(v)
|
||||
case map[string]string:
|
||||
for ks, vs := range v {
|
||||
vStr += `,` + ks + `=` + strings.Replace(vs, `"`, `\"`, -1)
|
||||
}
|
||||
vStr = "{" + Substr(vStr, 1) + "}"
|
||||
case string:
|
||||
vStr = `"` + strings.Replace(v, `"`, `\"`, -1) + `"`
|
||||
default:
|
||||
if vv, ok := v.(map[interface{}]interface{}); ok {
|
||||
vStr = BuildLuaResponse(vv)
|
||||
}
|
||||
}
|
||||
if vStr != "" {
|
||||
switch v := k.(type) {
|
||||
case int:
|
||||
ret += `,[` + strconv.Itoa(v) + `]=` + vStr
|
||||
case string:
|
||||
ret += `,` + v + `=` + vStr
|
||||
}
|
||||
}
|
||||
}
|
||||
return "{" + Substr(ret, 1) + "}"
|
||||
}
|
||||
return "{}"
|
||||
}
|
||||
|
||||
// outputLuaMsg 输出lua格式提示信息
|
||||
func OutputLua(w http.ResponseWriter, m map[interface{}]interface{}) {
|
||||
w.Write([]byte("return " + BuildLuaResponse(m)))
|
||||
}
|
||||
|
||||
// outputLuaMsg 输出lua格式提示信息
|
||||
func OutputLuaMsg(w http.ResponseWriter, msg string, code ...int) bool {
|
||||
var c int = 120
|
||||
if len(code) >= 1 {
|
||||
c = code[0]
|
||||
}
|
||||
OutputLua(w, NewLuaResult(msg, c))
|
||||
return c == 0
|
||||
}
|
||||
|
||||
// outputLuaOk 输出lua格式成功信息
|
||||
func OutputLuaOk(w http.ResponseWriter, msg string) {
|
||||
OutputLuaMsg(w, msg, 0)
|
||||
}
|
||||
|
||||
// 获取lua返回结果map
|
||||
func NewLuaResult(params ...interface{}) map[interface{}]interface{} {
|
||||
ret := make(map[interface{}]interface{})
|
||||
if len(params) > 0 {
|
||||
ret["msg"] = params[0]
|
||||
|
||||
if len(params) > 1 {
|
||||
ret["status"] = params[1]
|
||||
} else {
|
||||
ret["status"] = 0
|
||||
}
|
||||
}
|
||||
return ret
|
||||
}
|
|
@ -0,0 +1,91 @@
|
|||
package utils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 进度条定义
|
||||
type ProgressBar struct {
|
||||
Name string // 名称
|
||||
Total Counter // 总任务数
|
||||
Current *Counter // 当前已完成数量
|
||||
startTime time.Time // 任务开始时间
|
||||
exit chan struct{} // 是否退出进度条
|
||||
alreadyOutput bool
|
||||
}
|
||||
|
||||
// 完成指定数量的任务
|
||||
func (pgb *ProgressBar) Done(i ...int64) {
|
||||
if len(i) == 1 {
|
||||
pgb.Current.Add(i[0])
|
||||
} else {
|
||||
pgb.Current.Add(1)
|
||||
}
|
||||
}
|
||||
|
||||
// 退出进度条
|
||||
func (pgb *ProgressBar) Exit() {
|
||||
pgb.exit <- struct{}{}
|
||||
if pgb.alreadyOutput {
|
||||
fmt.Println("")
|
||||
}
|
||||
}
|
||||
|
||||
// 启动并显示进度条
|
||||
func (pgb *ProgressBar) Run() {
|
||||
for {
|
||||
select {
|
||||
case <-pgb.exit:
|
||||
return
|
||||
case <-time.After(time.Second):
|
||||
pgb.print()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 输出进度
|
||||
func (pgb *ProgressBar) print() {
|
||||
var percent float64 = 0
|
||||
var per, surplus int64
|
||||
|
||||
cur := pgb.Current.Get()
|
||||
if pgb.Total.Get() > 0 {
|
||||
percent = float64(cur) / float64(pgb.Total.Get())
|
||||
}
|
||||
useTime := int64(time.Now().Sub(pgb.startTime) / time.Second)
|
||||
if useTime > 0 {
|
||||
per = cur / useTime
|
||||
}
|
||||
if per > 0 {
|
||||
surplus = (pgb.Total.Get() - cur) / per
|
||||
}
|
||||
|
||||
fmt.Printf("\r\x1b[36m%s[%.2f%%] %d/%d %d/ps used:%s surplus:%s\x1b[0m", pgb.Name, percent * 100, cur, pgb.Total.Get(), per, HumanTimeSecond(useTime), HumanTimeSecond(surplus))
|
||||
|
||||
if !pgb.alreadyOutput {
|
||||
pgb.alreadyOutput = true
|
||||
}
|
||||
}
|
||||
|
||||
// 创建一个进度条
|
||||
func NewPGBar(total int64, name ...string) *ProgressBar {
|
||||
var n string
|
||||
if len(name) == 1 && name[0] != "" {
|
||||
n = name[0] + " "
|
||||
}
|
||||
return &ProgressBar{
|
||||
Name: n,
|
||||
Total: Counter{v : total},
|
||||
Current: &Counter{},
|
||||
startTime: time.Now(),
|
||||
exit: make(chan struct{}, 1),
|
||||
}
|
||||
}
|
||||
|
||||
// 生成一个新的进度条并运行
|
||||
func NewAndRunPGBar(total int64, name ...string) *ProgressBar {
|
||||
pgb := NewPGBar(total, name...)
|
||||
go pgb.Run()
|
||||
return pgb
|
||||
}
|
|
@ -0,0 +1,89 @@
|
|||
package utils
|
||||
|
||||
import (
|
||||
// "log"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
const (
|
||||
regUsername = `^[a-zA-Z0-9_]{4,22}$`
|
||||
regPwd = `^[\@A-Za-z0-9\!\#\$\%\^\&\*\.\~]{3,60}$`
|
||||
regNickname = `^{0,40}$`
|
||||
regEmail = `^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$`
|
||||
regPhone = `^((\d3)|(\d{3}\-))?13[0-9]\d{8}|14[0-9]\d{8}|15[0-9]\d{8}|17[0-9]\d{8}|18[0-9]\d{8}`
|
||||
regUrl = `^((https?|ftp|news|http):\/\/)?([a-z]([a-z0-9\-]*[\.。])+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel)|(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.%=&]*)?)?(#[a-z][a-z0-9_]*)?$`
|
||||
regGuid = `[a-zA-Z0-9-_]{0,40}`
|
||||
regDescription = `^{0,64}$`
|
||||
regOutTypeDescription = `^{0,20}$`
|
||||
regMac = `^{0,40}$`
|
||||
regTradeNo = `^[a-zA-Z0-9_-]{1,40}$`
|
||||
regAttach = `^{0,127}$`
|
||||
)
|
||||
|
||||
func CheckString(data string, pat string) bool {
|
||||
bFlag := false
|
||||
reg := regexp.MustCompile(pat)
|
||||
bFlag = reg.MatchString(data)
|
||||
return bFlag
|
||||
}
|
||||
|
||||
// 检测用户名
|
||||
func CheckUserName(username string) bool {
|
||||
return CheckString(username, regUsername)
|
||||
}
|
||||
|
||||
// 昵称
|
||||
func CheckNickname(nickname string) bool {
|
||||
return CheckString(nickname, regNickname)
|
||||
|
||||
}
|
||||
|
||||
// 密码
|
||||
func CheckPwd(password string) bool {
|
||||
return CheckString(password, regPwd)
|
||||
}
|
||||
|
||||
// 邮箱
|
||||
func CheckEmail(email string) bool {
|
||||
return CheckString(email, regEmail)
|
||||
}
|
||||
|
||||
// 手机号
|
||||
func CheckPhone(phone string) bool {
|
||||
return CheckString(phone, regPhone)
|
||||
}
|
||||
|
||||
// 网址
|
||||
func CheckUrl(url string) bool {
|
||||
return CheckString(url, regUrl)
|
||||
}
|
||||
|
||||
// guid
|
||||
func CheckGuid(guid string) bool {
|
||||
return CheckString(guid, regGuid)
|
||||
}
|
||||
|
||||
// 描述
|
||||
func CheckDescription(description string) bool {
|
||||
return CheckString(description, regDescription)
|
||||
}
|
||||
|
||||
// 平台交易类型描述
|
||||
func CheckOutTypeDescription(description string) bool {
|
||||
return CheckString(description, regOutTypeDescription)
|
||||
}
|
||||
|
||||
// mac 地址
|
||||
func CheckMac(mac string) bool {
|
||||
return CheckString(mac, regMac)
|
||||
}
|
||||
|
||||
// 订单号
|
||||
func CheckTradeNo(tradeNo string) bool {
|
||||
return CheckString(tradeNo, regTradeNo)
|
||||
}
|
||||
|
||||
// 附加参数
|
||||
func CheckAttach(attach string) bool {
|
||||
return CheckString(attach, regAttach)
|
||||
}
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,364 @@
|
|||
package utils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"math/rand"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Rand 随机数字 0 <= n < max
|
||||
func Rand(max int) int {
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
return rand.Intn(max)
|
||||
}
|
||||
|
||||
// RandInt 随机一个数字 min <= n < max
|
||||
func RandInt(min int, max int) int {
|
||||
if max == min {
|
||||
return min
|
||||
}
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
if max < min {
|
||||
min, max = max, min
|
||||
}
|
||||
return min + rand.Intn(max-min)
|
||||
}
|
||||
|
||||
// Rand64 随机数字 0 <= n < max
|
||||
func Rand64(max int64) int64 {
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
return rand.Int63n(max)
|
||||
}
|
||||
|
||||
// RandInt64 随机一个数字 min <= n < max
|
||||
func RandInt64(min int64, max int64) int64 {
|
||||
if max == min {
|
||||
return min
|
||||
}
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
if max < min {
|
||||
min, max = max, min
|
||||
}
|
||||
return min + rand.Int63n(max-min)
|
||||
}
|
||||
|
||||
// Max 取两个数较大的一个
|
||||
func Max(a, b int) int {
|
||||
if a > b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// MaxInt64 取两个数较大的一个
|
||||
func MaxInt64(a, b int64) int64 {
|
||||
if a > b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// Min 取两个数较小的一个
|
||||
func Min(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// MinInt64 取两个数较小的一个
|
||||
func MinInt64(a, b int64) int64 {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// RandNumStr 生成多位随机数字符串
|
||||
func RandNumStr(l int) string {
|
||||
ret := ""
|
||||
for i := 0; i < l; i++ {
|
||||
ret += strconv.Itoa(Rand(10))
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
// Reverse 字符串反转
|
||||
func Reverse(s string) string {
|
||||
runes := []rune(s)
|
||||
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
|
||||
runes[i], runes[j] = runes[j], runes[i]
|
||||
}
|
||||
return string(runes)
|
||||
}
|
||||
|
||||
// RandArray 随机一个数组值
|
||||
func RandArray(arr []string) string {
|
||||
return arr[Rand(len(arr))]
|
||||
}
|
||||
|
||||
// 随机一个字符串
|
||||
func RandString(l int) string {
|
||||
str := "0123456789abcdefghijklmnopqrstuvwxyz"
|
||||
bytes := []byte(str)
|
||||
result := []byte{}
|
||||
r := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
for i := 0; i < l; i++ {
|
||||
result = append(result, bytes[r.Intn(len(bytes))])
|
||||
}
|
||||
return string(result)
|
||||
}
|
||||
|
||||
// Range 生成一个数组 不包括n
|
||||
func Range(m, n int) (b []int) {
|
||||
if m >= n {
|
||||
return b
|
||||
}
|
||||
|
||||
for i := m; i < n; i++ {
|
||||
b = append(b, i)
|
||||
}
|
||||
|
||||
return b
|
||||
}
|
||||
|
||||
// Keys 返回map中的所有字符串key
|
||||
func KeysByString(m map[string]interface{}) []string {
|
||||
var keys []string
|
||||
for k, _ := range m {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
|
||||
return keys
|
||||
}
|
||||
|
||||
// Values 返回map中的所有value
|
||||
func Values(m map[string]interface{}) []interface{} {
|
||||
var values []interface{}
|
||||
for _, v := range m {
|
||||
values = append(values, v)
|
||||
}
|
||||
|
||||
return values
|
||||
}
|
||||
|
||||
// InArray 是否在列表中
|
||||
func InArray(v string, s []string) int {
|
||||
for i, val := range s {
|
||||
if val == v {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// InSlice 是否在Slice中
|
||||
/*func InSlice(v interface{}, s interface{}) int {
|
||||
if ss, ok := s.([]interface{}); ok {
|
||||
for i, val := range ss {
|
||||
if val == v {
|
||||
return i
|
||||
}
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}*/
|
||||
func InSlice(v interface{}, s interface{}) int {
|
||||
switch reflect.TypeOf(s).Kind() {
|
||||
case reflect.Slice:
|
||||
s := reflect.ValueOf(s)
|
||||
for i := 0; i < s.Len(); i++ {
|
||||
if reflect.DeepEqual(v, s.Index(i).Interface()) == true {
|
||||
return i
|
||||
}
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// Trim 清除左右两边空格
|
||||
func Trim(str string) string {
|
||||
return strings.Trim(str, " \r\n\t")
|
||||
}
|
||||
|
||||
// CheckFatal 检查致命错误
|
||||
func CheckFatal(err error) {
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
}
|
||||
|
||||
// CheckPanic 检查恐慌
|
||||
func CheckPanic(err error) {
|
||||
if err != nil {
|
||||
log.Panicln(err)
|
||||
}
|
||||
}
|
||||
|
||||
// CheckFormEmpty 检查Form表单的某个值是否为空
|
||||
// 为空返回真
|
||||
func CheckFormEmpty(form url.Values, key string) bool {
|
||||
if _, ok := form[key]; ok {
|
||||
if Trim(form[key][0]) != "" {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// 检查Form表单的哪个字段值为空
|
||||
// 发现空值时返回该字段的名称, 否则返回空白字符
|
||||
func CheckFormEmptyByKeys(form url.Values, keys string) string {
|
||||
arr := strings.Split(keys, ",")
|
||||
for _, key := range arr {
|
||||
k := Trim(key)
|
||||
if CheckFormEmpty(form, k) {
|
||||
return k
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// PrintStruct 用来打印一个结构的字段与值对应表
|
||||
func PrintStruct(structPtr interface{}) {
|
||||
s := reflect.ValueOf(structPtr).Elem()
|
||||
typeOfT := s.Type()
|
||||
for i := 0; i < s.NumField(); i++ {
|
||||
f := s.Field(i)
|
||||
fmt.Printf("%s (%s) = %v\n",
|
||||
typeOfT.Field(i).Name, f.Type(), f.Interface())
|
||||
}
|
||||
}
|
||||
|
||||
// Len 获取带有中文等非ASCII字符的字符串长度
|
||||
func Len(str string) int {
|
||||
rs := []rune(str)
|
||||
return len(rs)
|
||||
}
|
||||
|
||||
// Substr 截取字符串
|
||||
// 例: abc你好1234
|
||||
// Substr(str, 0) == abc你好1234
|
||||
// Substr(str, 2) == c你好1234
|
||||
// Substr(str, -2) == 34
|
||||
// Substr(str, 2, 3) == c你好
|
||||
// Substr(str, 0, -2) == 34
|
||||
// Substr(str, 2, -1) == b
|
||||
// Substr(str, -3, 2) == 23
|
||||
// Substr(str, -3, -2) == 好1
|
||||
func Substr(str string, start int, length ...int) string {
|
||||
rs := []rune(str)
|
||||
lth := len(rs)
|
||||
end := 0
|
||||
|
||||
if start > lth {
|
||||
return ""
|
||||
}
|
||||
|
||||
if len(length) == 1 {
|
||||
end = length[0]
|
||||
}
|
||||
|
||||
//从后数的某个位置向后截取
|
||||
if start < 0 {
|
||||
if -start >= lth {
|
||||
start = 0
|
||||
} else {
|
||||
start = lth + start
|
||||
}
|
||||
}
|
||||
|
||||
if end == 0 {
|
||||
end = lth
|
||||
} else if end > 0 {
|
||||
end += start
|
||||
if end > lth {
|
||||
end = lth
|
||||
}
|
||||
} else { //从指定位置向前截取
|
||||
if start == 0 {
|
||||
start = lth
|
||||
}
|
||||
start, end = start+end, start
|
||||
}
|
||||
if start < 0 {
|
||||
start = 0
|
||||
}
|
||||
|
||||
return string(rs[start:end])
|
||||
}
|
||||
|
||||
// SplitIDStr 把以半角逗号分隔的ID字符串分隔提取到切片中
|
||||
func SplitIDStr(str string) []int {
|
||||
ret := make([]int, 0)
|
||||
ids := strings.Split(str, ",")
|
||||
for _, idStr := range ids {
|
||||
idStr = Trim(idStr)
|
||||
if IsNumStr(idStr) {
|
||||
ret = append(ret, Atoi(idStr))
|
||||
}
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
// IntArrToString 将[]int转换成以指定分隔符分隔的字符串
|
||||
func IntArrToString(a []int, separator ...string) string {
|
||||
sep := ","
|
||||
if len(separator) == 1 {
|
||||
sep = separator[0]
|
||||
}
|
||||
return strings.Trim(strings.Replace(fmt.Sprint(a), " ", sep, -1), "[]")
|
||||
//return strings.Trim(strings.Join(strings.Split(fmt.Sprint(a), " "), sep), "[]")
|
||||
//return strings.Trim(strings.Join(strings.Fields(fmt.Sprint(a)), sep), "[]")
|
||||
}
|
||||
|
||||
// StrPad 向字符串中添加指定字符串到指定长度
|
||||
func StrPad(str interface{}, length int, pad interface{}, padLeft bool) string {
|
||||
returnStr := ""
|
||||
padStr := ""
|
||||
if "int" == GetTypeName(str) {
|
||||
returnStr = Itoa(str.(int))
|
||||
}
|
||||
|
||||
if "int" == GetTypeName(pad) {
|
||||
padStr = Itoa(pad.(int))
|
||||
}
|
||||
|
||||
padLen := length - Len(returnStr)
|
||||
if padLen > 0 {
|
||||
padString := ""
|
||||
for i := 0; i < padLen; i++ {
|
||||
padString += padStr
|
||||
}
|
||||
if padLeft {
|
||||
returnStr = padString + returnStr
|
||||
} else {
|
||||
returnStr += padString
|
||||
}
|
||||
}
|
||||
return returnStr
|
||||
}
|
||||
|
||||
// 返回sync.Map类型的长度
|
||||
func LenSyncMap(m *sync.Map) int {
|
||||
var length int
|
||||
m.Range(func(_, _ interface{}) bool {
|
||||
length++
|
||||
return true
|
||||
})
|
||||
return length
|
||||
}
|
||||
|
||||
// 模拟三元操作符
|
||||
func Ternary(b bool, trueVal, falseVal interface{}) interface{} {
|
||||
if b {
|
||||
return trueVal
|
||||
}
|
||||
return falseVal
|
||||
}
|
|
@ -0,0 +1,253 @@
|
|||
package utils
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"regexp"
|
||||
"strings"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
"math"
|
||||
)
|
||||
|
||||
// IsIDCard 检查是否是身份证
|
||||
func IsIDCard(str string, args ...bool) bool {
|
||||
if m, _ := regexp.MatchString("^(?:[\\dxX]{15}|[\\dxX]{18})$", str); !m {
|
||||
return false
|
||||
}
|
||||
|
||||
areaMap := map[int]string{
|
||||
11 : "北京",
|
||||
12 : "天津",
|
||||
13 : "河北",
|
||||
14 : "山西",
|
||||
15 : "内蒙古",
|
||||
21 : "辽宁",
|
||||
22 : "吉林",
|
||||
23 : "黑龙江",
|
||||
31 : "上海",
|
||||
32 : "江苏",
|
||||
33 : "浙江",
|
||||
34 : "安徽",
|
||||
35 : "福建",
|
||||
36 : "江西",
|
||||
37 : "山东",
|
||||
41 : "河南",
|
||||
42 : "湖北",
|
||||
43 : "湖南",
|
||||
44 : "广东",
|
||||
45 : "广西",
|
||||
46 : "海南",
|
||||
50 : "重庆",
|
||||
51 : "四川",
|
||||
52 : "贵州",
|
||||
53 : "云南",
|
||||
54 : "西藏",
|
||||
61 : "陕西",
|
||||
62 : "甘肃",
|
||||
63 : "青海",
|
||||
64 : "宁夏",
|
||||
65 : "新疆",
|
||||
71 : "台湾",
|
||||
81 : "香港",
|
||||
82 : "澳门",
|
||||
91 : "国外",
|
||||
}
|
||||
|
||||
allowLen15 := true
|
||||
if len(args) == 1 {
|
||||
allowLen15 = args[0]
|
||||
}
|
||||
|
||||
province := Atoi(Substr(str, 0, 2))
|
||||
if _, ok := areaMap[province]; !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
//如果是15位身份证
|
||||
if len(str) == 15 && allowLen15 {
|
||||
// 如果身份证顺序码是996 997 998 999,这些是为百岁以上老人的特殊编码
|
||||
code := Substr(str, 12, 3)
|
||||
if code == "996" || code == "997" || code == "998" || code == "999" {
|
||||
str = Substr(str, 0, 6) + "18" + Substr(str, 6, 9)
|
||||
} else {
|
||||
str = Substr(str, 0, 6) + "19" + Substr(str, 6, 9)
|
||||
}
|
||||
str += idcardVerifyNumber(str)
|
||||
}
|
||||
if len(str) != 18 || !checkIdcardFormat(str) {
|
||||
return false
|
||||
}
|
||||
return idcardVerifyNumber(Substr(str, 0, 17)) == strings.ToUpper(Substr(str, 17, 1))
|
||||
}
|
||||
|
||||
// checkIdcardFormat 检查身份证号码的格式
|
||||
// 针对近期出现身份证号码使用210000000000000000注册的用户
|
||||
// 验证地区码(3-6位)以及生日(6-14)位
|
||||
func checkIdcardFormat(str string) bool {
|
||||
code := Atoi(Substr(str, 3, 3))
|
||||
if code == 0 {
|
||||
return false
|
||||
}
|
||||
if len(str) == 18 {
|
||||
birthYear := Atoi(Substr(str, 6, 4))
|
||||
birthMonth := Atoi(Substr(str, 10, 2))
|
||||
birthDay := Atoi(Substr(str, 10, 2))
|
||||
if birthYear < 1900 || (birthMonth == 0 || birthMonth > 12) || (birthDay == 0 || birthDay > 31) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// idcardVerifyNumber 计算身份证校验码,根据国家标准GB 11643-1999
|
||||
func idcardVerifyNumber(str string) string {
|
||||
if len(str) != 17 {
|
||||
return ""
|
||||
}
|
||||
|
||||
//加权因子
|
||||
factor := []int{7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2}
|
||||
//校验码对应值
|
||||
verifyNumberList := []string{"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"}
|
||||
|
||||
checkSum := 0
|
||||
for i, l := 0, len(str); i < l; i++ {
|
||||
checkSum += Atoi(Substr(str, i, 1)) * factor[i]
|
||||
}
|
||||
checkSum = checkSum % 11
|
||||
return verifyNumberList[checkSum]
|
||||
}
|
||||
|
||||
// 是否为空
|
||||
func IsEmpty(val interface{}) (b bool) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
b = true
|
||||
}
|
||||
}()
|
||||
v := reflect.ValueOf(val)
|
||||
|
||||
switch v.Kind() {
|
||||
case reflect.Bool:
|
||||
b = (val.(bool) == false)
|
||||
case reflect.String:
|
||||
b = (val.(string) == "")
|
||||
case reflect.Array:
|
||||
fallthrough
|
||||
case reflect.Slice:
|
||||
fallthrough
|
||||
case reflect.Map:
|
||||
b = (v.Len() == 0)
|
||||
default:
|
||||
b = (v.Interface() == reflect.ValueOf(0).Interface() || v.Interface() == reflect.ValueOf(0.0).Interface())
|
||||
}
|
||||
|
||||
return b
|
||||
}
|
||||
|
||||
// 判断是否正确的ip地址
|
||||
func IsIp(ip string) bool {
|
||||
ips := strings.Split(ip, ".")
|
||||
if len(ips) != 4 {
|
||||
return false
|
||||
}
|
||||
for _, v := range ips {
|
||||
i := Atoi(v, -1)
|
||||
if i < 0 || i > 255 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
//检测是否为手机设备
|
||||
func IsMobileDevice(r *http.Request) bool {
|
||||
agent := r.UserAgent()
|
||||
if strings.Contains(agent,"iPhone") || strings.Contains(agent,"iPad") || strings.Contains(agent,"iOS") || strings.Contains(agent,"Android") {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// 检查字符串是否为纯数字组成
|
||||
func IsNumStr(s string) bool {
|
||||
if _, err := strconv.Atoi(s); err == nil {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// 检查字符串是否为纯数字组成
|
||||
func IsLongNumStr(s string) bool {
|
||||
if m, _ := regexp.MatchString("^\\d+$", s); m {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsMobileNum 检查是否是手机号
|
||||
func IsMobileNum(str string) bool {
|
||||
if m, _ := regexp.MatchString("^((13[\\d])|(147)|(15[\\d])|17[\\d]|(18[\\d]))[0-9]{8}$", str); m {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsVersionStr 检查字符串是否是一个版本格式
|
||||
func IsVersionStr(str string) bool {
|
||||
return IsVersion(str, "{2}")
|
||||
}
|
||||
|
||||
// IsVersion 检查字符串是否是一个版本格式
|
||||
func IsVersion(str string, length ...string) bool {
|
||||
vL := "{1,3}"
|
||||
if len(length) == 1 {
|
||||
vL = length[0]
|
||||
}
|
||||
if m, _ := regexp.MatchString("^\\d+(?:\\.\\d+)" + vL + "$", str); m {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsDeviceCode 检查字符串是否是一个机器码
|
||||
func IsDeviceCode(str string) bool {
|
||||
if m, _ := regexp.MatchString("^[a-zA-Z0-9]{40}$", str); m {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// RegexpOK 检查字符串被正则匹配
|
||||
func RegexpOK(pattern, str string) bool {
|
||||
if m, _ := regexp.MatchString(pattern, str); m {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// DiffDay 比较两个日志间隔的天数
|
||||
// 第1个日期小于第2个日期时返回正数
|
||||
// 第1个日期大于第2个日期时返回负数
|
||||
func DiffDay(t1, t2 string, fm ...string) (int, error) {
|
||||
format := "2006-01-02"
|
||||
if len(fm) == 1 {
|
||||
format = fm[0]
|
||||
}
|
||||
tm1, err := time.ParseInLocation(format, t1, time.Local)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
tm2, err := time.ParseInLocation(format, t2, time.Local)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
hour := tm2.Sub(tm1).Hours()
|
||||
if -24 >= hour || hour >= 24 {
|
||||
return int(math.Ceil(hour / 24)), nil
|
||||
}
|
||||
return 0, nil
|
||||
}
|
|
@ -0,0 +1,144 @@
|
|||
package utils
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var regexpSigns = regexp.MustCompile(`[_\-+]`)
|
||||
var regexpDotBeforeDigit = regexp.MustCompile(`([^.\d]+)`)
|
||||
var regexpMultipleDots = regexp.MustCompile(`\.{2,}`)
|
||||
|
||||
var specialForms = map[string]int{
|
||||
"dev": -6,
|
||||
"alpha": -5,
|
||||
"a": -5,
|
||||
"beta": -4,
|
||||
"b": -4,
|
||||
"RC": -3,
|
||||
"rc": -3,
|
||||
"#": -2,
|
||||
"p": 1,
|
||||
"pl": 1,
|
||||
}
|
||||
|
||||
// Compares two normalizated version number strings, for a particular relationship
|
||||
//
|
||||
// The function first replaces _, - and + with a dot . in the version strings
|
||||
// and also inserts dots . before and after any non number so that for example
|
||||
// '4.3.2RC1' becomes '4.3.2.RC.1'.
|
||||
//
|
||||
// Then it splits the results like if you were using Split(version, '.').
|
||||
// Then it compares the parts starting from left to right. If a part contains
|
||||
// special version strings these are handled in the following order: any string
|
||||
// not found in this list:
|
||||
// < dev < alpha = a < beta = b < RC = rc < # < pl = p.
|
||||
//
|
||||
// Usage
|
||||
// version.Compare("1.0-dev", "1.0", "<")
|
||||
// Returns: true
|
||||
//
|
||||
// version.Compare("1.0rc1", "1.0", ">=")
|
||||
// Returns: false
|
||||
//
|
||||
// version.Compare("1.0", "1.0b1", "ge")
|
||||
// Returns: true
|
||||
func CompareVersion(version1, version2, operator string) bool {
|
||||
compare := CompareVersionSimple(version1, version2)
|
||||
|
||||
switch {
|
||||
case operator == ">" || operator == "gt":
|
||||
return compare > 0
|
||||
case operator == ">=" || operator == "ge":
|
||||
return compare >= 0
|
||||
case operator == "<=" || operator == "le":
|
||||
return compare <= 0
|
||||
case operator == "==" || operator == "=" || operator == "eq":
|
||||
return compare == 0
|
||||
case operator == "<>" || operator == "!=" || operator == "ne":
|
||||
return compare != 0
|
||||
case operator == "" || operator == "<" || operator == "lt":
|
||||
return compare < 0
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// Compares two normalizated version number strings
|
||||
//
|
||||
// Just the same of CompareVersion but return a int result, 0 if both version
|
||||
// are equal, 1 if the right side is bigger and -1 if the right side is lower
|
||||
//
|
||||
// Usage
|
||||
// version.CompareVersionSimple("1.2", "1.0.1")
|
||||
// Returns: 1
|
||||
//
|
||||
// version.CompareVersionSimple("1.0rc1", "1.0")
|
||||
// Returns: -1
|
||||
func CompareVersionSimple(version1, version2 string) int {
|
||||
var x, r, l int = 0, 0, 0
|
||||
|
||||
v1, v2 := prepVersion(version1), prepVersion(version2)
|
||||
len1, len2 := len(v1), len(v2)
|
||||
|
||||
if len1 > len2 {
|
||||
x = len1
|
||||
} else {
|
||||
x = len2
|
||||
}
|
||||
|
||||
for i := 0; i < x; i++ {
|
||||
if i < len1 && i < len2 {
|
||||
if v1[i] == v2[i] {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
r = 0
|
||||
if i < len1 {
|
||||
r = numVersion(v1[i])
|
||||
}
|
||||
|
||||
l = 0
|
||||
if i < len2 {
|
||||
l = numVersion(v2[i])
|
||||
}
|
||||
|
||||
if r < l {
|
||||
return -1
|
||||
} else if r > l {
|
||||
return 1
|
||||
}
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
func prepVersion(version string) []string {
|
||||
if len(version) == 0 {
|
||||
return []string{""}
|
||||
}
|
||||
|
||||
version = regexpSigns.ReplaceAllString(version, ".")
|
||||
version = regexpDotBeforeDigit.ReplaceAllString(version, ".$1.")
|
||||
version = regexpMultipleDots.ReplaceAllString(version, ".")
|
||||
|
||||
return strings.Split(version, ".")
|
||||
}
|
||||
|
||||
func numVersion(value string) int {
|
||||
if value == "" {
|
||||
return 0
|
||||
}
|
||||
|
||||
if number, err := strconv.Atoi(value); err == nil {
|
||||
return number
|
||||
}
|
||||
|
||||
if special, ok := specialForms[value]; ok {
|
||||
return special
|
||||
}
|
||||
|
||||
return -7
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
Copyright (c) 2012 The Go Authors. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following disclaimer
|
||||
in the documentation and/or other materials provided with the
|
||||
distribution.
|
||||
* Neither the name of Google Inc. nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@ -0,0 +1,215 @@
|
|||
# A pure Go MSSQL driver for Go's database/sql package
|
||||
|
||||
[![GoDoc](https://godoc.org/github.com/denisenkom/go-mssqldb?status.svg)](http://godoc.org/github.com/denisenkom/go-mssqldb)
|
||||
[![Build status](https://ci.appveyor.com/api/projects/status/jrln8cs62wj9i0a2?svg=true)](https://ci.appveyor.com/project/denisenkom/go-mssqldb)
|
||||
[![codecov](https://codecov.io/gh/denisenkom/go-mssqldb/branch/master/graph/badge.svg)](https://codecov.io/gh/denisenkom/go-mssqldb)
|
||||
|
||||
## Install
|
||||
|
||||
Requires Go 1.8 or above.
|
||||
|
||||
Install with `go get github.com/denisenkom/go-mssqldb` .
|
||||
|
||||
## Connection Parameters and DSN
|
||||
|
||||
The recommended connection string uses a URL format:
|
||||
`sqlserver://username:password@host/instance?param1=value¶m2=value`
|
||||
Other supported formats are listed below.
|
||||
|
||||
### Common parameters:
|
||||
|
||||
* `user id` - enter the SQL Server Authentication user id or the Windows Authentication user id in the DOMAIN\User format. On Windows, if user id is empty or missing Single-Sign-On is used.
|
||||
* `password`
|
||||
* `database`
|
||||
* `connection timeout` - in seconds (default is 0 for no timeout), set to 0 for no timeout. Recommended to set to 0 and use context to manage query and connection timeouts.
|
||||
* `dial timeout` - in seconds (default is 15), set to 0 for no timeout
|
||||
* `encrypt`
|
||||
* `disable` - Data send between client and server is not encrypted.
|
||||
* `false` - Data sent between client and server is not encrypted beyond the login packet. (Default)
|
||||
* `true` - Data sent between client and server is encrypted.
|
||||
* `app name` - The application name (default is go-mssqldb)
|
||||
|
||||
### Connection parameters for ODBC and ADO style connection strings:
|
||||
|
||||
* `server` - host or host\instance (default localhost)
|
||||
* `port` - used only when there is no instance in server (default 1433)
|
||||
|
||||
### Less common parameters:
|
||||
|
||||
* `keepAlive` - in seconds; 0 to disable (default is 30)
|
||||
* `failoverpartner` - host or host\instance (default is no partner).
|
||||
* `failoverport` - used only when there is no instance in failoverpartner (default 1433)
|
||||
* `packet size` - in bytes; 512 to 32767 (default is 4096)
|
||||
* Encrypted connections have a maximum packet size of 16383 bytes
|
||||
* Further information on usage: https://docs.microsoft.com/en-us/sql/database-engine/configure-windows/configure-the-network-packet-size-server-configuration-option
|
||||
* `log` - logging flags (default 0/no logging, 63 for full logging)
|
||||
* 1 log errors
|
||||
* 2 log messages
|
||||
* 4 log rows affected
|
||||
* 8 trace sql statements
|
||||
* 16 log statement parameters
|
||||
* 32 log transaction begin/end
|
||||
* `TrustServerCertificate`
|
||||
* false - Server certificate is checked. Default is false if encypt is specified.
|
||||
* true - Server certificate is not checked. Default is true if encrypt is not specified. If trust server certificate is true, driver accepts any certificate presented by the server and any host name in that certificate. In this mode, TLS is susceptible to man-in-the-middle attacks. This should be used only for testing.
|
||||
* `certificate` - The file that contains the public key certificate of the CA that signed the SQL Server certificate. The specified certificate overrides the go platform specific CA certificates.
|
||||
* `hostNameInCertificate` - Specifies the Common Name (CN) in the server certificate. Default value is the server host.
|
||||
* `ServerSPN` - The kerberos SPN (Service Principal Name) for the server. Default is MSSQLSvc/host:port.
|
||||
* `Workstation ID` - The workstation name (default is the host name)
|
||||
* `ApplicationIntent` - Can be given the value `ReadOnly` to initiate a read-only connection to an Availability Group listener.
|
||||
|
||||
### The connection string can be specified in one of three formats:
|
||||
|
||||
|
||||
1. URL: with `sqlserver` scheme. username and password appears before the host. Any instance appears as
|
||||
the first segment in the path. All other options are query parameters. Examples:
|
||||
|
||||
* `sqlserver://username:password@host/instance?param1=value¶m2=value`
|
||||
* `sqlserver://username:password@host:port?param1=value¶m2=value`
|
||||
* `sqlserver://sa@localhost/SQLExpress?database=master&connection+timeout=30` // `SQLExpress instance.
|
||||
* `sqlserver://sa:mypass@localhost?database=master&connection+timeout=30` // username=sa, password=mypass.
|
||||
* `sqlserver://sa:mypass@localhost:1234?database=master&connection+timeout=30` // port 1234 on localhost.
|
||||
* `sqlserver://sa:my%7Bpass@somehost?connection+timeout=30` // password is "my{pass"
|
||||
|
||||
A string of this format can be constructed using the `URL` type in the `net/url` package.
|
||||
|
||||
```go
|
||||
query := url.Values{}
|
||||
query.Add("app name", "MyAppName")
|
||||
|
||||
u := &url.URL{
|
||||
Scheme: "sqlserver",
|
||||
User: url.UserPassword(username, password),
|
||||
Host: fmt.Sprintf("%s:%d", hostname, port),
|
||||
// Path: instance, // if connecting to an instance instead of a port
|
||||
RawQuery: query.Encode(),
|
||||
}
|
||||
db, err := sql.Open("sqlserver", u.String())
|
||||
```
|
||||
|
||||
2. ADO: `key=value` pairs separated by `;`. Values may not contain `;`, leading and trailing whitespace is ignored.
|
||||
Examples:
|
||||
|
||||
* `server=localhost\\SQLExpress;user id=sa;database=master;app name=MyAppName`
|
||||
* `server=localhost;user id=sa;database=master;app name=MyAppName`
|
||||
|
||||
3. ODBC: Prefix with `odbc`, `key=value` pairs separated by `;`. Allow `;` by wrapping
|
||||
values in `{}`. Examples:
|
||||
|
||||
* `odbc:server=localhost\\SQLExpress;user id=sa;database=master;app name=MyAppName`
|
||||
* `odbc:server=localhost;user id=sa;database=master;app name=MyAppName`
|
||||
* `odbc:server=localhost;user id=sa;password={foo;bar}` // Value marked with `{}`, password is "foo;bar"
|
||||
* `odbc:server=localhost;user id=sa;password={foo{bar}` // Value marked with `{}`, password is "foo{bar"
|
||||
* `odbc:server=localhost;user id=sa;password={foobar }` // Value marked with `{}`, password is "foobar "
|
||||
* `odbc:server=localhost;user id=sa;password=foo{bar` // Literal `{`, password is "foo{bar"
|
||||
* `odbc:server=localhost;user id=sa;password=foo}bar` // Literal `}`, password is "foo}bar"
|
||||
* `odbc:server=localhost;user id=sa;password={foo{bar}` // Literal `{`, password is "foo{bar"
|
||||
* `odbc:server=localhost;user id=sa;password={foo}}bar}` // Escaped `} with `}}`, password is "foo}bar"
|
||||
|
||||
## Executing Stored Procedures
|
||||
|
||||
To run a stored procedure, set the query text to the procedure name:
|
||||
```go
|
||||
var account = "abc"
|
||||
_, err := db.ExecContext(ctx, "sp_RunMe",
|
||||
sql.Named("ID", 123),
|
||||
sql.Named("Account", sql.Out{Dest: &account}),
|
||||
)
|
||||
```
|
||||
|
||||
## Return Status
|
||||
|
||||
To get the procedure return status, pass into the parameters a
|
||||
`*mssql.ReturnStatus`. For example:
|
||||
```
|
||||
var rs mssql.ReturnStatus
|
||||
_, err := db.ExecContext(ctx, "theproc", &rs)
|
||||
log.Printf("status=%d", rs)
|
||||
```
|
||||
|
||||
## Parameters
|
||||
|
||||
The `sqlserver` driver uses normal MS SQL Server syntax and expects parameters in
|
||||
the sql query to be in the form of either `@Name` or `@p1` to `@pN` (ordinal position).
|
||||
|
||||
```go
|
||||
db.QueryContext(ctx, `select * from t where ID = @ID and Name = @p2;`, sql.Named("ID", 6), "Bob")
|
||||
```
|
||||
|
||||
### Parameter Types
|
||||
|
||||
To pass specific types to the query parameters, say `varchar` or `date` types,
|
||||
you must convert the types to the type before passing in. The following types
|
||||
are supported:
|
||||
|
||||
* string -> nvarchar
|
||||
* mssql.VarChar -> varchar
|
||||
* time.Time -> datetimeoffset or datetime (TDS version dependent)
|
||||
* mssql.DateTime1 -> datetime
|
||||
* mssql.DateTimeOffset -> datetimeoffset
|
||||
* "cloud.google.com/go/civil".Date -> date
|
||||
* "cloud.google.com/go/civil".DateTime -> datetime2
|
||||
* "cloud.google.com/go/civil".Time -> time
|
||||
|
||||
## Important Notes
|
||||
|
||||
* [LastInsertId](https://golang.org/pkg/database/sql/#Result.LastInsertId) should
|
||||
not be used with this driver (or SQL Server) due to how the TDS protocol
|
||||
works. Please use the [OUTPUT Clause](https://docs.microsoft.com/en-us/sql/t-sql/queries/output-clause-transact-sql)
|
||||
or add a `select ID = convert(bigint, SCOPE_IDENTITY());` to the end of your
|
||||
query (ref [SCOPE_IDENTITY](https://docs.microsoft.com/en-us/sql/t-sql/functions/scope-identity-transact-sql)).
|
||||
This will ensure you are getting the correct ID and will prevent a network round trip.
|
||||
* [NewConnector](https://godoc.org/github.com/denisenkom/go-mssqldb#NewConnector)
|
||||
may be used with [OpenDB](https://golang.org/pkg/database/sql/#OpenDB).
|
||||
* [Connector.SessionInitSQL](https://godoc.org/github.com/denisenkom/go-mssqldb#Connector.SessionInitSQL)
|
||||
may be set to set any driver specific session settings after the session
|
||||
has been reset. If empty the session will still be reset but use the database
|
||||
defaults in Go1.10+.
|
||||
|
||||
## Features
|
||||
|
||||
* Can be used with SQL Server 2005 or newer
|
||||
* Can be used with Microsoft Azure SQL Database
|
||||
* Can be used on all go supported platforms (e.g. Linux, Mac OS X and Windows)
|
||||
* Supports new date/time types: date, time, datetime2, datetimeoffset
|
||||
* Supports string parameters longer than 8000 characters
|
||||
* Supports encryption using SSL/TLS
|
||||
* Supports SQL Server and Windows Authentication
|
||||
* Supports Single-Sign-On on Windows
|
||||
* Supports connections to AlwaysOn Availability Group listeners, including re-direction to read-only replicas.
|
||||
* Supports query notifications
|
||||
|
||||
## Tests
|
||||
|
||||
`go test` is used for testing. A running instance of MSSQL server is required.
|
||||
Environment variables are used to pass login information.
|
||||
|
||||
Example:
|
||||
|
||||
env SQLSERVER_DSN=sqlserver://user:pass@hostname/instance?database=test1 go test
|
||||
|
||||
## Deprecated
|
||||
|
||||
These features still exist in the driver, but they are are deprecated.
|
||||
|
||||
### Query Parameter Token Replace (driver "mssql")
|
||||
|
||||
If you use the driver name "mssql" (rather then "sqlserver") the SQL text
|
||||
will be loosly parsed and an attempt to extract identifiers using one of
|
||||
|
||||
* ?
|
||||
* ?nnn
|
||||
* :nnn
|
||||
* $nnn
|
||||
|
||||
will be used. This is not recommended with SQL Server.
|
||||
There is at least one existing `won't fix` issue with the query parsing.
|
||||
|
||||
Use the native "@Name" parameters instead with the "sqlserver" driver name.
|
||||
|
||||
## Known Issues
|
||||
|
||||
* SQL Server 2008 and 2008 R2 engine cannot handle login records when SSL encryption is not disabled.
|
||||
To fix SQL Server 2008 R2 issue, install SQL Server 2008 R2 Service Pack 2.
|
||||
To fix SQL Server 2008 issue, install Microsoft SQL Server 2008 Service Pack 3 and Cumulative update package 3 for SQL Server 2008 SP3.
|
||||
More information: http://support.microsoft.com/kb/2653857
|
|
@ -0,0 +1,48 @@
|
|||
version: 1.0.{build}
|
||||
|
||||
os: Windows Server 2012 R2
|
||||
|
||||
clone_folder: c:\gopath\src\github.com\denisenkom\go-mssqldb
|
||||
|
||||
environment:
|
||||
GOPATH: c:\gopath
|
||||
HOST: localhost
|
||||
SQLUSER: sa
|
||||
SQLPASSWORD: Password12!
|
||||
DATABASE: test
|
||||
GOVERSION: 110
|
||||
matrix:
|
||||
- GOVERSION: 18
|
||||
SQLINSTANCE: SQL2016
|
||||
- GOVERSION: 19
|
||||
SQLINSTANCE: SQL2016
|
||||
- GOVERSION: 110
|
||||
SQLINSTANCE: SQL2016
|
||||
- SQLINSTANCE: SQL2014
|
||||
- SQLINSTANCE: SQL2012SP1
|
||||
- SQLINSTANCE: SQL2008R2SP2
|
||||
|
||||
install:
|
||||
- set GOROOT=c:\go%GOVERSION%
|
||||
- set PATH=%GOPATH%\bin;%GOROOT%\bin;%PATH%
|
||||
- go version
|
||||
- go env
|
||||
- go get -u cloud.google.com/go/civil
|
||||
|
||||
build_script:
|
||||
- go build
|
||||
|
||||
before_test:
|
||||
# setup SQL Server
|
||||
- ps: |
|
||||
$instanceName = $env:SQLINSTANCE
|
||||
Start-Service "MSSQL`$$instanceName"
|
||||
Start-Service "SQLBrowser"
|
||||
- sqlcmd -S "(local)\%SQLINSTANCE%" -Q "Use [master]; CREATE DATABASE test;"
|
||||
- sqlcmd -S "(local)\%SQLINSTANCE%" -h -1 -Q "set nocount on; Select @@version"
|
||||
- pip install codecov
|
||||
|
||||
|
||||
test_script:
|
||||
- go test -race -cpu 4 -coverprofile=coverage.txt -covermode=atomic
|
||||
- codecov -f coverage.txt
|
|
@ -0,0 +1,258 @@
|
|||
package mssql
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
)
|
||||
|
||||
type packetType uint8
|
||||
|
||||
type header struct {
|
||||
PacketType packetType
|
||||
Status uint8
|
||||
Size uint16
|
||||
Spid uint16
|
||||
PacketNo uint8
|
||||
Pad uint8
|
||||
}
|
||||
|
||||
// tdsBuffer reads and writes TDS packets of data to the transport.
|
||||
// The write and read buffers are separate to make sending attn signals
|
||||
// possible without locks. Currently attn signals are only sent during
|
||||
// reads, not writes.
|
||||
type tdsBuffer struct {
|
||||
transport io.ReadWriteCloser
|
||||
|
||||
packetSize int
|
||||
|
||||
// Write fields.
|
||||
wbuf []byte
|
||||
wpos int
|
||||
wPacketSeq byte
|
||||
wPacketType packetType
|
||||
|
||||
// Read fields.
|
||||
rbuf []byte
|
||||
rpos int
|
||||
rsize int
|
||||
final bool
|
||||
rPacketType packetType
|
||||
|
||||
// afterFirst is assigned to right after tdsBuffer is created and
|
||||
// before the first use. It is executed after the first packet is
|
||||
// written and then removed.
|
||||
afterFirst func()
|
||||
}
|
||||
|
||||
func newTdsBuffer(bufsize uint16, transport io.ReadWriteCloser) *tdsBuffer {
|
||||
return &tdsBuffer{
|
||||
packetSize: int(bufsize),
|
||||
wbuf: make([]byte, 1<<16),
|
||||
rbuf: make([]byte, 1<<16),
|
||||
rpos: 8,
|
||||
transport: transport,
|
||||
}
|
||||
}
|
||||
|
||||
func (rw *tdsBuffer) ResizeBuffer(packetSize int) {
|
||||
rw.packetSize = packetSize
|
||||
}
|
||||
|
||||
func (w *tdsBuffer) PackageSize() int {
|
||||
return w.packetSize
|
||||
}
|
||||
|
||||
func (w *tdsBuffer) flush() (err error) {
|
||||
// Write packet size.
|
||||
w.wbuf[0] = byte(w.wPacketType)
|
||||
binary.BigEndian.PutUint16(w.wbuf[2:], uint16(w.wpos))
|
||||
w.wbuf[6] = w.wPacketSeq
|
||||
|
||||
// Write packet into underlying transport.
|
||||
if _, err = w.transport.Write(w.wbuf[:w.wpos]); err != nil {
|
||||
return err
|
||||
}
|
||||
// It is possible to create a whole new buffer after a flush.
|
||||
// Useful for debugging. Normally reuse the buffer.
|
||||
// w.wbuf = make([]byte, 1<<16)
|
||||
|
||||
// Execute afterFirst hook if it is set.
|
||||
if w.afterFirst != nil {
|
||||
w.afterFirst()
|
||||
w.afterFirst = nil
|
||||
}
|
||||
|
||||
w.wpos = 8
|
||||
w.wPacketSeq++
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *tdsBuffer) Write(p []byte) (total int, err error) {
|
||||
for {
|
||||
copied := copy(w.wbuf[w.wpos:w.packetSize], p)
|
||||
w.wpos += copied
|
||||
total += copied
|
||||
if copied == len(p) {
|
||||
return
|
||||
}
|
||||
if err = w.flush(); err != nil {
|
||||
return
|
||||
}
|
||||
p = p[copied:]
|
||||
}
|
||||
}
|
||||
|
||||
func (w *tdsBuffer) WriteByte(b byte) error {
|
||||
if int(w.wpos) == len(w.wbuf) || w.wpos == w.packetSize {
|
||||
if err := w.flush(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
w.wbuf[w.wpos] = b
|
||||
w.wpos += 1
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *tdsBuffer) BeginPacket(packetType packetType, resetSession bool) {
|
||||
status := byte(0)
|
||||
if resetSession {
|
||||
switch packetType {
|
||||
// Reset session can only be set on the following packet types.
|
||||
case packSQLBatch, packRPCRequest, packTransMgrReq:
|
||||
status = 0x8
|
||||
}
|
||||
}
|
||||
w.wbuf[1] = status // Packet is incomplete. This byte is set again in FinishPacket.
|
||||
w.wpos = 8
|
||||
w.wPacketSeq = 1
|
||||
w.wPacketType = packetType
|
||||
}
|
||||
|
||||
func (w *tdsBuffer) FinishPacket() error {
|
||||
w.wbuf[1] |= 1 // Mark this as the last packet in the message.
|
||||
return w.flush()
|
||||
}
|
||||
|
||||
var headerSize = binary.Size(header{})
|
||||
|
||||
func (r *tdsBuffer) readNextPacket() error {
|
||||
h := header{}
|
||||
var err error
|
||||
err = binary.Read(r.transport, binary.BigEndian, &h)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if int(h.Size) > r.packetSize {
|
||||
return errors.New("Invalid packet size, it is longer than buffer size")
|
||||
}
|
||||
if headerSize > int(h.Size) {
|
||||
return errors.New("Invalid packet size, it is shorter than header size")
|
||||
}
|
||||
_, err = io.ReadFull(r.transport, r.rbuf[headerSize:h.Size])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r.rpos = headerSize
|
||||
r.rsize = int(h.Size)
|
||||
r.final = h.Status != 0
|
||||
r.rPacketType = h.PacketType
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *tdsBuffer) BeginRead() (packetType, error) {
|
||||
err := r.readNextPacket()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return r.rPacketType, nil
|
||||
}
|
||||
|
||||
func (r *tdsBuffer) ReadByte() (res byte, err error) {
|
||||
if r.rpos == r.rsize {
|
||||
if r.final {
|
||||
return 0, io.EOF
|
||||
}
|
||||
err = r.readNextPacket()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
res = r.rbuf[r.rpos]
|
||||
r.rpos++
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func (r *tdsBuffer) byte() byte {
|
||||
b, err := r.ReadByte()
|
||||
if err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func (r *tdsBuffer) ReadFull(buf []byte) {
|
||||
_, err := io.ReadFull(r, buf[:])
|
||||
if err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *tdsBuffer) uint64() uint64 {
|
||||
var buf [8]byte
|
||||
r.ReadFull(buf[:])
|
||||
return binary.LittleEndian.Uint64(buf[:])
|
||||
}
|
||||
|
||||
func (r *tdsBuffer) int32() int32 {
|
||||
return int32(r.uint32())
|
||||
}
|
||||
|
||||
func (r *tdsBuffer) uint32() uint32 {
|
||||
var buf [4]byte
|
||||
r.ReadFull(buf[:])
|
||||
return binary.LittleEndian.Uint32(buf[:])
|
||||
}
|
||||
|
||||
func (r *tdsBuffer) uint16() uint16 {
|
||||
var buf [2]byte
|
||||
r.ReadFull(buf[:])
|
||||
return binary.LittleEndian.Uint16(buf[:])
|
||||
}
|
||||
|
||||
func (r *tdsBuffer) BVarChar() string {
|
||||
l := int(r.byte())
|
||||
return r.readUcs2(l)
|
||||
}
|
||||
|
||||
func (r *tdsBuffer) UsVarChar() string {
|
||||
l := int(r.uint16())
|
||||
return r.readUcs2(l)
|
||||
}
|
||||
|
||||
func (r *tdsBuffer) readUcs2(numchars int) string {
|
||||
b := make([]byte, numchars*2)
|
||||
r.ReadFull(b)
|
||||
res, err := ucs22str(b)
|
||||
if err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func (r *tdsBuffer) Read(buf []byte) (copied int, err error) {
|
||||
copied = 0
|
||||
err = nil
|
||||
if r.rpos == r.rsize {
|
||||
if r.final {
|
||||
return 0, io.EOF
|
||||
}
|
||||
err = r.readNextPacket()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
copied = copy(buf, r.rbuf[r.rpos:r.rsize])
|
||||
r.rpos += copied
|
||||
return
|
||||
}
|
|
@ -0,0 +1,554 @@
|
|||
package mssql
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"math"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Bulk struct {
|
||||
// ctx is used only for AddRow and Done methods.
|
||||
// This could be removed if AddRow and Done accepted
|
||||
// a ctx field as well, which is available with the
|
||||
// database/sql call.
|
||||
ctx context.Context
|
||||
|
||||
cn *Conn
|
||||
metadata []columnStruct
|
||||
bulkColumns []columnStruct
|
||||
columnsName []string
|
||||
tablename string
|
||||
numRows int
|
||||
|
||||
headerSent bool
|
||||
Options BulkOptions
|
||||
Debug bool
|
||||
}
|
||||
type BulkOptions struct {
|
||||
CheckConstraints bool
|
||||
FireTriggers bool
|
||||
KeepNulls bool
|
||||
KilobytesPerBatch int
|
||||
RowsPerBatch int
|
||||
Order []string
|
||||
Tablock bool
|
||||
}
|
||||
|
||||
type DataValue interface{}
|
||||
|
||||
func (cn *Conn) CreateBulk(table string, columns []string) (_ *Bulk) {
|
||||
b := Bulk{ctx: context.Background(), cn: cn, tablename: table, headerSent: false, columnsName: columns}
|
||||
b.Debug = false
|
||||
return &b
|
||||
}
|
||||
|
||||
func (cn *Conn) CreateBulkContext(ctx context.Context, table string, columns []string) (_ *Bulk) {
|
||||
b := Bulk{ctx: ctx, cn: cn, tablename: table, headerSent: false, columnsName: columns}
|
||||
b.Debug = false
|
||||
return &b
|
||||
}
|
||||
|
||||
func (b *Bulk) sendBulkCommand(ctx context.Context) (err error) {
|
||||
//get table columns info
|
||||
err = b.getMetadata(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
//match the columns
|
||||
for _, colname := range b.columnsName {
|
||||
var bulkCol *columnStruct
|
||||
|
||||
for _, m := range b.metadata {
|
||||
if m.ColName == colname {
|
||||
bulkCol = &m
|
||||
break
|
||||
}
|
||||
}
|
||||
if bulkCol != nil {
|
||||
|
||||
if bulkCol.ti.TypeId == typeUdt {
|
||||
//send udt as binary
|
||||
bulkCol.ti.TypeId = typeBigVarBin
|
||||
}
|
||||
b.bulkColumns = append(b.bulkColumns, *bulkCol)
|
||||
b.dlogf("Adding column %s %s %#x", colname, bulkCol.ColName, bulkCol.ti.TypeId)
|
||||
} else {
|
||||
return fmt.Errorf("Column %s does not exist in destination table %s", colname, b.tablename)
|
||||
}
|
||||
}
|
||||
|
||||
//create the bulk command
|
||||
|
||||
//columns definitions
|
||||
var col_defs bytes.Buffer
|
||||
for i, col := range b.bulkColumns {
|
||||
if i != 0 {
|
||||
col_defs.WriteString(", ")
|
||||
}
|
||||
col_defs.WriteString("[" + col.ColName + "] " + makeDecl(col.ti))
|
||||
}
|
||||
|
||||
//options
|
||||
var with_opts []string
|
||||
|
||||
if b.Options.CheckConstraints {
|
||||
with_opts = append(with_opts, "CHECK_CONSTRAINTS")
|
||||
}
|
||||
if b.Options.FireTriggers {
|
||||
with_opts = append(with_opts, "FIRE_TRIGGERS")
|
||||
}
|
||||
if b.Options.KeepNulls {
|
||||
with_opts = append(with_opts, "KEEP_NULLS")
|
||||
}
|
||||
if b.Options.KilobytesPerBatch > 0 {
|
||||
with_opts = append(with_opts, fmt.Sprintf("KILOBYTES_PER_BATCH = %d", b.Options.KilobytesPerBatch))
|
||||
}
|
||||
if b.Options.RowsPerBatch > 0 {
|
||||
with_opts = append(with_opts, fmt.Sprintf("ROWS_PER_BATCH = %d", b.Options.RowsPerBatch))
|
||||
}
|
||||
if len(b.Options.Order) > 0 {
|
||||
with_opts = append(with_opts, fmt.Sprintf("ORDER(%s)", strings.Join(b.Options.Order, ",")))
|
||||
}
|
||||
if b.Options.Tablock {
|
||||
with_opts = append(with_opts, "TABLOCK")
|
||||
}
|
||||
var with_part string
|
||||
if len(with_opts) > 0 {
|
||||
with_part = fmt.Sprintf("WITH (%s)", strings.Join(with_opts, ","))
|
||||
}
|
||||
|
||||
query := fmt.Sprintf("INSERT BULK %s (%s) %s", b.tablename, col_defs.String(), with_part)
|
||||
|
||||
stmt, err := b.cn.PrepareContext(ctx, query)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Prepare failed: %s", err.Error())
|
||||
}
|
||||
b.dlogf(query)
|
||||
|
||||
_, err = stmt.(*Stmt).ExecContext(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
b.headerSent = true
|
||||
|
||||
var buf = b.cn.sess.buf
|
||||
buf.BeginPacket(packBulkLoadBCP, false)
|
||||
|
||||
// Send the columns metadata.
|
||||
columnMetadata := b.createColMetadata()
|
||||
_, err = buf.Write(columnMetadata)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// AddRow immediately writes the row to the destination table.
|
||||
// The arguments are the row values in the order they were specified.
|
||||
func (b *Bulk) AddRow(row []interface{}) (err error) {
|
||||
if !b.headerSent {
|
||||
err = b.sendBulkCommand(b.ctx)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if len(row) != len(b.bulkColumns) {
|
||||
return fmt.Errorf("Row does not have the same number of columns than the destination table %d %d",
|
||||
len(row), len(b.bulkColumns))
|
||||
}
|
||||
|
||||
bytes, err := b.makeRowData(row)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
_, err = b.cn.sess.buf.Write(bytes)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
b.numRows = b.numRows + 1
|
||||
return
|
||||
}
|
||||
|
||||
func (b *Bulk) makeRowData(row []interface{}) ([]byte, error) {
|
||||
buf := new(bytes.Buffer)
|
||||
buf.WriteByte(byte(tokenRow))
|
||||
|
||||
var logcol bytes.Buffer
|
||||
for i, col := range b.bulkColumns {
|
||||
|
||||
if b.Debug {
|
||||
logcol.WriteString(fmt.Sprintf(" col[%d]='%v' ", i, row[i]))
|
||||
}
|
||||
param, err := b.makeParam(row[i], col)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("bulkcopy: %s", err.Error())
|
||||
}
|
||||
|
||||
if col.ti.Writer == nil {
|
||||
return nil, fmt.Errorf("no writer for column: %s, TypeId: %#x",
|
||||
col.ColName, col.ti.TypeId)
|
||||
}
|
||||
err = col.ti.Writer(buf, param.ti, param.buffer)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("bulkcopy: %s", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
b.dlogf("row[%d] %s\n", b.numRows, logcol.String())
|
||||
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
func (b *Bulk) Done() (rowcount int64, err error) {
|
||||
if b.headerSent == false {
|
||||
//no rows had been sent
|
||||
return 0, nil
|
||||
}
|
||||
var buf = b.cn.sess.buf
|
||||
buf.WriteByte(byte(tokenDone))
|
||||
|
||||
binary.Write(buf, binary.LittleEndian, uint16(doneFinal))
|
||||
binary.Write(buf, binary.LittleEndian, uint16(0)) // curcmd
|
||||
|
||||
if b.cn.sess.loginAck.TDSVersion >= verTDS72 {
|
||||
binary.Write(buf, binary.LittleEndian, uint64(0)) //rowcount 0
|
||||
} else {
|
||||
binary.Write(buf, binary.LittleEndian, uint32(0)) //rowcount 0
|
||||
}
|
||||
|
||||
buf.FinishPacket()
|
||||
|
||||
tokchan := make(chan tokenStruct, 5)
|
||||
go processResponse(b.ctx, b.cn.sess, tokchan, nil)
|
||||
|
||||
var rowCount int64
|
||||
for token := range tokchan {
|
||||
switch token := token.(type) {
|
||||
case doneStruct:
|
||||
if token.Status&doneCount != 0 {
|
||||
rowCount = int64(token.RowCount)
|
||||
}
|
||||
if token.isError() {
|
||||
return 0, token.getError()
|
||||
}
|
||||
case error:
|
||||
return 0, b.cn.checkBadConn(token)
|
||||
}
|
||||
}
|
||||
return rowCount, nil
|
||||
}
|
||||
|
||||
func (b *Bulk) createColMetadata() []byte {
|
||||
buf := new(bytes.Buffer)
|
||||
buf.WriteByte(byte(tokenColMetadata)) // token
|
||||
binary.Write(buf, binary.LittleEndian, uint16(len(b.bulkColumns))) // column count
|
||||
|
||||
for i, col := range b.bulkColumns {
|
||||
|
||||
if b.cn.sess.loginAck.TDSVersion >= verTDS72 {
|
||||
binary.Write(buf, binary.LittleEndian, uint32(col.UserType)) // usertype, always 0?
|
||||
} else {
|
||||
binary.Write(buf, binary.LittleEndian, uint16(col.UserType))
|
||||
}
|
||||
binary.Write(buf, binary.LittleEndian, uint16(col.Flags))
|
||||
|
||||
writeTypeInfo(buf, &b.bulkColumns[i].ti)
|
||||
|
||||
if col.ti.TypeId == typeNText ||
|
||||
col.ti.TypeId == typeText ||
|
||||
col.ti.TypeId == typeImage {
|
||||
|
||||
tablename_ucs2 := str2ucs2(b.tablename)
|
||||
binary.Write(buf, binary.LittleEndian, uint16(len(tablename_ucs2)/2))
|
||||
buf.Write(tablename_ucs2)
|
||||
}
|
||||
colname_ucs2 := str2ucs2(col.ColName)
|
||||
buf.WriteByte(uint8(len(colname_ucs2) / 2))
|
||||
buf.Write(colname_ucs2)
|
||||
}
|
||||
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
func (b *Bulk) getMetadata(ctx context.Context) (err error) {
|
||||
stmt, err := b.cn.prepareContext(ctx, "SET FMTONLY ON")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
_, err = stmt.ExecContext(ctx, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// Get columns info.
|
||||
stmt, err = b.cn.prepareContext(ctx, fmt.Sprintf("select * from %s SET FMTONLY OFF", b.tablename))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
rows, err := stmt.QueryContext(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("get columns info failed: %v", err)
|
||||
}
|
||||
b.metadata = rows.(*Rows).cols
|
||||
|
||||
if b.Debug {
|
||||
for _, col := range b.metadata {
|
||||
b.dlogf("col: %s typeId: %#x size: %d scale: %d prec: %d flags: %d lcid: %#x\n",
|
||||
col.ColName, col.ti.TypeId, col.ti.Size, col.ti.Scale, col.ti.Prec,
|
||||
col.Flags, col.ti.Collation.LcidAndFlags)
|
||||
}
|
||||
}
|
||||
|
||||
return rows.Close()
|
||||
}
|
||||
|
||||
func (b *Bulk) makeParam(val DataValue, col columnStruct) (res param, err error) {
|
||||
res.ti.Size = col.ti.Size
|
||||
res.ti.TypeId = col.ti.TypeId
|
||||
|
||||
if val == nil {
|
||||
res.ti.Size = 0
|
||||
return
|
||||
}
|
||||
|
||||
switch col.ti.TypeId {
|
||||
|
||||
case typeInt1, typeInt2, typeInt4, typeInt8, typeIntN:
|
||||
var intvalue int64
|
||||
|
||||
switch val := val.(type) {
|
||||
case int:
|
||||
intvalue = int64(val)
|
||||
case int32:
|
||||
intvalue = int64(val)
|
||||
case int64:
|
||||
intvalue = val
|
||||
default:
|
||||
err = fmt.Errorf("mssql: invalid type for int column")
|
||||
return
|
||||
}
|
||||
|
||||
res.buffer = make([]byte, res.ti.Size)
|
||||
if col.ti.Size == 1 {
|
||||
res.buffer[0] = byte(intvalue)
|
||||
} else if col.ti.Size == 2 {
|
||||
binary.LittleEndian.PutUint16(res.buffer, uint16(intvalue))
|
||||
} else if col.ti.Size == 4 {
|
||||
binary.LittleEndian.PutUint32(res.buffer, uint32(intvalue))
|
||||
} else if col.ti.Size == 8 {
|
||||
binary.LittleEndian.PutUint64(res.buffer, uint64(intvalue))
|
||||
}
|
||||
case typeFlt4, typeFlt8, typeFltN:
|
||||
var floatvalue float64
|
||||
|
||||
switch val := val.(type) {
|
||||
case float32:
|
||||
floatvalue = float64(val)
|
||||
case float64:
|
||||
floatvalue = val
|
||||
case int:
|
||||
floatvalue = float64(val)
|
||||
case int64:
|
||||
floatvalue = float64(val)
|
||||
default:
|
||||
err = fmt.Errorf("mssql: invalid type for float column: %s", val)
|
||||
return
|
||||
}
|
||||
|
||||
if col.ti.Size == 4 {
|
||||
res.buffer = make([]byte, 4)
|
||||
binary.LittleEndian.PutUint32(res.buffer, math.Float32bits(float32(floatvalue)))
|
||||
} else if col.ti.Size == 8 {
|
||||
res.buffer = make([]byte, 8)
|
||||
binary.LittleEndian.PutUint64(res.buffer, math.Float64bits(floatvalue))
|
||||
}
|
||||
case typeNVarChar, typeNText, typeNChar:
|
||||
|
||||
switch val := val.(type) {
|
||||
case string:
|
||||
res.buffer = str2ucs2(val)
|
||||
case []byte:
|
||||
res.buffer = val
|
||||
default:
|
||||
err = fmt.Errorf("mssql: invalid type for nvarchar column: %s", val)
|
||||
return
|
||||
}
|
||||
res.ti.Size = len(res.buffer)
|
||||
|
||||
case typeVarChar, typeBigVarChar, typeText, typeChar, typeBigChar:
|
||||
switch val := val.(type) {
|
||||
case string:
|
||||
res.buffer = []byte(val)
|
||||
case []byte:
|
||||
res.buffer = val
|
||||
default:
|
||||
err = fmt.Errorf("mssql: invalid type for varchar column: %s", val)
|
||||
return
|
||||
}
|
||||
res.ti.Size = len(res.buffer)
|
||||
|
||||
case typeBit, typeBitN:
|
||||
if reflect.TypeOf(val).Kind() != reflect.Bool {
|
||||
err = fmt.Errorf("mssql: invalid type for bit column: %s", val)
|
||||
return
|
||||
}
|
||||
res.ti.TypeId = typeBitN
|
||||
res.ti.Size = 1
|
||||
res.buffer = make([]byte, 1)
|
||||
if val.(bool) {
|
||||
res.buffer[0] = 1
|
||||
}
|
||||
case typeDateTime2N:
|
||||
switch val := val.(type) {
|
||||
case time.Time:
|
||||
res.buffer = encodeDateTime2(val, int(col.ti.Scale))
|
||||
res.ti.Size = len(res.buffer)
|
||||
default:
|
||||
err = fmt.Errorf("mssql: invalid type for datetime2 column: %s", val)
|
||||
return
|
||||
}
|
||||
case typeDateTimeOffsetN:
|
||||
switch val := val.(type) {
|
||||
case time.Time:
|
||||
res.buffer = encodeDateTimeOffset(val, int(res.ti.Scale))
|
||||
res.ti.Size = len(res.buffer)
|
||||
|
||||
default:
|
||||
err = fmt.Errorf("mssql: invalid type for datetimeoffset column: %s", val)
|
||||
return
|
||||
}
|
||||
case typeDateN:
|
||||
switch val := val.(type) {
|
||||
case time.Time:
|
||||
res.buffer = encodeDate(val)
|
||||
res.ti.Size = len(res.buffer)
|
||||
default:
|
||||
err = fmt.Errorf("mssql: invalid type for date column: %s", val)
|
||||
return
|
||||
}
|
||||
case typeDateTime, typeDateTimeN, typeDateTim4:
|
||||
switch val := val.(type) {
|
||||
case time.Time:
|
||||
if col.ti.Size == 4 {
|
||||
res.buffer = encodeDateTim4(val)
|
||||
res.ti.Size = len(res.buffer)
|
||||
} else if col.ti.Size == 8 {
|
||||
res.buffer = encodeDateTime(val)
|
||||
res.ti.Size = len(res.buffer)
|
||||
} else {
|
||||
err = fmt.Errorf("mssql: invalid size of column")
|
||||
}
|
||||
|
||||
default:
|
||||
err = fmt.Errorf("mssql: invalid type for datetime column: %s", val)
|
||||
}
|
||||
|
||||
// case typeMoney, typeMoney4, typeMoneyN:
|
||||
case typeDecimal, typeDecimalN, typeNumeric, typeNumericN:
|
||||
var value float64
|
||||
switch v := val.(type) {
|
||||
case int:
|
||||
value = float64(v)
|
||||
case int8:
|
||||
value = float64(v)
|
||||
case int16:
|
||||
value = float64(v)
|
||||
case int32:
|
||||
value = float64(v)
|
||||
case int64:
|
||||
value = float64(v)
|
||||
case float32:
|
||||
value = float64(v)
|
||||
case float64:
|
||||
value = v
|
||||
case string:
|
||||
if value, err = strconv.ParseFloat(v, 64); err != nil {
|
||||
return res, fmt.Errorf("bulk: unable to convert string to float: %v", err)
|
||||
}
|
||||
default:
|
||||
return res, fmt.Errorf("unknown value for decimal: %#v", v)
|
||||
}
|
||||
|
||||
perc := col.ti.Prec
|
||||
scale := col.ti.Scale
|
||||
var dec Decimal
|
||||
dec, err = Float64ToDecimalScale(value, scale)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
dec.prec = perc
|
||||
|
||||
var length byte
|
||||
switch {
|
||||
case perc <= 9:
|
||||
length = 4
|
||||
case perc <= 19:
|
||||
length = 8
|
||||
case perc <= 28:
|
||||
length = 12
|
||||
default:
|
||||
length = 16
|
||||
}
|
||||
|
||||
buf := make([]byte, length+1)
|
||||
// first byte length written by typeInfo.writer
|
||||
res.ti.Size = int(length) + 1
|
||||
// second byte sign
|
||||
if value < 0 {
|
||||
buf[0] = 0
|
||||
} else {
|
||||
buf[0] = 1
|
||||
}
|
||||
|
||||
ub := dec.UnscaledBytes()
|
||||
l := len(ub)
|
||||
if l > int(length) {
|
||||
err = fmt.Errorf("decimal out of range: %s", dec)
|
||||
return res, err
|
||||
}
|
||||
// reverse the bytes
|
||||
for i, j := 1, l-1; j >= 0; i, j = i+1, j-1 {
|
||||
buf[i] = ub[j]
|
||||
}
|
||||
res.buffer = buf
|
||||
case typeBigVarBin, typeBigBinary:
|
||||
switch val := val.(type) {
|
||||
case []byte:
|
||||
res.ti.Size = len(val)
|
||||
res.buffer = val
|
||||
default:
|
||||
err = fmt.Errorf("mssql: invalid type for Binary column: %s", val)
|
||||
return
|
||||
}
|
||||
case typeGuid:
|
||||
switch val := val.(type) {
|
||||
case []byte:
|
||||
res.ti.Size = len(val)
|
||||
res.buffer = val
|
||||
default:
|
||||
err = fmt.Errorf("mssql: invalid type for Guid column: %s", val)
|
||||
return
|
||||
}
|
||||
|
||||
default:
|
||||
err = fmt.Errorf("mssql: type %x not implemented", col.ti.TypeId)
|
||||
}
|
||||
return
|
||||
|
||||
}
|
||||
|
||||
func (b *Bulk) dlogf(format string, v ...interface{}) {
|
||||
if b.Debug {
|
||||
b.cn.sess.log.Printf(format, v...)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,93 @@
|
|||
package mssql
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql/driver"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
)
|
||||
|
||||
type copyin struct {
|
||||
cn *Conn
|
||||
bulkcopy *Bulk
|
||||
closed bool
|
||||
}
|
||||
|
||||
type serializableBulkConfig struct {
|
||||
TableName string
|
||||
ColumnsName []string
|
||||
Options BulkOptions
|
||||
}
|
||||
|
||||
func (d *Driver) OpenConnection(dsn string) (*Conn, error) {
|
||||
return d.open(context.Background(), dsn)
|
||||
}
|
||||
|
||||
func (c *Conn) prepareCopyIn(ctx context.Context, query string) (_ driver.Stmt, err error) {
|
||||
config_json := query[11:]
|
||||
|
||||
bulkconfig := serializableBulkConfig{}
|
||||
err = json.Unmarshal([]byte(config_json), &bulkconfig)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
bulkcopy := c.CreateBulkContext(ctx, bulkconfig.TableName, bulkconfig.ColumnsName)
|
||||
bulkcopy.Options = bulkconfig.Options
|
||||
|
||||
ci := ©in{
|
||||
cn: c,
|
||||
bulkcopy: bulkcopy,
|
||||
}
|
||||
|
||||
return ci, nil
|
||||
}
|
||||
|
||||
func CopyIn(table string, options BulkOptions, columns ...string) string {
|
||||
bulkconfig := &serializableBulkConfig{TableName: table, Options: options, ColumnsName: columns}
|
||||
|
||||
config_json, err := json.Marshal(bulkconfig)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
stmt := "INSERTBULK " + string(config_json)
|
||||
|
||||
return stmt
|
||||
}
|
||||
|
||||
func (ci *copyin) NumInput() int {
|
||||
return -1
|
||||
}
|
||||
|
||||
func (ci *copyin) Query(v []driver.Value) (r driver.Rows, err error) {
|
||||
panic("should never be called")
|
||||
}
|
||||
|
||||
func (ci *copyin) Exec(v []driver.Value) (r driver.Result, err error) {
|
||||
if ci.closed {
|
||||
return nil, errors.New("copyin query is closed")
|
||||
}
|
||||
|
||||
if len(v) == 0 {
|
||||
rowCount, err := ci.bulkcopy.Done()
|
||||
ci.closed = true
|
||||
return driver.RowsAffected(rowCount), err
|
||||
}
|
||||
|
||||
t := make([]interface{}, len(v))
|
||||
for i, val := range v {
|
||||
t[i] = val
|
||||
}
|
||||
|
||||
err = ci.bulkcopy.AddRow(t)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
return driver.RowsAffected(0), nil
|
||||
}
|
||||
|
||||
func (ci *copyin) Close() (err error) {
|
||||
return nil
|
||||
}
|
|
@ -0,0 +1,306 @@
|
|||
package mssql
|
||||
|
||||
import "errors"
|
||||
|
||||
// Copyright 2011 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Type conversions for Scan.
|
||||
|
||||
// This file was imported from database.sql.convert for go 1.10.3 with minor modifications to get
|
||||
// convertAssign function
|
||||
// This function is used internally by sql to convert values during call to Scan, we need same
|
||||
// logic to return values for OUTPUT parameters.
|
||||
// TODO: sql library should instead expose function defaultCheckNamedValue to be callable by drivers
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"database/sql/driver"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
var errNilPtr = errors.New("destination pointer is nil") // embedded in descriptive error
|
||||
|
||||
// convertAssign copies to dest the value in src, converting it if possible.
|
||||
// An error is returned if the copy would result in loss of information.
|
||||
// dest should be a pointer type.
|
||||
func convertAssign(dest, src interface{}) error {
|
||||
// Common cases, without reflect.
|
||||
switch s := src.(type) {
|
||||
case string:
|
||||
switch d := dest.(type) {
|
||||
case *string:
|
||||
if d == nil {
|
||||
return errNilPtr
|
||||
}
|
||||
*d = s
|
||||
return nil
|
||||
case *[]byte:
|
||||
if d == nil {
|
||||
return errNilPtr
|
||||
}
|
||||
*d = []byte(s)
|
||||
return nil
|
||||
case *sql.RawBytes:
|
||||
if d == nil {
|
||||
return errNilPtr
|
||||
}
|
||||
*d = append((*d)[:0], s...)
|
||||
return nil
|
||||
}
|
||||
case []byte:
|
||||
switch d := dest.(type) {
|
||||
case *string:
|
||||
if d == nil {
|
||||
return errNilPtr
|
||||
}
|
||||
*d = string(s)
|
||||
return nil
|
||||
case *interface{}:
|
||||
if d == nil {
|
||||
return errNilPtr
|
||||
}
|
||||
*d = cloneBytes(s)
|
||||
return nil
|
||||
case *[]byte:
|
||||
if d == nil {
|
||||
return errNilPtr
|
||||
}
|
||||
*d = cloneBytes(s)
|
||||
return nil
|
||||
case *sql.RawBytes:
|
||||
if d == nil {
|
||||
return errNilPtr
|
||||
}
|
||||
*d = s
|
||||
return nil
|
||||
}
|
||||
case time.Time:
|
||||
switch d := dest.(type) {
|
||||
case *time.Time:
|
||||
*d = s
|
||||
return nil
|
||||
case *string:
|
||||
*d = s.Format(time.RFC3339Nano)
|
||||
return nil
|
||||
case *[]byte:
|
||||
if d == nil {
|
||||
return errNilPtr
|
||||
}
|
||||
*d = []byte(s.Format(time.RFC3339Nano))
|
||||
return nil
|
||||
case *sql.RawBytes:
|
||||
if d == nil {
|
||||
return errNilPtr
|
||||
}
|
||||
*d = s.AppendFormat((*d)[:0], time.RFC3339Nano)
|
||||
return nil
|
||||
}
|
||||
case nil:
|
||||
switch d := dest.(type) {
|
||||
case *interface{}:
|
||||
if d == nil {
|
||||
return errNilPtr
|
||||
}
|
||||
*d = nil
|
||||
return nil
|
||||
case *[]byte:
|
||||
if d == nil {
|
||||
return errNilPtr
|
||||
}
|
||||
*d = nil
|
||||
return nil
|
||||
case *sql.RawBytes:
|
||||
if d == nil {
|
||||
return errNilPtr
|
||||
}
|
||||
*d = nil
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
var sv reflect.Value
|
||||
|
||||
switch d := dest.(type) {
|
||||
case *string:
|
||||
sv = reflect.ValueOf(src)
|
||||
switch sv.Kind() {
|
||||
case reflect.Bool,
|
||||
reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
|
||||
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
|
||||
reflect.Float32, reflect.Float64:
|
||||
*d = asString(src)
|
||||
return nil
|
||||
}
|
||||
case *[]byte:
|
||||
sv = reflect.ValueOf(src)
|
||||
if b, ok := asBytes(nil, sv); ok {
|
||||
*d = b
|
||||
return nil
|
||||
}
|
||||
case *sql.RawBytes:
|
||||
sv = reflect.ValueOf(src)
|
||||
if b, ok := asBytes([]byte(*d)[:0], sv); ok {
|
||||
*d = sql.RawBytes(b)
|
||||
return nil
|
||||
}
|
||||
case *bool:
|
||||
bv, err := driver.Bool.ConvertValue(src)
|
||||
if err == nil {
|
||||
*d = bv.(bool)
|
||||
}
|
||||
return err
|
||||
case *interface{}:
|
||||
*d = src
|
||||
return nil
|
||||
}
|
||||
|
||||
if scanner, ok := dest.(sql.Scanner); ok {
|
||||
return scanner.Scan(src)
|
||||
}
|
||||
|
||||
dpv := reflect.ValueOf(dest)
|
||||
if dpv.Kind() != reflect.Ptr {
|
||||
return errors.New("destination not a pointer")
|
||||
}
|
||||
if dpv.IsNil() {
|
||||
return errNilPtr
|
||||
}
|
||||
|
||||
if !sv.IsValid() {
|
||||
sv = reflect.ValueOf(src)
|
||||
}
|
||||
|
||||
dv := reflect.Indirect(dpv)
|
||||
if sv.IsValid() && sv.Type().AssignableTo(dv.Type()) {
|
||||
switch b := src.(type) {
|
||||
case []byte:
|
||||
dv.Set(reflect.ValueOf(cloneBytes(b)))
|
||||
default:
|
||||
dv.Set(sv)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
if dv.Kind() == sv.Kind() && sv.Type().ConvertibleTo(dv.Type()) {
|
||||
dv.Set(sv.Convert(dv.Type()))
|
||||
return nil
|
||||
}
|
||||
|
||||
// The following conversions use a string value as an intermediate representation
|
||||
// to convert between various numeric types.
|
||||
//
|
||||
// This also allows scanning into user defined types such as "type Int int64".
|
||||
// For symmetry, also check for string destination types.
|
||||
switch dv.Kind() {
|
||||
case reflect.Ptr:
|
||||
if src == nil {
|
||||
dv.Set(reflect.Zero(dv.Type()))
|
||||
return nil
|
||||
} else {
|
||||
dv.Set(reflect.New(dv.Type().Elem()))
|
||||
return convertAssign(dv.Interface(), src)
|
||||
}
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
s := asString(src)
|
||||
i64, err := strconv.ParseInt(s, 10, dv.Type().Bits())
|
||||
if err != nil {
|
||||
err = strconvErr(err)
|
||||
return fmt.Errorf("converting driver.Value type %T (%q) to a %s: %v", src, s, dv.Kind(), err)
|
||||
}
|
||||
dv.SetInt(i64)
|
||||
return nil
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||
s := asString(src)
|
||||
u64, err := strconv.ParseUint(s, 10, dv.Type().Bits())
|
||||
if err != nil {
|
||||
err = strconvErr(err)
|
||||
return fmt.Errorf("converting driver.Value type %T (%q) to a %s: %v", src, s, dv.Kind(), err)
|
||||
}
|
||||
dv.SetUint(u64)
|
||||
return nil
|
||||
case reflect.Float32, reflect.Float64:
|
||||
s := asString(src)
|
||||
f64, err := strconv.ParseFloat(s, dv.Type().Bits())
|
||||
if err != nil {
|
||||
err = strconvErr(err)
|
||||
return fmt.Errorf("converting driver.Value type %T (%q) to a %s: %v", src, s, dv.Kind(), err)
|
||||
}
|
||||
dv.SetFloat(f64)
|
||||
return nil
|
||||
case reflect.String:
|
||||
switch v := src.(type) {
|
||||
case string:
|
||||
dv.SetString(v)
|
||||
return nil
|
||||
case []byte:
|
||||
dv.SetString(string(v))
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf("unsupported Scan, storing driver.Value type %T into type %T", src, dest)
|
||||
}
|
||||
|
||||
func strconvErr(err error) error {
|
||||
if ne, ok := err.(*strconv.NumError); ok {
|
||||
return ne.Err
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func cloneBytes(b []byte) []byte {
|
||||
if b == nil {
|
||||
return nil
|
||||
} else {
|
||||
c := make([]byte, len(b))
|
||||
copy(c, b)
|
||||
return c
|
||||
}
|
||||
}
|
||||
|
||||
func asString(src interface{}) string {
|
||||
switch v := src.(type) {
|
||||
case string:
|
||||
return v
|
||||
case []byte:
|
||||
return string(v)
|
||||
}
|
||||
rv := reflect.ValueOf(src)
|
||||
switch rv.Kind() {
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
return strconv.FormatInt(rv.Int(), 10)
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||
return strconv.FormatUint(rv.Uint(), 10)
|
||||
case reflect.Float64:
|
||||
return strconv.FormatFloat(rv.Float(), 'g', -1, 64)
|
||||
case reflect.Float32:
|
||||
return strconv.FormatFloat(rv.Float(), 'g', -1, 32)
|
||||
case reflect.Bool:
|
||||
return strconv.FormatBool(rv.Bool())
|
||||
}
|
||||
return fmt.Sprintf("%v", src)
|
||||
}
|
||||
|
||||
func asBytes(buf []byte, rv reflect.Value) (b []byte, ok bool) {
|
||||
switch rv.Kind() {
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
return strconv.AppendInt(buf, rv.Int(), 10), true
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||
return strconv.AppendUint(buf, rv.Uint(), 10), true
|
||||
case reflect.Float32:
|
||||
return strconv.AppendFloat(buf, rv.Float(), 'g', -1, 32), true
|
||||
case reflect.Float64:
|
||||
return strconv.AppendFloat(buf, rv.Float(), 'g', -1, 64), true
|
||||
case reflect.Bool:
|
||||
return strconv.AppendBool(buf, rv.Bool()), true
|
||||
case reflect.String:
|
||||
s := rv.String()
|
||||
return append(buf, s...), true
|
||||
}
|
||||
return
|
||||
}
|
|
@ -0,0 +1,131 @@
|
|||
package mssql
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"math"
|
||||
"math/big"
|
||||
)
|
||||
|
||||
// http://msdn.microsoft.com/en-us/library/ee780893.aspx
|
||||
type Decimal struct {
|
||||
integer [4]uint32
|
||||
positive bool
|
||||
prec uint8
|
||||
scale uint8
|
||||
}
|
||||
|
||||
var scaletblflt64 [39]float64
|
||||
|
||||
func (d Decimal) ToFloat64() float64 {
|
||||
val := float64(0)
|
||||
for i := 3; i >= 0; i-- {
|
||||
val *= 0x100000000
|
||||
val += float64(d.integer[i])
|
||||
}
|
||||
if !d.positive {
|
||||
val = -val
|
||||
}
|
||||
if d.scale != 0 {
|
||||
val /= scaletblflt64[d.scale]
|
||||
}
|
||||
return val
|
||||
}
|
||||
|
||||
const autoScale = 100
|
||||
|
||||
func Float64ToDecimal(f float64) (Decimal, error) {
|
||||
return Float64ToDecimalScale(f, autoScale)
|
||||
}
|
||||
|
||||
func Float64ToDecimalScale(f float64, scale uint8) (Decimal, error) {
|
||||
var dec Decimal
|
||||
if math.IsNaN(f) {
|
||||
return dec, errors.New("NaN")
|
||||
}
|
||||
if math.IsInf(f, 0) {
|
||||
return dec, errors.New("Infinity can't be converted to decimal")
|
||||
}
|
||||
dec.positive = f >= 0
|
||||
if !dec.positive {
|
||||
f = math.Abs(f)
|
||||
}
|
||||
if f > 3.402823669209385e+38 {
|
||||
return dec, errors.New("Float value is out of range")
|
||||
}
|
||||
dec.prec = 20
|
||||
var integer float64
|
||||
for dec.scale = 0; dec.scale <= scale; dec.scale++ {
|
||||
integer = f * scaletblflt64[dec.scale]
|
||||
_, frac := math.Modf(integer)
|
||||
if frac == 0 && scale == autoScale {
|
||||
break
|
||||
}
|
||||
}
|
||||
for i := 0; i < 4; i++ {
|
||||
mod := math.Mod(integer, 0x100000000)
|
||||
integer -= mod
|
||||
integer /= 0x100000000
|
||||
dec.integer[i] = uint32(mod)
|
||||
}
|
||||
return dec, nil
|
||||
}
|
||||
|
||||
func init() {
|
||||
var acc float64 = 1
|
||||
for i := 0; i <= 38; i++ {
|
||||
scaletblflt64[i] = acc
|
||||
acc *= 10
|
||||
}
|
||||
}
|
||||
|
||||
func (d Decimal) BigInt() big.Int {
|
||||
bytes := make([]byte, 16)
|
||||
binary.BigEndian.PutUint32(bytes[0:4], d.integer[3])
|
||||
binary.BigEndian.PutUint32(bytes[4:8], d.integer[2])
|
||||
binary.BigEndian.PutUint32(bytes[8:12], d.integer[1])
|
||||
binary.BigEndian.PutUint32(bytes[12:16], d.integer[0])
|
||||
var x big.Int
|
||||
x.SetBytes(bytes)
|
||||
if !d.positive {
|
||||
x.Neg(&x)
|
||||
}
|
||||
return x
|
||||
}
|
||||
|
||||
func (d Decimal) Bytes() []byte {
|
||||
x := d.BigInt()
|
||||
return scaleBytes(x.String(), d.scale)
|
||||
}
|
||||
|
||||
func (d Decimal) UnscaledBytes() []byte {
|
||||
x := d.BigInt()
|
||||
return x.Bytes()
|
||||
}
|
||||
|
||||
func scaleBytes(s string, scale uint8) []byte {
|
||||
z := make([]byte, 0, len(s)+1)
|
||||
if s[0] == '-' || s[0] == '+' {
|
||||
z = append(z, byte(s[0]))
|
||||
s = s[1:]
|
||||
}
|
||||
pos := len(s) - int(scale)
|
||||
if pos <= 0 {
|
||||
z = append(z, byte('0'))
|
||||
} else if pos > 0 {
|
||||
z = append(z, []byte(s[:pos])...)
|
||||
}
|
||||
if scale > 0 {
|
||||
z = append(z, byte('.'))
|
||||
for pos < 0 {
|
||||
z = append(z, byte('0'))
|
||||
pos++
|
||||
}
|
||||
z = append(z, []byte(s[pos:])...)
|
||||
}
|
||||
return z
|
||||
}
|
||||
|
||||
func (d Decimal) String() string {
|
||||
return string(d.Bytes())
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
// package mssql implements the TDS protocol used to connect to MS SQL Server (sqlserver)
|
||||
// database servers.
|
||||
//
|
||||
// This package registers the driver:
|
||||
// sqlserver: uses native "@" parameter placeholder names and does no pre-processing.
|
||||
//
|
||||
// If the ordinal position is used for query parameters, identifiers will be named
|
||||
// "@p1", "@p2", ... "@pN".
|
||||
//
|
||||
// Please refer to the README for the format of the DSN. There are multiple DSN
|
||||
// formats accepted: ADO style, ODBC style, and URL style. The following is an
|
||||
// example of a URL style DSN:
|
||||
// sqlserver://sa:mypass@localhost:1234?database=master&connection+timeout=30
|
||||
package mssql
|
|
@ -0,0 +1,73 @@
|
|||
package mssql
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// Error represents an SQL Server error. This
|
||||
// type includes methods for reading the contents
|
||||
// of the struct, which allows calling programs
|
||||
// to check for specific error conditions without
|
||||
// having to import this package directly.
|
||||
type Error struct {
|
||||
Number int32
|
||||
State uint8
|
||||
Class uint8
|
||||
Message string
|
||||
ServerName string
|
||||
ProcName string
|
||||
LineNo int32
|
||||
}
|
||||
|
||||
func (e Error) Error() string {
|
||||
return "mssql: " + e.Message
|
||||
}
|
||||
|
||||
// SQLErrorNumber returns the SQL Server error number.
|
||||
func (e Error) SQLErrorNumber() int32 {
|
||||
return e.Number
|
||||
}
|
||||
|
||||
func (e Error) SQLErrorState() uint8 {
|
||||
return e.State
|
||||
}
|
||||
|
||||
func (e Error) SQLErrorClass() uint8 {
|
||||
return e.Class
|
||||
}
|
||||
|
||||
func (e Error) SQLErrorMessage() string {
|
||||
return e.Message
|
||||
}
|
||||
|
||||
func (e Error) SQLErrorServerName() string {
|
||||
return e.ServerName
|
||||
}
|
||||
|
||||
func (e Error) SQLErrorProcName() string {
|
||||
return e.ProcName
|
||||
}
|
||||
|
||||
func (e Error) SQLErrorLineNo() int32 {
|
||||
return e.LineNo
|
||||
}
|
||||
|
||||
type StreamError struct {
|
||||
Message string
|
||||
}
|
||||
|
||||
func (e StreamError) Error() string {
|
||||
return e.Message
|
||||
}
|
||||
|
||||
func streamErrorf(format string, v ...interface{}) StreamError {
|
||||
return StreamError{"Invalid TDS stream: " + fmt.Sprintf(format, v...)}
|
||||
}
|
||||
|
||||
func badStreamPanic(err error) {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
func badStreamPanicf(format string, v ...interface{}) {
|
||||
panic(streamErrorf(format, v...))
|
||||
}
|
|
@ -0,0 +1,113 @@
|
|||
package cp
|
||||
|
||||
type charsetMap struct {
|
||||
sb [256]rune // single byte runes, -1 for a double byte character lead byte
|
||||
db map[int]rune // double byte runes
|
||||
}
|
||||
|
||||
func collation2charset(col Collation) *charsetMap {
|
||||
// http://msdn.microsoft.com/en-us/library/ms144250.aspx
|
||||
// http://msdn.microsoft.com/en-us/library/ms144250(v=sql.105).aspx
|
||||
switch col.SortId {
|
||||
case 30, 31, 32, 33, 34:
|
||||
return cp437
|
||||
case 40, 41, 42, 44, 49, 55, 56, 57, 58, 59, 60, 61:
|
||||
return cp850
|
||||
case 50, 51, 52, 53, 54, 71, 72, 73, 74, 75:
|
||||
return cp1252
|
||||
case 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96:
|
||||
return cp1250
|
||||
case 104, 105, 106, 107, 108:
|
||||
return cp1251
|
||||
case 112, 113, 114, 121, 124:
|
||||
return cp1253
|
||||
case 128, 129, 130:
|
||||
return cp1254
|
||||
case 136, 137, 138:
|
||||
return cp1255
|
||||
case 144, 145, 146:
|
||||
return cp1256
|
||||
case 152, 153, 154, 155, 156, 157, 158, 159, 160:
|
||||
return cp1257
|
||||
case 183, 184, 185, 186:
|
||||
return cp1252
|
||||
case 192, 193:
|
||||
return cp932
|
||||
case 194, 195:
|
||||
return cp949
|
||||
case 196, 197:
|
||||
return cp950
|
||||
case 198, 199:
|
||||
return cp936
|
||||
case 200:
|
||||
return cp932
|
||||
case 201:
|
||||
return cp949
|
||||
case 202:
|
||||
return cp950
|
||||
case 203:
|
||||
return cp936
|
||||
case 204, 205, 206:
|
||||
return cp874
|
||||
case 210, 211, 212, 213, 214, 215, 216, 217:
|
||||
return cp1252
|
||||
}
|
||||
// http://technet.microsoft.com/en-us/library/aa176553(v=sql.80).aspx
|
||||
switch col.getLcid() {
|
||||
case 0x001e, 0x041e:
|
||||
return cp874
|
||||
case 0x0411, 0x10411:
|
||||
return cp932
|
||||
case 0x0804, 0x1004, 0x20804:
|
||||
return cp936
|
||||
case 0x0012, 0x0412:
|
||||
return cp949
|
||||
case 0x0404, 0x1404, 0x0c04, 0x7c04, 0x30404:
|
||||
return cp950
|
||||
case 0x041c, 0x041a, 0x0405, 0x040e, 0x104e, 0x0415, 0x0418, 0x041b, 0x0424, 0x1040e:
|
||||
return cp1250
|
||||
case 0x0423, 0x0402, 0x042f, 0x0419, 0x081a, 0x0c1a, 0x0422, 0x043f, 0x0444, 0x082c:
|
||||
return cp1251
|
||||
case 0x0408:
|
||||
return cp1253
|
||||
case 0x041f, 0x042c, 0x0443:
|
||||
return cp1254
|
||||
case 0x040d:
|
||||
return cp1255
|
||||
case 0x0401, 0x0801, 0xc01, 0x1001, 0x1401, 0x1801, 0x1c01, 0x2001, 0x2401, 0x2801, 0x2c01, 0x3001, 0x3401, 0x3801, 0x3c01, 0x4001, 0x0429, 0x0420:
|
||||
return cp1256
|
||||
case 0x0425, 0x0426, 0x0427, 0x0827:
|
||||
return cp1257
|
||||
case 0x042a:
|
||||
return cp1258
|
||||
case 0x0439, 0x045a, 0x0465:
|
||||
return nil
|
||||
}
|
||||
return cp1252
|
||||
}
|
||||
|
||||
func CharsetToUTF8(col Collation, s []byte) string {
|
||||
cm := collation2charset(col)
|
||||
if cm == nil {
|
||||
return string(s)
|
||||
}
|
||||
buf := make([]rune, 0, len(s))
|
||||
for i := 0; i < len(s); i++ {
|
||||
ch := cm.sb[s[i]]
|
||||
if ch == -1 {
|
||||
if i+1 == len(s) {
|
||||
ch = 0xfffd
|
||||
} else {
|
||||
n := int(s[i+1]) + (int(s[i]) << 8)
|
||||
i++
|
||||
var ok bool
|
||||
ch, ok = cm.db[n]
|
||||
if !ok {
|
||||
ch = 0xfffd
|
||||
}
|
||||
}
|
||||
}
|
||||
buf = append(buf, ch)
|
||||
}
|
||||
return string(buf)
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package cp
|
||||
|
||||
// http://msdn.microsoft.com/en-us/library/dd340437.aspx
|
||||
|
||||
type Collation struct {
|
||||
LcidAndFlags uint32
|
||||
SortId uint8
|
||||
}
|
||||
|
||||
func (c Collation) getLcid() uint32 {
|
||||
return c.LcidAndFlags & 0x000fffff
|
||||
}
|
||||
|
||||
func (c Collation) getFlags() uint32 {
|
||||
return (c.LcidAndFlags & 0x0ff00000) >> 20
|
||||
}
|
||||
|
||||
func (c Collation) getVersion() uint32 {
|
||||
return (c.LcidAndFlags & 0xf0000000) >> 28
|
||||
}
|
|
@ -0,0 +1,262 @@
|
|||
package cp
|
||||
|
||||
var cp1250 *charsetMap = &charsetMap{
|
||||
sb: [256]rune{
|
||||
0x0000, //NULL
|
||||
0x0001, //START OF HEADING
|
||||
0x0002, //START OF TEXT
|
||||
0x0003, //END OF TEXT
|
||||
0x0004, //END OF TRANSMISSION
|
||||
0x0005, //ENQUIRY
|
||||
0x0006, //ACKNOWLEDGE
|
||||
0x0007, //BELL
|
||||
0x0008, //BACKSPACE
|
||||
0x0009, //HORIZONTAL TABULATION
|
||||
0x000A, //LINE FEED
|
||||
0x000B, //VERTICAL TABULATION
|
||||
0x000C, //FORM FEED
|
||||
0x000D, //CARRIAGE RETURN
|
||||
0x000E, //SHIFT OUT
|
||||
0x000F, //SHIFT IN
|
||||
0x0010, //DATA LINK ESCAPE
|
||||
0x0011, //DEVICE CONTROL ONE
|
||||
0x0012, //DEVICE CONTROL TWO
|
||||
0x0013, //DEVICE CONTROL THREE
|
||||
0x0014, //DEVICE CONTROL FOUR
|
||||
0x0015, //NEGATIVE ACKNOWLEDGE
|
||||
0x0016, //SYNCHRONOUS IDLE
|
||||
0x0017, //END OF TRANSMISSION BLOCK
|
||||
0x0018, //CANCEL
|
||||
0x0019, //END OF MEDIUM
|
||||
0x001A, //SUBSTITUTE
|
||||
0x001B, //ESCAPE
|
||||
0x001C, //FILE SEPARATOR
|
||||
0x001D, //GROUP SEPARATOR
|
||||
0x001E, //RECORD SEPARATOR
|
||||
0x001F, //UNIT SEPARATOR
|
||||
0x0020, //SPACE
|
||||
0x0021, //EXCLAMATION MARK
|
||||
0x0022, //QUOTATION MARK
|
||||
0x0023, //NUMBER SIGN
|
||||
0x0024, //DOLLAR SIGN
|
||||
0x0025, //PERCENT SIGN
|
||||
0x0026, //AMPERSAND
|
||||
0x0027, //APOSTROPHE
|
||||
0x0028, //LEFT PARENTHESIS
|
||||
0x0029, //RIGHT PARENTHESIS
|
||||
0x002A, //ASTERISK
|
||||
0x002B, //PLUS SIGN
|
||||
0x002C, //COMMA
|
||||
0x002D, //HYPHEN-MINUS
|
||||
0x002E, //FULL STOP
|
||||
0x002F, //SOLIDUS
|
||||
0x0030, //DIGIT ZERO
|
||||
0x0031, //DIGIT ONE
|
||||
0x0032, //DIGIT TWO
|
||||
0x0033, //DIGIT THREE
|
||||
0x0034, //DIGIT FOUR
|
||||
0x0035, //DIGIT FIVE
|
||||
0x0036, //DIGIT SIX
|
||||
0x0037, //DIGIT SEVEN
|
||||
0x0038, //DIGIT EIGHT
|
||||
0x0039, //DIGIT NINE
|
||||
0x003A, //COLON
|
||||
0x003B, //SEMICOLON
|
||||
0x003C, //LESS-THAN SIGN
|
||||
0x003D, //EQUALS SIGN
|
||||
0x003E, //GREATER-THAN SIGN
|
||||
0x003F, //QUESTION MARK
|
||||
0x0040, //COMMERCIAL AT
|
||||
0x0041, //LATIN CAPITAL LETTER A
|
||||
0x0042, //LATIN CAPITAL LETTER B
|
||||
0x0043, //LATIN CAPITAL LETTER C
|
||||
0x0044, //LATIN CAPITAL LETTER D
|
||||
0x0045, //LATIN CAPITAL LETTER E
|
||||
0x0046, //LATIN CAPITAL LETTER F
|
||||
0x0047, //LATIN CAPITAL LETTER G
|
||||
0x0048, //LATIN CAPITAL LETTER H
|
||||
0x0049, //LATIN CAPITAL LETTER I
|
||||
0x004A, //LATIN CAPITAL LETTER J
|
||||
0x004B, //LATIN CAPITAL LETTER K
|
||||
0x004C, //LATIN CAPITAL LETTER L
|
||||
0x004D, //LATIN CAPITAL LETTER M
|
||||
0x004E, //LATIN CAPITAL LETTER N
|
||||
0x004F, //LATIN CAPITAL LETTER O
|
||||
0x0050, //LATIN CAPITAL LETTER P
|
||||
0x0051, //LATIN CAPITAL LETTER Q
|
||||
0x0052, //LATIN CAPITAL LETTER R
|
||||
0x0053, //LATIN CAPITAL LETTER S
|
||||
0x0054, //LATIN CAPITAL LETTER T
|
||||
0x0055, //LATIN CAPITAL LETTER U
|
||||
0x0056, //LATIN CAPITAL LETTER V
|
||||
0x0057, //LATIN CAPITAL LETTER W
|
||||
0x0058, //LATIN CAPITAL LETTER X
|
||||
0x0059, //LATIN CAPITAL LETTER Y
|
||||
0x005A, //LATIN CAPITAL LETTER Z
|
||||
0x005B, //LEFT SQUARE BRACKET
|
||||
0x005C, //REVERSE SOLIDUS
|
||||
0x005D, //RIGHT SQUARE BRACKET
|
||||
0x005E, //CIRCUMFLEX ACCENT
|
||||
0x005F, //LOW LINE
|
||||
0x0060, //GRAVE ACCENT
|
||||
0x0061, //LATIN SMALL LETTER A
|
||||
0x0062, //LATIN SMALL LETTER B
|
||||
0x0063, //LATIN SMALL LETTER C
|
||||
0x0064, //LATIN SMALL LETTER D
|
||||
0x0065, //LATIN SMALL LETTER E
|
||||
0x0066, //LATIN SMALL LETTER F
|
||||
0x0067, //LATIN SMALL LETTER G
|
||||
0x0068, //LATIN SMALL LETTER H
|
||||
0x0069, //LATIN SMALL LETTER I
|
||||
0x006A, //LATIN SMALL LETTER J
|
||||
0x006B, //LATIN SMALL LETTER K
|
||||
0x006C, //LATIN SMALL LETTER L
|
||||
0x006D, //LATIN SMALL LETTER M
|
||||
0x006E, //LATIN SMALL LETTER N
|
||||
0x006F, //LATIN SMALL LETTER O
|
||||
0x0070, //LATIN SMALL LETTER P
|
||||
0x0071, //LATIN SMALL LETTER Q
|
||||
0x0072, //LATIN SMALL LETTER R
|
||||
0x0073, //LATIN SMALL LETTER S
|
||||
0x0074, //LATIN SMALL LETTER T
|
||||
0x0075, //LATIN SMALL LETTER U
|
||||
0x0076, //LATIN SMALL LETTER V
|
||||
0x0077, //LATIN SMALL LETTER W
|
||||
0x0078, //LATIN SMALL LETTER X
|
||||
0x0079, //LATIN SMALL LETTER Y
|
||||
0x007A, //LATIN SMALL LETTER Z
|
||||
0x007B, //LEFT CURLY BRACKET
|
||||
0x007C, //VERTICAL LINE
|
||||
0x007D, //RIGHT CURLY BRACKET
|
||||
0x007E, //TILDE
|
||||
0x007F, //DELETE
|
||||
0x20AC, //EURO SIGN
|
||||
0xFFFD, //UNDEFINED
|
||||
0x201A, //SINGLE LOW-9 QUOTATION MARK
|
||||
0xFFFD, //UNDEFINED
|
||||
0x201E, //DOUBLE LOW-9 QUOTATION MARK
|
||||
0x2026, //HORIZONTAL ELLIPSIS
|
||||
0x2020, //DAGGER
|
||||
0x2021, //DOUBLE DAGGER
|
||||
0xFFFD, //UNDEFINED
|
||||
0x2030, //PER MILLE SIGN
|
||||
0x0160, //LATIN CAPITAL LETTER S WITH CARON
|
||||
0x2039, //SINGLE LEFT-POINTING ANGLE QUOTATION MARK
|
||||
0x015A, //LATIN CAPITAL LETTER S WITH ACUTE
|
||||
0x0164, //LATIN CAPITAL LETTER T WITH CARON
|
||||
0x017D, //LATIN CAPITAL LETTER Z WITH CARON
|
||||
0x0179, //LATIN CAPITAL LETTER Z WITH ACUTE
|
||||
0xFFFD, //UNDEFINED
|
||||
0x2018, //LEFT SINGLE QUOTATION MARK
|
||||
0x2019, //RIGHT SINGLE QUOTATION MARK
|
||||
0x201C, //LEFT DOUBLE QUOTATION MARK
|
||||
0x201D, //RIGHT DOUBLE QUOTATION MARK
|
||||
0x2022, //BULLET
|
||||
0x2013, //EN DASH
|
||||
0x2014, //EM DASH
|
||||
0xFFFD, //UNDEFINED
|
||||
0x2122, //TRADE MARK SIGN
|
||||
0x0161, //LATIN SMALL LETTER S WITH CARON
|
||||
0x203A, //SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
|
||||
0x015B, //LATIN SMALL LETTER S WITH ACUTE
|
||||
0x0165, //LATIN SMALL LETTER T WITH CARON
|
||||
0x017E, //LATIN SMALL LETTER Z WITH CARON
|
||||
0x017A, //LATIN SMALL LETTER Z WITH ACUTE
|
||||
0x00A0, //NO-BREAK SPACE
|
||||
0x02C7, //CARON
|
||||
0x02D8, //BREVE
|
||||
0x0141, //LATIN CAPITAL LETTER L WITH STROKE
|
||||
0x00A4, //CURRENCY SIGN
|
||||
0x0104, //LATIN CAPITAL LETTER A WITH OGONEK
|
||||
0x00A6, //BROKEN BAR
|
||||
0x00A7, //SECTION SIGN
|
||||
0x00A8, //DIAERESIS
|
||||
0x00A9, //COPYRIGHT SIGN
|
||||
0x015E, //LATIN CAPITAL LETTER S WITH CEDILLA
|
||||
0x00AB, //LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
|
||||
0x00AC, //NOT SIGN
|
||||
0x00AD, //SOFT HYPHEN
|
||||
0x00AE, //REGISTERED SIGN
|
||||
0x017B, //LATIN CAPITAL LETTER Z WITH DOT ABOVE
|
||||
0x00B0, //DEGREE SIGN
|
||||
0x00B1, //PLUS-MINUS SIGN
|
||||
0x02DB, //OGONEK
|
||||
0x0142, //LATIN SMALL LETTER L WITH STROKE
|
||||
0x00B4, //ACUTE ACCENT
|
||||
0x00B5, //MICRO SIGN
|
||||
0x00B6, //PILCROW SIGN
|
||||
0x00B7, //MIDDLE DOT
|
||||
0x00B8, //CEDILLA
|
||||
0x0105, //LATIN SMALL LETTER A WITH OGONEK
|
||||
0x015F, //LATIN SMALL LETTER S WITH CEDILLA
|
||||
0x00BB, //RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
|
||||
0x013D, //LATIN CAPITAL LETTER L WITH CARON
|
||||
0x02DD, //DOUBLE ACUTE ACCENT
|
||||
0x013E, //LATIN SMALL LETTER L WITH CARON
|
||||
0x017C, //LATIN SMALL LETTER Z WITH DOT ABOVE
|
||||
0x0154, //LATIN CAPITAL LETTER R WITH ACUTE
|
||||
0x00C1, //LATIN CAPITAL LETTER A WITH ACUTE
|
||||
0x00C2, //LATIN CAPITAL LETTER A WITH CIRCUMFLEX
|
||||
0x0102, //LATIN CAPITAL LETTER A WITH BREVE
|
||||
0x00C4, //LATIN CAPITAL LETTER A WITH DIAERESIS
|
||||
0x0139, //LATIN CAPITAL LETTER L WITH ACUTE
|
||||
0x0106, //LATIN CAPITAL LETTER C WITH ACUTE
|
||||
0x00C7, //LATIN CAPITAL LETTER C WITH CEDILLA
|
||||
0x010C, //LATIN CAPITAL LETTER C WITH CARON
|
||||
0x00C9, //LATIN CAPITAL LETTER E WITH ACUTE
|
||||
0x0118, //LATIN CAPITAL LETTER E WITH OGONEK
|
||||
0x00CB, //LATIN CAPITAL LETTER E WITH DIAERESIS
|
||||
0x011A, //LATIN CAPITAL LETTER E WITH CARON
|
||||
0x00CD, //LATIN CAPITAL LETTER I WITH ACUTE
|
||||
0x00CE, //LATIN CAPITAL LETTER I WITH CIRCUMFLEX
|
||||
0x010E, //LATIN CAPITAL LETTER D WITH CARON
|
||||
0x0110, //LATIN CAPITAL LETTER D WITH STROKE
|
||||
0x0143, //LATIN CAPITAL LETTER N WITH ACUTE
|
||||
0x0147, //LATIN CAPITAL LETTER N WITH CARON
|
||||
0x00D3, //LATIN CAPITAL LETTER O WITH ACUTE
|
||||
0x00D4, //LATIN CAPITAL LETTER O WITH CIRCUMFLEX
|
||||
0x0150, //LATIN CAPITAL LETTER O WITH DOUBLE ACUTE
|
||||
0x00D6, //LATIN CAPITAL LETTER O WITH DIAERESIS
|
||||
0x00D7, //MULTIPLICATION SIGN
|
||||
0x0158, //LATIN CAPITAL LETTER R WITH CARON
|
||||
0x016E, //LATIN CAPITAL LETTER U WITH RING ABOVE
|
||||
0x00DA, //LATIN CAPITAL LETTER U WITH ACUTE
|
||||
0x0170, //LATIN CAPITAL LETTER U WITH DOUBLE ACUTE
|
||||
0x00DC, //LATIN CAPITAL LETTER U WITH DIAERESIS
|
||||
0x00DD, //LATIN CAPITAL LETTER Y WITH ACUTE
|
||||
0x0162, //LATIN CAPITAL LETTER T WITH CEDILLA
|
||||
0x00DF, //LATIN SMALL LETTER SHARP S
|
||||
0x0155, //LATIN SMALL LETTER R WITH ACUTE
|
||||
0x00E1, //LATIN SMALL LETTER A WITH ACUTE
|
||||
0x00E2, //LATIN SMALL LETTER A WITH CIRCUMFLEX
|
||||
0x0103, //LATIN SMALL LETTER A WITH BREVE
|
||||
0x00E4, //LATIN SMALL LETTER A WITH DIAERESIS
|
||||
0x013A, //LATIN SMALL LETTER L WITH ACUTE
|
||||
0x0107, //LATIN SMALL LETTER C WITH ACUTE
|
||||
0x00E7, //LATIN SMALL LETTER C WITH CEDILLA
|
||||
0x010D, //LATIN SMALL LETTER C WITH CARON
|
||||
0x00E9, //LATIN SMALL LETTER E WITH ACUTE
|
||||
0x0119, //LATIN SMALL LETTER E WITH OGONEK
|
||||
0x00EB, //LATIN SMALL LETTER E WITH DIAERESIS
|
||||
0x011B, //LATIN SMALL LETTER E WITH CARON
|
||||
0x00ED, //LATIN SMALL LETTER I WITH ACUTE
|
||||
0x00EE, //LATIN SMALL LETTER I WITH CIRCUMFLEX
|
||||
0x010F, //LATIN SMALL LETTER D WITH CARON
|
||||
0x0111, //LATIN SMALL LETTER D WITH STROKE
|
||||
0x0144, //LATIN SMALL LETTER N WITH ACUTE
|
||||
0x0148, //LATIN SMALL LETTER N WITH CARON
|
||||
0x00F3, //LATIN SMALL LETTER O WITH ACUTE
|
||||
0x00F4, //LATIN SMALL LETTER O WITH CIRCUMFLEX
|
||||
0x0151, //LATIN SMALL LETTER O WITH DOUBLE ACUTE
|
||||
0x00F6, //LATIN SMALL LETTER O WITH DIAERESIS
|
||||
0x00F7, //DIVISION SIGN
|
||||
0x0159, //LATIN SMALL LETTER R WITH CARON
|
||||
0x016F, //LATIN SMALL LETTER U WITH RING ABOVE
|
||||
0x00FA, //LATIN SMALL LETTER U WITH ACUTE
|
||||
0x0171, //LATIN SMALL LETTER U WITH DOUBLE ACUTE
|
||||
0x00FC, //LATIN SMALL LETTER U WITH DIAERESIS
|
||||
0x00FD, //LATIN SMALL LETTER Y WITH ACUTE
|
||||
0x0163, //LATIN SMALL LETTER T WITH CEDILLA
|
||||
0x02D9, //DOT ABOVE
|
||||
},
|
||||
}
|
|
@ -0,0 +1,262 @@
|
|||
package cp
|
||||
|
||||
var cp1251 *charsetMap = &charsetMap{
|
||||
sb: [256]rune{
|
||||
0x0000, //NULL
|
||||
0x0001, //START OF HEADING
|
||||
0x0002, //START OF TEXT
|
||||
0x0003, //END OF TEXT
|
||||
0x0004, //END OF TRANSMISSION
|
||||
0x0005, //ENQUIRY
|
||||
0x0006, //ACKNOWLEDGE
|
||||
0x0007, //BELL
|
||||
0x0008, //BACKSPACE
|
||||
0x0009, //HORIZONTAL TABULATION
|
||||
0x000A, //LINE FEED
|
||||
0x000B, //VERTICAL TABULATION
|
||||
0x000C, //FORM FEED
|
||||
0x000D, //CARRIAGE RETURN
|
||||
0x000E, //SHIFT OUT
|
||||
0x000F, //SHIFT IN
|
||||
0x0010, //DATA LINK ESCAPE
|
||||
0x0011, //DEVICE CONTROL ONE
|
||||
0x0012, //DEVICE CONTROL TWO
|
||||
0x0013, //DEVICE CONTROL THREE
|
||||
0x0014, //DEVICE CONTROL FOUR
|
||||
0x0015, //NEGATIVE ACKNOWLEDGE
|
||||
0x0016, //SYNCHRONOUS IDLE
|
||||
0x0017, //END OF TRANSMISSION BLOCK
|
||||
0x0018, //CANCEL
|
||||
0x0019, //END OF MEDIUM
|
||||
0x001A, //SUBSTITUTE
|
||||
0x001B, //ESCAPE
|
||||
0x001C, //FILE SEPARATOR
|
||||
0x001D, //GROUP SEPARATOR
|
||||
0x001E, //RECORD SEPARATOR
|
||||
0x001F, //UNIT SEPARATOR
|
||||
0x0020, //SPACE
|
||||
0x0021, //EXCLAMATION MARK
|
||||
0x0022, //QUOTATION MARK
|
||||
0x0023, //NUMBER SIGN
|
||||
0x0024, //DOLLAR SIGN
|
||||
0x0025, //PERCENT SIGN
|
||||
0x0026, //AMPERSAND
|
||||
0x0027, //APOSTROPHE
|
||||
0x0028, //LEFT PARENTHESIS
|
||||
0x0029, //RIGHT PARENTHESIS
|
||||
0x002A, //ASTERISK
|
||||
0x002B, //PLUS SIGN
|
||||
0x002C, //COMMA
|
||||
0x002D, //HYPHEN-MINUS
|
||||
0x002E, //FULL STOP
|
||||
0x002F, //SOLIDUS
|
||||
0x0030, //DIGIT ZERO
|
||||
0x0031, //DIGIT ONE
|
||||
0x0032, //DIGIT TWO
|
||||
0x0033, //DIGIT THREE
|
||||
0x0034, //DIGIT FOUR
|
||||
0x0035, //DIGIT FIVE
|
||||
0x0036, //DIGIT SIX
|
||||
0x0037, //DIGIT SEVEN
|
||||
0x0038, //DIGIT EIGHT
|
||||
0x0039, //DIGIT NINE
|
||||
0x003A, //COLON
|
||||
0x003B, //SEMICOLON
|
||||
0x003C, //LESS-THAN SIGN
|
||||
0x003D, //EQUALS SIGN
|
||||
0x003E, //GREATER-THAN SIGN
|
||||
0x003F, //QUESTION MARK
|
||||
0x0040, //COMMERCIAL AT
|
||||
0x0041, //LATIN CAPITAL LETTER A
|
||||
0x0042, //LATIN CAPITAL LETTER B
|
||||
0x0043, //LATIN CAPITAL LETTER C
|
||||
0x0044, //LATIN CAPITAL LETTER D
|
||||
0x0045, //LATIN CAPITAL LETTER E
|
||||
0x0046, //LATIN CAPITAL LETTER F
|
||||
0x0047, //LATIN CAPITAL LETTER G
|
||||
0x0048, //LATIN CAPITAL LETTER H
|
||||
0x0049, //LATIN CAPITAL LETTER I
|
||||
0x004A, //LATIN CAPITAL LETTER J
|
||||
0x004B, //LATIN CAPITAL LETTER K
|
||||
0x004C, //LATIN CAPITAL LETTER L
|
||||
0x004D, //LATIN CAPITAL LETTER M
|
||||
0x004E, //LATIN CAPITAL LETTER N
|
||||
0x004F, //LATIN CAPITAL LETTER O
|
||||
0x0050, //LATIN CAPITAL LETTER P
|
||||
0x0051, //LATIN CAPITAL LETTER Q
|
||||
0x0052, //LATIN CAPITAL LETTER R
|
||||
0x0053, //LATIN CAPITAL LETTER S
|
||||
0x0054, //LATIN CAPITAL LETTER T
|
||||
0x0055, //LATIN CAPITAL LETTER U
|
||||
0x0056, //LATIN CAPITAL LETTER V
|
||||
0x0057, //LATIN CAPITAL LETTER W
|
||||
0x0058, //LATIN CAPITAL LETTER X
|
||||
0x0059, //LATIN CAPITAL LETTER Y
|
||||
0x005A, //LATIN CAPITAL LETTER Z
|
||||
0x005B, //LEFT SQUARE BRACKET
|
||||
0x005C, //REVERSE SOLIDUS
|
||||
0x005D, //RIGHT SQUARE BRACKET
|
||||
0x005E, //CIRCUMFLEX ACCENT
|
||||
0x005F, //LOW LINE
|
||||
0x0060, //GRAVE ACCENT
|
||||
0x0061, //LATIN SMALL LETTER A
|
||||
0x0062, //LATIN SMALL LETTER B
|
||||
0x0063, //LATIN SMALL LETTER C
|
||||
0x0064, //LATIN SMALL LETTER D
|
||||
0x0065, //LATIN SMALL LETTER E
|
||||
0x0066, //LATIN SMALL LETTER F
|
||||
0x0067, //LATIN SMALL LETTER G
|
||||
0x0068, //LATIN SMALL LETTER H
|
||||
0x0069, //LATIN SMALL LETTER I
|
||||
0x006A, //LATIN SMALL LETTER J
|
||||
0x006B, //LATIN SMALL LETTER K
|
||||
0x006C, //LATIN SMALL LETTER L
|
||||
0x006D, //LATIN SMALL LETTER M
|
||||
0x006E, //LATIN SMALL LETTER N
|
||||
0x006F, //LATIN SMALL LETTER O
|
||||
0x0070, //LATIN SMALL LETTER P
|
||||
0x0071, //LATIN SMALL LETTER Q
|
||||
0x0072, //LATIN SMALL LETTER R
|
||||
0x0073, //LATIN SMALL LETTER S
|
||||
0x0074, //LATIN SMALL LETTER T
|
||||
0x0075, //LATIN SMALL LETTER U
|
||||
0x0076, //LATIN SMALL LETTER V
|
||||
0x0077, //LATIN SMALL LETTER W
|
||||
0x0078, //LATIN SMALL LETTER X
|
||||
0x0079, //LATIN SMALL LETTER Y
|
||||
0x007A, //LATIN SMALL LETTER Z
|
||||
0x007B, //LEFT CURLY BRACKET
|
||||
0x007C, //VERTICAL LINE
|
||||
0x007D, //RIGHT CURLY BRACKET
|
||||
0x007E, //TILDE
|
||||
0x007F, //DELETE
|
||||
0x0402, //CYRILLIC CAPITAL LETTER DJE
|
||||
0x0403, //CYRILLIC CAPITAL LETTER GJE
|
||||
0x201A, //SINGLE LOW-9 QUOTATION MARK
|
||||
0x0453, //CYRILLIC SMALL LETTER GJE
|
||||
0x201E, //DOUBLE LOW-9 QUOTATION MARK
|
||||
0x2026, //HORIZONTAL ELLIPSIS
|
||||
0x2020, //DAGGER
|
||||
0x2021, //DOUBLE DAGGER
|
||||
0x20AC, //EURO SIGN
|
||||
0x2030, //PER MILLE SIGN
|
||||
0x0409, //CYRILLIC CAPITAL LETTER LJE
|
||||
0x2039, //SINGLE LEFT-POINTING ANGLE QUOTATION MARK
|
||||
0x040A, //CYRILLIC CAPITAL LETTER NJE
|
||||
0x040C, //CYRILLIC CAPITAL LETTER KJE
|
||||
0x040B, //CYRILLIC CAPITAL LETTER TSHE
|
||||
0x040F, //CYRILLIC CAPITAL LETTER DZHE
|
||||
0x0452, //CYRILLIC SMALL LETTER DJE
|
||||
0x2018, //LEFT SINGLE QUOTATION MARK
|
||||
0x2019, //RIGHT SINGLE QUOTATION MARK
|
||||
0x201C, //LEFT DOUBLE QUOTATION MARK
|
||||
0x201D, //RIGHT DOUBLE QUOTATION MARK
|
||||
0x2022, //BULLET
|
||||
0x2013, //EN DASH
|
||||
0x2014, //EM DASH
|
||||
0xFFFD, //UNDEFINED
|
||||
0x2122, //TRADE MARK SIGN
|
||||
0x0459, //CYRILLIC SMALL LETTER LJE
|
||||
0x203A, //SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
|
||||
0x045A, //CYRILLIC SMALL LETTER NJE
|
||||
0x045C, //CYRILLIC SMALL LETTER KJE
|
||||
0x045B, //CYRILLIC SMALL LETTER TSHE
|
||||
0x045F, //CYRILLIC SMALL LETTER DZHE
|
||||
0x00A0, //NO-BREAK SPACE
|
||||
0x040E, //CYRILLIC CAPITAL LETTER SHORT U
|
||||
0x045E, //CYRILLIC SMALL LETTER SHORT U
|
||||
0x0408, //CYRILLIC CAPITAL LETTER JE
|
||||
0x00A4, //CURRENCY SIGN
|
||||
0x0490, //CYRILLIC CAPITAL LETTER GHE WITH UPTURN
|
||||
0x00A6, //BROKEN BAR
|
||||
0x00A7, //SECTION SIGN
|
||||
0x0401, //CYRILLIC CAPITAL LETTER IO
|
||||
0x00A9, //COPYRIGHT SIGN
|
||||
0x0404, //CYRILLIC CAPITAL LETTER UKRAINIAN IE
|
||||
0x00AB, //LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
|
||||
0x00AC, //NOT SIGN
|
||||
0x00AD, //SOFT HYPHEN
|
||||
0x00AE, //REGISTERED SIGN
|
||||
0x0407, //CYRILLIC CAPITAL LETTER YI
|
||||
0x00B0, //DEGREE SIGN
|
||||
0x00B1, //PLUS-MINUS SIGN
|
||||
0x0406, //CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I
|
||||
0x0456, //CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I
|
||||
0x0491, //CYRILLIC SMALL LETTER GHE WITH UPTURN
|
||||
0x00B5, //MICRO SIGN
|
||||
0x00B6, //PILCROW SIGN
|
||||
0x00B7, //MIDDLE DOT
|
||||
0x0451, //CYRILLIC SMALL LETTER IO
|
||||
0x2116, //NUMERO SIGN
|
||||
0x0454, //CYRILLIC SMALL LETTER UKRAINIAN IE
|
||||
0x00BB, //RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
|
||||
0x0458, //CYRILLIC SMALL LETTER JE
|
||||
0x0405, //CYRILLIC CAPITAL LETTER DZE
|
||||
0x0455, //CYRILLIC SMALL LETTER DZE
|
||||
0x0457, //CYRILLIC SMALL LETTER YI
|
||||
0x0410, //CYRILLIC CAPITAL LETTER A
|
||||
0x0411, //CYRILLIC CAPITAL LETTER BE
|
||||
0x0412, //CYRILLIC CAPITAL LETTER VE
|
||||
0x0413, //CYRILLIC CAPITAL LETTER GHE
|
||||
0x0414, //CYRILLIC CAPITAL LETTER DE
|
||||
0x0415, //CYRILLIC CAPITAL LETTER IE
|
||||
0x0416, //CYRILLIC CAPITAL LETTER ZHE
|
||||
0x0417, //CYRILLIC CAPITAL LETTER ZE
|
||||
0x0418, //CYRILLIC CAPITAL LETTER I
|
||||
0x0419, //CYRILLIC CAPITAL LETTER SHORT I
|
||||
0x041A, //CYRILLIC CAPITAL LETTER KA
|
||||
0x041B, //CYRILLIC CAPITAL LETTER EL
|
||||
0x041C, //CYRILLIC CAPITAL LETTER EM
|
||||
0x041D, //CYRILLIC CAPITAL LETTER EN
|
||||
0x041E, //CYRILLIC CAPITAL LETTER O
|
||||
0x041F, //CYRILLIC CAPITAL LETTER PE
|
||||
0x0420, //CYRILLIC CAPITAL LETTER ER
|
||||
0x0421, //CYRILLIC CAPITAL LETTER ES
|
||||
0x0422, //CYRILLIC CAPITAL LETTER TE
|
||||
0x0423, //CYRILLIC CAPITAL LETTER U
|
||||
0x0424, //CYRILLIC CAPITAL LETTER EF
|
||||
0x0425, //CYRILLIC CAPITAL LETTER HA
|
||||
0x0426, //CYRILLIC CAPITAL LETTER TSE
|
||||
0x0427, //CYRILLIC CAPITAL LETTER CHE
|
||||
0x0428, //CYRILLIC CAPITAL LETTER SHA
|
||||
0x0429, //CYRILLIC CAPITAL LETTER SHCHA
|
||||
0x042A, //CYRILLIC CAPITAL LETTER HARD SIGN
|
||||
0x042B, //CYRILLIC CAPITAL LETTER YERU
|
||||
0x042C, //CYRILLIC CAPITAL LETTER SOFT SIGN
|
||||
0x042D, //CYRILLIC CAPITAL LETTER E
|
||||
0x042E, //CYRILLIC CAPITAL LETTER YU
|
||||
0x042F, //CYRILLIC CAPITAL LETTER YA
|
||||
0x0430, //CYRILLIC SMALL LETTER A
|
||||
0x0431, //CYRILLIC SMALL LETTER BE
|
||||
0x0432, //CYRILLIC SMALL LETTER VE
|
||||
0x0433, //CYRILLIC SMALL LETTER GHE
|
||||
0x0434, //CYRILLIC SMALL LETTER DE
|
||||
0x0435, //CYRILLIC SMALL LETTER IE
|
||||
0x0436, //CYRILLIC SMALL LETTER ZHE
|
||||
0x0437, //CYRILLIC SMALL LETTER ZE
|
||||
0x0438, //CYRILLIC SMALL LETTER I
|
||||
0x0439, //CYRILLIC SMALL LETTER SHORT I
|
||||
0x043A, //CYRILLIC SMALL LETTER KA
|
||||
0x043B, //CYRILLIC SMALL LETTER EL
|
||||
0x043C, //CYRILLIC SMALL LETTER EM
|
||||
0x043D, //CYRILLIC SMALL LETTER EN
|
||||
0x043E, //CYRILLIC SMALL LETTER O
|
||||
0x043F, //CYRILLIC SMALL LETTER PE
|
||||
0x0440, //CYRILLIC SMALL LETTER ER
|
||||
0x0441, //CYRILLIC SMALL LETTER ES
|
||||
0x0442, //CYRILLIC SMALL LETTER TE
|
||||
0x0443, //CYRILLIC SMALL LETTER U
|
||||
0x0444, //CYRILLIC SMALL LETTER EF
|
||||
0x0445, //CYRILLIC SMALL LETTER HA
|
||||
0x0446, //CYRILLIC SMALL LETTER TSE
|
||||
0x0447, //CYRILLIC SMALL LETTER CHE
|
||||
0x0448, //CYRILLIC SMALL LETTER SHA
|
||||
0x0449, //CYRILLIC SMALL LETTER SHCHA
|
||||
0x044A, //CYRILLIC SMALL LETTER HARD SIGN
|
||||
0x044B, //CYRILLIC SMALL LETTER YERU
|
||||
0x044C, //CYRILLIC SMALL LETTER SOFT SIGN
|
||||
0x044D, //CYRILLIC SMALL LETTER E
|
||||
0x044E, //CYRILLIC SMALL LETTER YU
|
||||
0x044F, //CYRILLIC SMALL LETTER YA
|
||||
},
|
||||
}
|
|
@ -0,0 +1,262 @@
|
|||
package cp
|
||||
|
||||
var cp1252 *charsetMap = &charsetMap{
|
||||
sb: [256]rune{
|
||||
0x0000, //NULL
|
||||
0x0001, //START OF HEADING
|
||||
0x0002, //START OF TEXT
|
||||
0x0003, //END OF TEXT
|
||||
0x0004, //END OF TRANSMISSION
|
||||
0x0005, //ENQUIRY
|
||||
0x0006, //ACKNOWLEDGE
|
||||
0x0007, //BELL
|
||||
0x0008, //BACKSPACE
|
||||
0x0009, //HORIZONTAL TABULATION
|
||||
0x000A, //LINE FEED
|
||||
0x000B, //VERTICAL TABULATION
|
||||
0x000C, //FORM FEED
|
||||
0x000D, //CARRIAGE RETURN
|
||||
0x000E, //SHIFT OUT
|
||||
0x000F, //SHIFT IN
|
||||
0x0010, //DATA LINK ESCAPE
|
||||
0x0011, //DEVICE CONTROL ONE
|
||||
0x0012, //DEVICE CONTROL TWO
|
||||
0x0013, //DEVICE CONTROL THREE
|
||||
0x0014, //DEVICE CONTROL FOUR
|
||||
0x0015, //NEGATIVE ACKNOWLEDGE
|
||||
0x0016, //SYNCHRONOUS IDLE
|
||||
0x0017, //END OF TRANSMISSION BLOCK
|
||||
0x0018, //CANCEL
|
||||
0x0019, //END OF MEDIUM
|
||||
0x001A, //SUBSTITUTE
|
||||
0x001B, //ESCAPE
|
||||
0x001C, //FILE SEPARATOR
|
||||
0x001D, //GROUP SEPARATOR
|
||||
0x001E, //RECORD SEPARATOR
|
||||
0x001F, //UNIT SEPARATOR
|
||||
0x0020, //SPACE
|
||||
0x0021, //EXCLAMATION MARK
|
||||
0x0022, //QUOTATION MARK
|
||||
0x0023, //NUMBER SIGN
|
||||
0x0024, //DOLLAR SIGN
|
||||
0x0025, //PERCENT SIGN
|
||||
0x0026, //AMPERSAND
|
||||
0x0027, //APOSTROPHE
|
||||
0x0028, //LEFT PARENTHESIS
|
||||
0x0029, //RIGHT PARENTHESIS
|
||||
0x002A, //ASTERISK
|
||||
0x002B, //PLUS SIGN
|
||||
0x002C, //COMMA
|
||||
0x002D, //HYPHEN-MINUS
|
||||
0x002E, //FULL STOP
|
||||
0x002F, //SOLIDUS
|
||||
0x0030, //DIGIT ZERO
|
||||
0x0031, //DIGIT ONE
|
||||
0x0032, //DIGIT TWO
|
||||
0x0033, //DIGIT THREE
|
||||
0x0034, //DIGIT FOUR
|
||||
0x0035, //DIGIT FIVE
|
||||
0x0036, //DIGIT SIX
|
||||
0x0037, //DIGIT SEVEN
|
||||
0x0038, //DIGIT EIGHT
|
||||
0x0039, //DIGIT NINE
|
||||
0x003A, //COLON
|
||||
0x003B, //SEMICOLON
|
||||
0x003C, //LESS-THAN SIGN
|
||||
0x003D, //EQUALS SIGN
|
||||
0x003E, //GREATER-THAN SIGN
|
||||
0x003F, //QUESTION MARK
|
||||
0x0040, //COMMERCIAL AT
|
||||
0x0041, //LATIN CAPITAL LETTER A
|
||||
0x0042, //LATIN CAPITAL LETTER B
|
||||
0x0043, //LATIN CAPITAL LETTER C
|
||||
0x0044, //LATIN CAPITAL LETTER D
|
||||
0x0045, //LATIN CAPITAL LETTER E
|
||||
0x0046, //LATIN CAPITAL LETTER F
|
||||
0x0047, //LATIN CAPITAL LETTER G
|
||||
0x0048, //LATIN CAPITAL LETTER H
|
||||
0x0049, //LATIN CAPITAL LETTER I
|
||||
0x004A, //LATIN CAPITAL LETTER J
|
||||
0x004B, //LATIN CAPITAL LETTER K
|
||||
0x004C, //LATIN CAPITAL LETTER L
|
||||
0x004D, //LATIN CAPITAL LETTER M
|
||||
0x004E, //LATIN CAPITAL LETTER N
|
||||
0x004F, //LATIN CAPITAL LETTER O
|
||||
0x0050, //LATIN CAPITAL LETTER P
|
||||
0x0051, //LATIN CAPITAL LETTER Q
|
||||
0x0052, //LATIN CAPITAL LETTER R
|
||||
0x0053, //LATIN CAPITAL LETTER S
|
||||
0x0054, //LATIN CAPITAL LETTER T
|
||||
0x0055, //LATIN CAPITAL LETTER U
|
||||
0x0056, //LATIN CAPITAL LETTER V
|
||||
0x0057, //LATIN CAPITAL LETTER W
|
||||
0x0058, //LATIN CAPITAL LETTER X
|
||||
0x0059, //LATIN CAPITAL LETTER Y
|
||||
0x005A, //LATIN CAPITAL LETTER Z
|
||||
0x005B, //LEFT SQUARE BRACKET
|
||||
0x005C, //REVERSE SOLIDUS
|
||||
0x005D, //RIGHT SQUARE BRACKET
|
||||
0x005E, //CIRCUMFLEX ACCENT
|
||||
0x005F, //LOW LINE
|
||||
0x0060, //GRAVE ACCENT
|
||||
0x0061, //LATIN SMALL LETTER A
|
||||
0x0062, //LATIN SMALL LETTER B
|
||||
0x0063, //LATIN SMALL LETTER C
|
||||
0x0064, //LATIN SMALL LETTER D
|
||||
0x0065, //LATIN SMALL LETTER E
|
||||
0x0066, //LATIN SMALL LETTER F
|
||||
0x0067, //LATIN SMALL LETTER G
|
||||
0x0068, //LATIN SMALL LETTER H
|
||||
0x0069, //LATIN SMALL LETTER I
|
||||
0x006A, //LATIN SMALL LETTER J
|
||||
0x006B, //LATIN SMALL LETTER K
|
||||
0x006C, //LATIN SMALL LETTER L
|
||||
0x006D, //LATIN SMALL LETTER M
|
||||
0x006E, //LATIN SMALL LETTER N
|
||||
0x006F, //LATIN SMALL LETTER O
|
||||
0x0070, //LATIN SMALL LETTER P
|
||||
0x0071, //LATIN SMALL LETTER Q
|
||||
0x0072, //LATIN SMALL LETTER R
|
||||
0x0073, //LATIN SMALL LETTER S
|
||||
0x0074, //LATIN SMALL LETTER T
|
||||
0x0075, //LATIN SMALL LETTER U
|
||||
0x0076, //LATIN SMALL LETTER V
|
||||
0x0077, //LATIN SMALL LETTER W
|
||||
0x0078, //LATIN SMALL LETTER X
|
||||
0x0079, //LATIN SMALL LETTER Y
|
||||
0x007A, //LATIN SMALL LETTER Z
|
||||
0x007B, //LEFT CURLY BRACKET
|
||||
0x007C, //VERTICAL LINE
|
||||
0x007D, //RIGHT CURLY BRACKET
|
||||
0x007E, //TILDE
|
||||
0x007F, //DELETE
|
||||
0x20AC, //EURO SIGN
|
||||
0xFFFD, //UNDEFINED
|
||||
0x201A, //SINGLE LOW-9 QUOTATION MARK
|
||||
0x0192, //LATIN SMALL LETTER F WITH HOOK
|
||||
0x201E, //DOUBLE LOW-9 QUOTATION MARK
|
||||
0x2026, //HORIZONTAL ELLIPSIS
|
||||
0x2020, //DAGGER
|
||||
0x2021, //DOUBLE DAGGER
|
||||
0x02C6, //MODIFIER LETTER CIRCUMFLEX ACCENT
|
||||
0x2030, //PER MILLE SIGN
|
||||
0x0160, //LATIN CAPITAL LETTER S WITH CARON
|
||||
0x2039, //SINGLE LEFT-POINTING ANGLE QUOTATION MARK
|
||||
0x0152, //LATIN CAPITAL LIGATURE OE
|
||||
0xFFFD, //UNDEFINED
|
||||
0x017D, //LATIN CAPITAL LETTER Z WITH CARON
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0x2018, //LEFT SINGLE QUOTATION MARK
|
||||
0x2019, //RIGHT SINGLE QUOTATION MARK
|
||||
0x201C, //LEFT DOUBLE QUOTATION MARK
|
||||
0x201D, //RIGHT DOUBLE QUOTATION MARK
|
||||
0x2022, //BULLET
|
||||
0x2013, //EN DASH
|
||||
0x2014, //EM DASH
|
||||
0x02DC, //SMALL TILDE
|
||||
0x2122, //TRADE MARK SIGN
|
||||
0x0161, //LATIN SMALL LETTER S WITH CARON
|
||||
0x203A, //SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
|
||||
0x0153, //LATIN SMALL LIGATURE OE
|
||||
0xFFFD, //UNDEFINED
|
||||
0x017E, //LATIN SMALL LETTER Z WITH CARON
|
||||
0x0178, //LATIN CAPITAL LETTER Y WITH DIAERESIS
|
||||
0x00A0, //NO-BREAK SPACE
|
||||
0x00A1, //INVERTED EXCLAMATION MARK
|
||||
0x00A2, //CENT SIGN
|
||||
0x00A3, //POUND SIGN
|
||||
0x00A4, //CURRENCY SIGN
|
||||
0x00A5, //YEN SIGN
|
||||
0x00A6, //BROKEN BAR
|
||||
0x00A7, //SECTION SIGN
|
||||
0x00A8, //DIAERESIS
|
||||
0x00A9, //COPYRIGHT SIGN
|
||||
0x00AA, //FEMININE ORDINAL INDICATOR
|
||||
0x00AB, //LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
|
||||
0x00AC, //NOT SIGN
|
||||
0x00AD, //SOFT HYPHEN
|
||||
0x00AE, //REGISTERED SIGN
|
||||
0x00AF, //MACRON
|
||||
0x00B0, //DEGREE SIGN
|
||||
0x00B1, //PLUS-MINUS SIGN
|
||||
0x00B2, //SUPERSCRIPT TWO
|
||||
0x00B3, //SUPERSCRIPT THREE
|
||||
0x00B4, //ACUTE ACCENT
|
||||
0x00B5, //MICRO SIGN
|
||||
0x00B6, //PILCROW SIGN
|
||||
0x00B7, //MIDDLE DOT
|
||||
0x00B8, //CEDILLA
|
||||
0x00B9, //SUPERSCRIPT ONE
|
||||
0x00BA, //MASCULINE ORDINAL INDICATOR
|
||||
0x00BB, //RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
|
||||
0x00BC, //VULGAR FRACTION ONE QUARTER
|
||||
0x00BD, //VULGAR FRACTION ONE HALF
|
||||
0x00BE, //VULGAR FRACTION THREE QUARTERS
|
||||
0x00BF, //INVERTED QUESTION MARK
|
||||
0x00C0, //LATIN CAPITAL LETTER A WITH GRAVE
|
||||
0x00C1, //LATIN CAPITAL LETTER A WITH ACUTE
|
||||
0x00C2, //LATIN CAPITAL LETTER A WITH CIRCUMFLEX
|
||||
0x00C3, //LATIN CAPITAL LETTER A WITH TILDE
|
||||
0x00C4, //LATIN CAPITAL LETTER A WITH DIAERESIS
|
||||
0x00C5, //LATIN CAPITAL LETTER A WITH RING ABOVE
|
||||
0x00C6, //LATIN CAPITAL LETTER AE
|
||||
0x00C7, //LATIN CAPITAL LETTER C WITH CEDILLA
|
||||
0x00C8, //LATIN CAPITAL LETTER E WITH GRAVE
|
||||
0x00C9, //LATIN CAPITAL LETTER E WITH ACUTE
|
||||
0x00CA, //LATIN CAPITAL LETTER E WITH CIRCUMFLEX
|
||||
0x00CB, //LATIN CAPITAL LETTER E WITH DIAERESIS
|
||||
0x00CC, //LATIN CAPITAL LETTER I WITH GRAVE
|
||||
0x00CD, //LATIN CAPITAL LETTER I WITH ACUTE
|
||||
0x00CE, //LATIN CAPITAL LETTER I WITH CIRCUMFLEX
|
||||
0x00CF, //LATIN CAPITAL LETTER I WITH DIAERESIS
|
||||
0x00D0, //LATIN CAPITAL LETTER ETH
|
||||
0x00D1, //LATIN CAPITAL LETTER N WITH TILDE
|
||||
0x00D2, //LATIN CAPITAL LETTER O WITH GRAVE
|
||||
0x00D3, //LATIN CAPITAL LETTER O WITH ACUTE
|
||||
0x00D4, //LATIN CAPITAL LETTER O WITH CIRCUMFLEX
|
||||
0x00D5, //LATIN CAPITAL LETTER O WITH TILDE
|
||||
0x00D6, //LATIN CAPITAL LETTER O WITH DIAERESIS
|
||||
0x00D7, //MULTIPLICATION SIGN
|
||||
0x00D8, //LATIN CAPITAL LETTER O WITH STROKE
|
||||
0x00D9, //LATIN CAPITAL LETTER U WITH GRAVE
|
||||
0x00DA, //LATIN CAPITAL LETTER U WITH ACUTE
|
||||
0x00DB, //LATIN CAPITAL LETTER U WITH CIRCUMFLEX
|
||||
0x00DC, //LATIN CAPITAL LETTER U WITH DIAERESIS
|
||||
0x00DD, //LATIN CAPITAL LETTER Y WITH ACUTE
|
||||
0x00DE, //LATIN CAPITAL LETTER THORN
|
||||
0x00DF, //LATIN SMALL LETTER SHARP S
|
||||
0x00E0, //LATIN SMALL LETTER A WITH GRAVE
|
||||
0x00E1, //LATIN SMALL LETTER A WITH ACUTE
|
||||
0x00E2, //LATIN SMALL LETTER A WITH CIRCUMFLEX
|
||||
0x00E3, //LATIN SMALL LETTER A WITH TILDE
|
||||
0x00E4, //LATIN SMALL LETTER A WITH DIAERESIS
|
||||
0x00E5, //LATIN SMALL LETTER A WITH RING ABOVE
|
||||
0x00E6, //LATIN SMALL LETTER AE
|
||||
0x00E7, //LATIN SMALL LETTER C WITH CEDILLA
|
||||
0x00E8, //LATIN SMALL LETTER E WITH GRAVE
|
||||
0x00E9, //LATIN SMALL LETTER E WITH ACUTE
|
||||
0x00EA, //LATIN SMALL LETTER E WITH CIRCUMFLEX
|
||||
0x00EB, //LATIN SMALL LETTER E WITH DIAERESIS
|
||||
0x00EC, //LATIN SMALL LETTER I WITH GRAVE
|
||||
0x00ED, //LATIN SMALL LETTER I WITH ACUTE
|
||||
0x00EE, //LATIN SMALL LETTER I WITH CIRCUMFLEX
|
||||
0x00EF, //LATIN SMALL LETTER I WITH DIAERESIS
|
||||
0x00F0, //LATIN SMALL LETTER ETH
|
||||
0x00F1, //LATIN SMALL LETTER N WITH TILDE
|
||||
0x00F2, //LATIN SMALL LETTER O WITH GRAVE
|
||||
0x00F3, //LATIN SMALL LETTER O WITH ACUTE
|
||||
0x00F4, //LATIN SMALL LETTER O WITH CIRCUMFLEX
|
||||
0x00F5, //LATIN SMALL LETTER O WITH TILDE
|
||||
0x00F6, //LATIN SMALL LETTER O WITH DIAERESIS
|
||||
0x00F7, //DIVISION SIGN
|
||||
0x00F8, //LATIN SMALL LETTER O WITH STROKE
|
||||
0x00F9, //LATIN SMALL LETTER U WITH GRAVE
|
||||
0x00FA, //LATIN SMALL LETTER U WITH ACUTE
|
||||
0x00FB, //LATIN SMALL LETTER U WITH CIRCUMFLEX
|
||||
0x00FC, //LATIN SMALL LETTER U WITH DIAERESIS
|
||||
0x00FD, //LATIN SMALL LETTER Y WITH ACUTE
|
||||
0x00FE, //LATIN SMALL LETTER THORN
|
||||
0x00FF, //LATIN SMALL LETTER Y WITH DIAERESIS
|
||||
},
|
||||
}
|
|
@ -0,0 +1,262 @@
|
|||
package cp
|
||||
|
||||
var cp1253 *charsetMap = &charsetMap{
|
||||
sb: [256]rune{
|
||||
0x0000, //NULL
|
||||
0x0001, //START OF HEADING
|
||||
0x0002, //START OF TEXT
|
||||
0x0003, //END OF TEXT
|
||||
0x0004, //END OF TRANSMISSION
|
||||
0x0005, //ENQUIRY
|
||||
0x0006, //ACKNOWLEDGE
|
||||
0x0007, //BELL
|
||||
0x0008, //BACKSPACE
|
||||
0x0009, //HORIZONTAL TABULATION
|
||||
0x000A, //LINE FEED
|
||||
0x000B, //VERTICAL TABULATION
|
||||
0x000C, //FORM FEED
|
||||
0x000D, //CARRIAGE RETURN
|
||||
0x000E, //SHIFT OUT
|
||||
0x000F, //SHIFT IN
|
||||
0x0010, //DATA LINK ESCAPE
|
||||
0x0011, //DEVICE CONTROL ONE
|
||||
0x0012, //DEVICE CONTROL TWO
|
||||
0x0013, //DEVICE CONTROL THREE
|
||||
0x0014, //DEVICE CONTROL FOUR
|
||||
0x0015, //NEGATIVE ACKNOWLEDGE
|
||||
0x0016, //SYNCHRONOUS IDLE
|
||||
0x0017, //END OF TRANSMISSION BLOCK
|
||||
0x0018, //CANCEL
|
||||
0x0019, //END OF MEDIUM
|
||||
0x001A, //SUBSTITUTE
|
||||
0x001B, //ESCAPE
|
||||
0x001C, //FILE SEPARATOR
|
||||
0x001D, //GROUP SEPARATOR
|
||||
0x001E, //RECORD SEPARATOR
|
||||
0x001F, //UNIT SEPARATOR
|
||||
0x0020, //SPACE
|
||||
0x0021, //EXCLAMATION MARK
|
||||
0x0022, //QUOTATION MARK
|
||||
0x0023, //NUMBER SIGN
|
||||
0x0024, //DOLLAR SIGN
|
||||
0x0025, //PERCENT SIGN
|
||||
0x0026, //AMPERSAND
|
||||
0x0027, //APOSTROPHE
|
||||
0x0028, //LEFT PARENTHESIS
|
||||
0x0029, //RIGHT PARENTHESIS
|
||||
0x002A, //ASTERISK
|
||||
0x002B, //PLUS SIGN
|
||||
0x002C, //COMMA
|
||||
0x002D, //HYPHEN-MINUS
|
||||
0x002E, //FULL STOP
|
||||
0x002F, //SOLIDUS
|
||||
0x0030, //DIGIT ZERO
|
||||
0x0031, //DIGIT ONE
|
||||
0x0032, //DIGIT TWO
|
||||
0x0033, //DIGIT THREE
|
||||
0x0034, //DIGIT FOUR
|
||||
0x0035, //DIGIT FIVE
|
||||
0x0036, //DIGIT SIX
|
||||
0x0037, //DIGIT SEVEN
|
||||
0x0038, //DIGIT EIGHT
|
||||
0x0039, //DIGIT NINE
|
||||
0x003A, //COLON
|
||||
0x003B, //SEMICOLON
|
||||
0x003C, //LESS-THAN SIGN
|
||||
0x003D, //EQUALS SIGN
|
||||
0x003E, //GREATER-THAN SIGN
|
||||
0x003F, //QUESTION MARK
|
||||
0x0040, //COMMERCIAL AT
|
||||
0x0041, //LATIN CAPITAL LETTER A
|
||||
0x0042, //LATIN CAPITAL LETTER B
|
||||
0x0043, //LATIN CAPITAL LETTER C
|
||||
0x0044, //LATIN CAPITAL LETTER D
|
||||
0x0045, //LATIN CAPITAL LETTER E
|
||||
0x0046, //LATIN CAPITAL LETTER F
|
||||
0x0047, //LATIN CAPITAL LETTER G
|
||||
0x0048, //LATIN CAPITAL LETTER H
|
||||
0x0049, //LATIN CAPITAL LETTER I
|
||||
0x004A, //LATIN CAPITAL LETTER J
|
||||
0x004B, //LATIN CAPITAL LETTER K
|
||||
0x004C, //LATIN CAPITAL LETTER L
|
||||
0x004D, //LATIN CAPITAL LETTER M
|
||||
0x004E, //LATIN CAPITAL LETTER N
|
||||
0x004F, //LATIN CAPITAL LETTER O
|
||||
0x0050, //LATIN CAPITAL LETTER P
|
||||
0x0051, //LATIN CAPITAL LETTER Q
|
||||
0x0052, //LATIN CAPITAL LETTER R
|
||||
0x0053, //LATIN CAPITAL LETTER S
|
||||
0x0054, //LATIN CAPITAL LETTER T
|
||||
0x0055, //LATIN CAPITAL LETTER U
|
||||
0x0056, //LATIN CAPITAL LETTER V
|
||||
0x0057, //LATIN CAPITAL LETTER W
|
||||
0x0058, //LATIN CAPITAL LETTER X
|
||||
0x0059, //LATIN CAPITAL LETTER Y
|
||||
0x005A, //LATIN CAPITAL LETTER Z
|
||||
0x005B, //LEFT SQUARE BRACKET
|
||||
0x005C, //REVERSE SOLIDUS
|
||||
0x005D, //RIGHT SQUARE BRACKET
|
||||
0x005E, //CIRCUMFLEX ACCENT
|
||||
0x005F, //LOW LINE
|
||||
0x0060, //GRAVE ACCENT
|
||||
0x0061, //LATIN SMALL LETTER A
|
||||
0x0062, //LATIN SMALL LETTER B
|
||||
0x0063, //LATIN SMALL LETTER C
|
||||
0x0064, //LATIN SMALL LETTER D
|
||||
0x0065, //LATIN SMALL LETTER E
|
||||
0x0066, //LATIN SMALL LETTER F
|
||||
0x0067, //LATIN SMALL LETTER G
|
||||
0x0068, //LATIN SMALL LETTER H
|
||||
0x0069, //LATIN SMALL LETTER I
|
||||
0x006A, //LATIN SMALL LETTER J
|
||||
0x006B, //LATIN SMALL LETTER K
|
||||
0x006C, //LATIN SMALL LETTER L
|
||||
0x006D, //LATIN SMALL LETTER M
|
||||
0x006E, //LATIN SMALL LETTER N
|
||||
0x006F, //LATIN SMALL LETTER O
|
||||
0x0070, //LATIN SMALL LETTER P
|
||||
0x0071, //LATIN SMALL LETTER Q
|
||||
0x0072, //LATIN SMALL LETTER R
|
||||
0x0073, //LATIN SMALL LETTER S
|
||||
0x0074, //LATIN SMALL LETTER T
|
||||
0x0075, //LATIN SMALL LETTER U
|
||||
0x0076, //LATIN SMALL LETTER V
|
||||
0x0077, //LATIN SMALL LETTER W
|
||||
0x0078, //LATIN SMALL LETTER X
|
||||
0x0079, //LATIN SMALL LETTER Y
|
||||
0x007A, //LATIN SMALL LETTER Z
|
||||
0x007B, //LEFT CURLY BRACKET
|
||||
0x007C, //VERTICAL LINE
|
||||
0x007D, //RIGHT CURLY BRACKET
|
||||
0x007E, //TILDE
|
||||
0x007F, //DELETE
|
||||
0x20AC, //EURO SIGN
|
||||
0xFFFD, //UNDEFINED
|
||||
0x201A, //SINGLE LOW-9 QUOTATION MARK
|
||||
0x0192, //LATIN SMALL LETTER F WITH HOOK
|
||||
0x201E, //DOUBLE LOW-9 QUOTATION MARK
|
||||
0x2026, //HORIZONTAL ELLIPSIS
|
||||
0x2020, //DAGGER
|
||||
0x2021, //DOUBLE DAGGER
|
||||
0xFFFD, //UNDEFINED
|
||||
0x2030, //PER MILLE SIGN
|
||||
0xFFFD, //UNDEFINED
|
||||
0x2039, //SINGLE LEFT-POINTING ANGLE QUOTATION MARK
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0x2018, //LEFT SINGLE QUOTATION MARK
|
||||
0x2019, //RIGHT SINGLE QUOTATION MARK
|
||||
0x201C, //LEFT DOUBLE QUOTATION MARK
|
||||
0x201D, //RIGHT DOUBLE QUOTATION MARK
|
||||
0x2022, //BULLET
|
||||
0x2013, //EN DASH
|
||||
0x2014, //EM DASH
|
||||
0xFFFD, //UNDEFINED
|
||||
0x2122, //TRADE MARK SIGN
|
||||
0xFFFD, //UNDEFINED
|
||||
0x203A, //SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0x00A0, //NO-BREAK SPACE
|
||||
0x0385, //GREEK DIALYTIKA TONOS
|
||||
0x0386, //GREEK CAPITAL LETTER ALPHA WITH TONOS
|
||||
0x00A3, //POUND SIGN
|
||||
0x00A4, //CURRENCY SIGN
|
||||
0x00A5, //YEN SIGN
|
||||
0x00A6, //BROKEN BAR
|
||||
0x00A7, //SECTION SIGN
|
||||
0x00A8, //DIAERESIS
|
||||
0x00A9, //COPYRIGHT SIGN
|
||||
0xFFFD, //UNDEFINED
|
||||
0x00AB, //LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
|
||||
0x00AC, //NOT SIGN
|
||||
0x00AD, //SOFT HYPHEN
|
||||
0x00AE, //REGISTERED SIGN
|
||||
0x2015, //HORIZONTAL BAR
|
||||
0x00B0, //DEGREE SIGN
|
||||
0x00B1, //PLUS-MINUS SIGN
|
||||
0x00B2, //SUPERSCRIPT TWO
|
||||
0x00B3, //SUPERSCRIPT THREE
|
||||
0x0384, //GREEK TONOS
|
||||
0x00B5, //MICRO SIGN
|
||||
0x00B6, //PILCROW SIGN
|
||||
0x00B7, //MIDDLE DOT
|
||||
0x0388, //GREEK CAPITAL LETTER EPSILON WITH TONOS
|
||||
0x0389, //GREEK CAPITAL LETTER ETA WITH TONOS
|
||||
0x038A, //GREEK CAPITAL LETTER IOTA WITH TONOS
|
||||
0x00BB, //RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
|
||||
0x038C, //GREEK CAPITAL LETTER OMICRON WITH TONOS
|
||||
0x00BD, //VULGAR FRACTION ONE HALF
|
||||
0x038E, //GREEK CAPITAL LETTER UPSILON WITH TONOS
|
||||
0x038F, //GREEK CAPITAL LETTER OMEGA WITH TONOS
|
||||
0x0390, //GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS
|
||||
0x0391, //GREEK CAPITAL LETTER ALPHA
|
||||
0x0392, //GREEK CAPITAL LETTER BETA
|
||||
0x0393, //GREEK CAPITAL LETTER GAMMA
|
||||
0x0394, //GREEK CAPITAL LETTER DELTA
|
||||
0x0395, //GREEK CAPITAL LETTER EPSILON
|
||||
0x0396, //GREEK CAPITAL LETTER ZETA
|
||||
0x0397, //GREEK CAPITAL LETTER ETA
|
||||
0x0398, //GREEK CAPITAL LETTER THETA
|
||||
0x0399, //GREEK CAPITAL LETTER IOTA
|
||||
0x039A, //GREEK CAPITAL LETTER KAPPA
|
||||
0x039B, //GREEK CAPITAL LETTER LAMDA
|
||||
0x039C, //GREEK CAPITAL LETTER MU
|
||||
0x039D, //GREEK CAPITAL LETTER NU
|
||||
0x039E, //GREEK CAPITAL LETTER XI
|
||||
0x039F, //GREEK CAPITAL LETTER OMICRON
|
||||
0x03A0, //GREEK CAPITAL LETTER PI
|
||||
0x03A1, //GREEK CAPITAL LETTER RHO
|
||||
0xFFFD, //UNDEFINED
|
||||
0x03A3, //GREEK CAPITAL LETTER SIGMA
|
||||
0x03A4, //GREEK CAPITAL LETTER TAU
|
||||
0x03A5, //GREEK CAPITAL LETTER UPSILON
|
||||
0x03A6, //GREEK CAPITAL LETTER PHI
|
||||
0x03A7, //GREEK CAPITAL LETTER CHI
|
||||
0x03A8, //GREEK CAPITAL LETTER PSI
|
||||
0x03A9, //GREEK CAPITAL LETTER OMEGA
|
||||
0x03AA, //GREEK CAPITAL LETTER IOTA WITH DIALYTIKA
|
||||
0x03AB, //GREEK CAPITAL LETTER UPSILON WITH DIALYTIKA
|
||||
0x03AC, //GREEK SMALL LETTER ALPHA WITH TONOS
|
||||
0x03AD, //GREEK SMALL LETTER EPSILON WITH TONOS
|
||||
0x03AE, //GREEK SMALL LETTER ETA WITH TONOS
|
||||
0x03AF, //GREEK SMALL LETTER IOTA WITH TONOS
|
||||
0x03B0, //GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS
|
||||
0x03B1, //GREEK SMALL LETTER ALPHA
|
||||
0x03B2, //GREEK SMALL LETTER BETA
|
||||
0x03B3, //GREEK SMALL LETTER GAMMA
|
||||
0x03B4, //GREEK SMALL LETTER DELTA
|
||||
0x03B5, //GREEK SMALL LETTER EPSILON
|
||||
0x03B6, //GREEK SMALL LETTER ZETA
|
||||
0x03B7, //GREEK SMALL LETTER ETA
|
||||
0x03B8, //GREEK SMALL LETTER THETA
|
||||
0x03B9, //GREEK SMALL LETTER IOTA
|
||||
0x03BA, //GREEK SMALL LETTER KAPPA
|
||||
0x03BB, //GREEK SMALL LETTER LAMDA
|
||||
0x03BC, //GREEK SMALL LETTER MU
|
||||
0x03BD, //GREEK SMALL LETTER NU
|
||||
0x03BE, //GREEK SMALL LETTER XI
|
||||
0x03BF, //GREEK SMALL LETTER OMICRON
|
||||
0x03C0, //GREEK SMALL LETTER PI
|
||||
0x03C1, //GREEK SMALL LETTER RHO
|
||||
0x03C2, //GREEK SMALL LETTER FINAL SIGMA
|
||||
0x03C3, //GREEK SMALL LETTER SIGMA
|
||||
0x03C4, //GREEK SMALL LETTER TAU
|
||||
0x03C5, //GREEK SMALL LETTER UPSILON
|
||||
0x03C6, //GREEK SMALL LETTER PHI
|
||||
0x03C7, //GREEK SMALL LETTER CHI
|
||||
0x03C8, //GREEK SMALL LETTER PSI
|
||||
0x03C9, //GREEK SMALL LETTER OMEGA
|
||||
0x03CA, //GREEK SMALL LETTER IOTA WITH DIALYTIKA
|
||||
0x03CB, //GREEK SMALL LETTER UPSILON WITH DIALYTIKA
|
||||
0x03CC, //GREEK SMALL LETTER OMICRON WITH TONOS
|
||||
0x03CD, //GREEK SMALL LETTER UPSILON WITH TONOS
|
||||
0x03CE, //GREEK SMALL LETTER OMEGA WITH TONOS
|
||||
0xFFFD, //UNDEFINED
|
||||
},
|
||||
}
|
|
@ -0,0 +1,262 @@
|
|||
package cp
|
||||
|
||||
var cp1254 *charsetMap = &charsetMap{
|
||||
sb: [256]rune{
|
||||
0x0000, //NULL
|
||||
0x0001, //START OF HEADING
|
||||
0x0002, //START OF TEXT
|
||||
0x0003, //END OF TEXT
|
||||
0x0004, //END OF TRANSMISSION
|
||||
0x0005, //ENQUIRY
|
||||
0x0006, //ACKNOWLEDGE
|
||||
0x0007, //BELL
|
||||
0x0008, //BACKSPACE
|
||||
0x0009, //HORIZONTAL TABULATION
|
||||
0x000A, //LINE FEED
|
||||
0x000B, //VERTICAL TABULATION
|
||||
0x000C, //FORM FEED
|
||||
0x000D, //CARRIAGE RETURN
|
||||
0x000E, //SHIFT OUT
|
||||
0x000F, //SHIFT IN
|
||||
0x0010, //DATA LINK ESCAPE
|
||||
0x0011, //DEVICE CONTROL ONE
|
||||
0x0012, //DEVICE CONTROL TWO
|
||||
0x0013, //DEVICE CONTROL THREE
|
||||
0x0014, //DEVICE CONTROL FOUR
|
||||
0x0015, //NEGATIVE ACKNOWLEDGE
|
||||
0x0016, //SYNCHRONOUS IDLE
|
||||
0x0017, //END OF TRANSMISSION BLOCK
|
||||
0x0018, //CANCEL
|
||||
0x0019, //END OF MEDIUM
|
||||
0x001A, //SUBSTITUTE
|
||||
0x001B, //ESCAPE
|
||||
0x001C, //FILE SEPARATOR
|
||||
0x001D, //GROUP SEPARATOR
|
||||
0x001E, //RECORD SEPARATOR
|
||||
0x001F, //UNIT SEPARATOR
|
||||
0x0020, //SPACE
|
||||
0x0021, //EXCLAMATION MARK
|
||||
0x0022, //QUOTATION MARK
|
||||
0x0023, //NUMBER SIGN
|
||||
0x0024, //DOLLAR SIGN
|
||||
0x0025, //PERCENT SIGN
|
||||
0x0026, //AMPERSAND
|
||||
0x0027, //APOSTROPHE
|
||||
0x0028, //LEFT PARENTHESIS
|
||||
0x0029, //RIGHT PARENTHESIS
|
||||
0x002A, //ASTERISK
|
||||
0x002B, //PLUS SIGN
|
||||
0x002C, //COMMA
|
||||
0x002D, //HYPHEN-MINUS
|
||||
0x002E, //FULL STOP
|
||||
0x002F, //SOLIDUS
|
||||
0x0030, //DIGIT ZERO
|
||||
0x0031, //DIGIT ONE
|
||||
0x0032, //DIGIT TWO
|
||||
0x0033, //DIGIT THREE
|
||||
0x0034, //DIGIT FOUR
|
||||
0x0035, //DIGIT FIVE
|
||||
0x0036, //DIGIT SIX
|
||||
0x0037, //DIGIT SEVEN
|
||||
0x0038, //DIGIT EIGHT
|
||||
0x0039, //DIGIT NINE
|
||||
0x003A, //COLON
|
||||
0x003B, //SEMICOLON
|
||||
0x003C, //LESS-THAN SIGN
|
||||
0x003D, //EQUALS SIGN
|
||||
0x003E, //GREATER-THAN SIGN
|
||||
0x003F, //QUESTION MARK
|
||||
0x0040, //COMMERCIAL AT
|
||||
0x0041, //LATIN CAPITAL LETTER A
|
||||
0x0042, //LATIN CAPITAL LETTER B
|
||||
0x0043, //LATIN CAPITAL LETTER C
|
||||
0x0044, //LATIN CAPITAL LETTER D
|
||||
0x0045, //LATIN CAPITAL LETTER E
|
||||
0x0046, //LATIN CAPITAL LETTER F
|
||||
0x0047, //LATIN CAPITAL LETTER G
|
||||
0x0048, //LATIN CAPITAL LETTER H
|
||||
0x0049, //LATIN CAPITAL LETTER I
|
||||
0x004A, //LATIN CAPITAL LETTER J
|
||||
0x004B, //LATIN CAPITAL LETTER K
|
||||
0x004C, //LATIN CAPITAL LETTER L
|
||||
0x004D, //LATIN CAPITAL LETTER M
|
||||
0x004E, //LATIN CAPITAL LETTER N
|
||||
0x004F, //LATIN CAPITAL LETTER O
|
||||
0x0050, //LATIN CAPITAL LETTER P
|
||||
0x0051, //LATIN CAPITAL LETTER Q
|
||||
0x0052, //LATIN CAPITAL LETTER R
|
||||
0x0053, //LATIN CAPITAL LETTER S
|
||||
0x0054, //LATIN CAPITAL LETTER T
|
||||
0x0055, //LATIN CAPITAL LETTER U
|
||||
0x0056, //LATIN CAPITAL LETTER V
|
||||
0x0057, //LATIN CAPITAL LETTER W
|
||||
0x0058, //LATIN CAPITAL LETTER X
|
||||
0x0059, //LATIN CAPITAL LETTER Y
|
||||
0x005A, //LATIN CAPITAL LETTER Z
|
||||
0x005B, //LEFT SQUARE BRACKET
|
||||
0x005C, //REVERSE SOLIDUS
|
||||
0x005D, //RIGHT SQUARE BRACKET
|
||||
0x005E, //CIRCUMFLEX ACCENT
|
||||
0x005F, //LOW LINE
|
||||
0x0060, //GRAVE ACCENT
|
||||
0x0061, //LATIN SMALL LETTER A
|
||||
0x0062, //LATIN SMALL LETTER B
|
||||
0x0063, //LATIN SMALL LETTER C
|
||||
0x0064, //LATIN SMALL LETTER D
|
||||
0x0065, //LATIN SMALL LETTER E
|
||||
0x0066, //LATIN SMALL LETTER F
|
||||
0x0067, //LATIN SMALL LETTER G
|
||||
0x0068, //LATIN SMALL LETTER H
|
||||
0x0069, //LATIN SMALL LETTER I
|
||||
0x006A, //LATIN SMALL LETTER J
|
||||
0x006B, //LATIN SMALL LETTER K
|
||||
0x006C, //LATIN SMALL LETTER L
|
||||
0x006D, //LATIN SMALL LETTER M
|
||||
0x006E, //LATIN SMALL LETTER N
|
||||
0x006F, //LATIN SMALL LETTER O
|
||||
0x0070, //LATIN SMALL LETTER P
|
||||
0x0071, //LATIN SMALL LETTER Q
|
||||
0x0072, //LATIN SMALL LETTER R
|
||||
0x0073, //LATIN SMALL LETTER S
|
||||
0x0074, //LATIN SMALL LETTER T
|
||||
0x0075, //LATIN SMALL LETTER U
|
||||
0x0076, //LATIN SMALL LETTER V
|
||||
0x0077, //LATIN SMALL LETTER W
|
||||
0x0078, //LATIN SMALL LETTER X
|
||||
0x0079, //LATIN SMALL LETTER Y
|
||||
0x007A, //LATIN SMALL LETTER Z
|
||||
0x007B, //LEFT CURLY BRACKET
|
||||
0x007C, //VERTICAL LINE
|
||||
0x007D, //RIGHT CURLY BRACKET
|
||||
0x007E, //TILDE
|
||||
0x007F, //DELETE
|
||||
0x20AC, //EURO SIGN
|
||||
0xFFFD, //UNDEFINED
|
||||
0x201A, //SINGLE LOW-9 QUOTATION MARK
|
||||
0x0192, //LATIN SMALL LETTER F WITH HOOK
|
||||
0x201E, //DOUBLE LOW-9 QUOTATION MARK
|
||||
0x2026, //HORIZONTAL ELLIPSIS
|
||||
0x2020, //DAGGER
|
||||
0x2021, //DOUBLE DAGGER
|
||||
0x02C6, //MODIFIER LETTER CIRCUMFLEX ACCENT
|
||||
0x2030, //PER MILLE SIGN
|
||||
0x0160, //LATIN CAPITAL LETTER S WITH CARON
|
||||
0x2039, //SINGLE LEFT-POINTING ANGLE QUOTATION MARK
|
||||
0x0152, //LATIN CAPITAL LIGATURE OE
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0x2018, //LEFT SINGLE QUOTATION MARK
|
||||
0x2019, //RIGHT SINGLE QUOTATION MARK
|
||||
0x201C, //LEFT DOUBLE QUOTATION MARK
|
||||
0x201D, //RIGHT DOUBLE QUOTATION MARK
|
||||
0x2022, //BULLET
|
||||
0x2013, //EN DASH
|
||||
0x2014, //EM DASH
|
||||
0x02DC, //SMALL TILDE
|
||||
0x2122, //TRADE MARK SIGN
|
||||
0x0161, //LATIN SMALL LETTER S WITH CARON
|
||||
0x203A, //SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
|
||||
0x0153, //LATIN SMALL LIGATURE OE
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0x0178, //LATIN CAPITAL LETTER Y WITH DIAERESIS
|
||||
0x00A0, //NO-BREAK SPACE
|
||||
0x00A1, //INVERTED EXCLAMATION MARK
|
||||
0x00A2, //CENT SIGN
|
||||
0x00A3, //POUND SIGN
|
||||
0x00A4, //CURRENCY SIGN
|
||||
0x00A5, //YEN SIGN
|
||||
0x00A6, //BROKEN BAR
|
||||
0x00A7, //SECTION SIGN
|
||||
0x00A8, //DIAERESIS
|
||||
0x00A9, //COPYRIGHT SIGN
|
||||
0x00AA, //FEMININE ORDINAL INDICATOR
|
||||
0x00AB, //LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
|
||||
0x00AC, //NOT SIGN
|
||||
0x00AD, //SOFT HYPHEN
|
||||
0x00AE, //REGISTERED SIGN
|
||||
0x00AF, //MACRON
|
||||
0x00B0, //DEGREE SIGN
|
||||
0x00B1, //PLUS-MINUS SIGN
|
||||
0x00B2, //SUPERSCRIPT TWO
|
||||
0x00B3, //SUPERSCRIPT THREE
|
||||
0x00B4, //ACUTE ACCENT
|
||||
0x00B5, //MICRO SIGN
|
||||
0x00B6, //PILCROW SIGN
|
||||
0x00B7, //MIDDLE DOT
|
||||
0x00B8, //CEDILLA
|
||||
0x00B9, //SUPERSCRIPT ONE
|
||||
0x00BA, //MASCULINE ORDINAL INDICATOR
|
||||
0x00BB, //RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
|
||||
0x00BC, //VULGAR FRACTION ONE QUARTER
|
||||
0x00BD, //VULGAR FRACTION ONE HALF
|
||||
0x00BE, //VULGAR FRACTION THREE QUARTERS
|
||||
0x00BF, //INVERTED QUESTION MARK
|
||||
0x00C0, //LATIN CAPITAL LETTER A WITH GRAVE
|
||||
0x00C1, //LATIN CAPITAL LETTER A WITH ACUTE
|
||||
0x00C2, //LATIN CAPITAL LETTER A WITH CIRCUMFLEX
|
||||
0x00C3, //LATIN CAPITAL LETTER A WITH TILDE
|
||||
0x00C4, //LATIN CAPITAL LETTER A WITH DIAERESIS
|
||||
0x00C5, //LATIN CAPITAL LETTER A WITH RING ABOVE
|
||||
0x00C6, //LATIN CAPITAL LETTER AE
|
||||
0x00C7, //LATIN CAPITAL LETTER C WITH CEDILLA
|
||||
0x00C8, //LATIN CAPITAL LETTER E WITH GRAVE
|
||||
0x00C9, //LATIN CAPITAL LETTER E WITH ACUTE
|
||||
0x00CA, //LATIN CAPITAL LETTER E WITH CIRCUMFLEX
|
||||
0x00CB, //LATIN CAPITAL LETTER E WITH DIAERESIS
|
||||
0x00CC, //LATIN CAPITAL LETTER I WITH GRAVE
|
||||
0x00CD, //LATIN CAPITAL LETTER I WITH ACUTE
|
||||
0x00CE, //LATIN CAPITAL LETTER I WITH CIRCUMFLEX
|
||||
0x00CF, //LATIN CAPITAL LETTER I WITH DIAERESIS
|
||||
0x011E, //LATIN CAPITAL LETTER G WITH BREVE
|
||||
0x00D1, //LATIN CAPITAL LETTER N WITH TILDE
|
||||
0x00D2, //LATIN CAPITAL LETTER O WITH GRAVE
|
||||
0x00D3, //LATIN CAPITAL LETTER O WITH ACUTE
|
||||
0x00D4, //LATIN CAPITAL LETTER O WITH CIRCUMFLEX
|
||||
0x00D5, //LATIN CAPITAL LETTER O WITH TILDE
|
||||
0x00D6, //LATIN CAPITAL LETTER O WITH DIAERESIS
|
||||
0x00D7, //MULTIPLICATION SIGN
|
||||
0x00D8, //LATIN CAPITAL LETTER O WITH STROKE
|
||||
0x00D9, //LATIN CAPITAL LETTER U WITH GRAVE
|
||||
0x00DA, //LATIN CAPITAL LETTER U WITH ACUTE
|
||||
0x00DB, //LATIN CAPITAL LETTER U WITH CIRCUMFLEX
|
||||
0x00DC, //LATIN CAPITAL LETTER U WITH DIAERESIS
|
||||
0x0130, //LATIN CAPITAL LETTER I WITH DOT ABOVE
|
||||
0x015E, //LATIN CAPITAL LETTER S WITH CEDILLA
|
||||
0x00DF, //LATIN SMALL LETTER SHARP S
|
||||
0x00E0, //LATIN SMALL LETTER A WITH GRAVE
|
||||
0x00E1, //LATIN SMALL LETTER A WITH ACUTE
|
||||
0x00E2, //LATIN SMALL LETTER A WITH CIRCUMFLEX
|
||||
0x00E3, //LATIN SMALL LETTER A WITH TILDE
|
||||
0x00E4, //LATIN SMALL LETTER A WITH DIAERESIS
|
||||
0x00E5, //LATIN SMALL LETTER A WITH RING ABOVE
|
||||
0x00E6, //LATIN SMALL LETTER AE
|
||||
0x00E7, //LATIN SMALL LETTER C WITH CEDILLA
|
||||
0x00E8, //LATIN SMALL LETTER E WITH GRAVE
|
||||
0x00E9, //LATIN SMALL LETTER E WITH ACUTE
|
||||
0x00EA, //LATIN SMALL LETTER E WITH CIRCUMFLEX
|
||||
0x00EB, //LATIN SMALL LETTER E WITH DIAERESIS
|
||||
0x00EC, //LATIN SMALL LETTER I WITH GRAVE
|
||||
0x00ED, //LATIN SMALL LETTER I WITH ACUTE
|
||||
0x00EE, //LATIN SMALL LETTER I WITH CIRCUMFLEX
|
||||
0x00EF, //LATIN SMALL LETTER I WITH DIAERESIS
|
||||
0x011F, //LATIN SMALL LETTER G WITH BREVE
|
||||
0x00F1, //LATIN SMALL LETTER N WITH TILDE
|
||||
0x00F2, //LATIN SMALL LETTER O WITH GRAVE
|
||||
0x00F3, //LATIN SMALL LETTER O WITH ACUTE
|
||||
0x00F4, //LATIN SMALL LETTER O WITH CIRCUMFLEX
|
||||
0x00F5, //LATIN SMALL LETTER O WITH TILDE
|
||||
0x00F6, //LATIN SMALL LETTER O WITH DIAERESIS
|
||||
0x00F7, //DIVISION SIGN
|
||||
0x00F8, //LATIN SMALL LETTER O WITH STROKE
|
||||
0x00F9, //LATIN SMALL LETTER U WITH GRAVE
|
||||
0x00FA, //LATIN SMALL LETTER U WITH ACUTE
|
||||
0x00FB, //LATIN SMALL LETTER U WITH CIRCUMFLEX
|
||||
0x00FC, //LATIN SMALL LETTER U WITH DIAERESIS
|
||||
0x0131, //LATIN SMALL LETTER DOTLESS I
|
||||
0x015F, //LATIN SMALL LETTER S WITH CEDILLA
|
||||
0x00FF, //LATIN SMALL LETTER Y WITH DIAERESIS
|
||||
},
|
||||
}
|
|
@ -0,0 +1,262 @@
|
|||
package cp
|
||||
|
||||
var cp1255 *charsetMap = &charsetMap{
|
||||
sb: [256]rune{
|
||||
0x0000, //NULL
|
||||
0x0001, //START OF HEADING
|
||||
0x0002, //START OF TEXT
|
||||
0x0003, //END OF TEXT
|
||||
0x0004, //END OF TRANSMISSION
|
||||
0x0005, //ENQUIRY
|
||||
0x0006, //ACKNOWLEDGE
|
||||
0x0007, //BELL
|
||||
0x0008, //BACKSPACE
|
||||
0x0009, //HORIZONTAL TABULATION
|
||||
0x000A, //LINE FEED
|
||||
0x000B, //VERTICAL TABULATION
|
||||
0x000C, //FORM FEED
|
||||
0x000D, //CARRIAGE RETURN
|
||||
0x000E, //SHIFT OUT
|
||||
0x000F, //SHIFT IN
|
||||
0x0010, //DATA LINK ESCAPE
|
||||
0x0011, //DEVICE CONTROL ONE
|
||||
0x0012, //DEVICE CONTROL TWO
|
||||
0x0013, //DEVICE CONTROL THREE
|
||||
0x0014, //DEVICE CONTROL FOUR
|
||||
0x0015, //NEGATIVE ACKNOWLEDGE
|
||||
0x0016, //SYNCHRONOUS IDLE
|
||||
0x0017, //END OF TRANSMISSION BLOCK
|
||||
0x0018, //CANCEL
|
||||
0x0019, //END OF MEDIUM
|
||||
0x001A, //SUBSTITUTE
|
||||
0x001B, //ESCAPE
|
||||
0x001C, //FILE SEPARATOR
|
||||
0x001D, //GROUP SEPARATOR
|
||||
0x001E, //RECORD SEPARATOR
|
||||
0x001F, //UNIT SEPARATOR
|
||||
0x0020, //SPACE
|
||||
0x0021, //EXCLAMATION MARK
|
||||
0x0022, //QUOTATION MARK
|
||||
0x0023, //NUMBER SIGN
|
||||
0x0024, //DOLLAR SIGN
|
||||
0x0025, //PERCENT SIGN
|
||||
0x0026, //AMPERSAND
|
||||
0x0027, //APOSTROPHE
|
||||
0x0028, //LEFT PARENTHESIS
|
||||
0x0029, //RIGHT PARENTHESIS
|
||||
0x002A, //ASTERISK
|
||||
0x002B, //PLUS SIGN
|
||||
0x002C, //COMMA
|
||||
0x002D, //HYPHEN-MINUS
|
||||
0x002E, //FULL STOP
|
||||
0x002F, //SOLIDUS
|
||||
0x0030, //DIGIT ZERO
|
||||
0x0031, //DIGIT ONE
|
||||
0x0032, //DIGIT TWO
|
||||
0x0033, //DIGIT THREE
|
||||
0x0034, //DIGIT FOUR
|
||||
0x0035, //DIGIT FIVE
|
||||
0x0036, //DIGIT SIX
|
||||
0x0037, //DIGIT SEVEN
|
||||
0x0038, //DIGIT EIGHT
|
||||
0x0039, //DIGIT NINE
|
||||
0x003A, //COLON
|
||||
0x003B, //SEMICOLON
|
||||
0x003C, //LESS-THAN SIGN
|
||||
0x003D, //EQUALS SIGN
|
||||
0x003E, //GREATER-THAN SIGN
|
||||
0x003F, //QUESTION MARK
|
||||
0x0040, //COMMERCIAL AT
|
||||
0x0041, //LATIN CAPITAL LETTER A
|
||||
0x0042, //LATIN CAPITAL LETTER B
|
||||
0x0043, //LATIN CAPITAL LETTER C
|
||||
0x0044, //LATIN CAPITAL LETTER D
|
||||
0x0045, //LATIN CAPITAL LETTER E
|
||||
0x0046, //LATIN CAPITAL LETTER F
|
||||
0x0047, //LATIN CAPITAL LETTER G
|
||||
0x0048, //LATIN CAPITAL LETTER H
|
||||
0x0049, //LATIN CAPITAL LETTER I
|
||||
0x004A, //LATIN CAPITAL LETTER J
|
||||
0x004B, //LATIN CAPITAL LETTER K
|
||||
0x004C, //LATIN CAPITAL LETTER L
|
||||
0x004D, //LATIN CAPITAL LETTER M
|
||||
0x004E, //LATIN CAPITAL LETTER N
|
||||
0x004F, //LATIN CAPITAL LETTER O
|
||||
0x0050, //LATIN CAPITAL LETTER P
|
||||
0x0051, //LATIN CAPITAL LETTER Q
|
||||
0x0052, //LATIN CAPITAL LETTER R
|
||||
0x0053, //LATIN CAPITAL LETTER S
|
||||
0x0054, //LATIN CAPITAL LETTER T
|
||||
0x0055, //LATIN CAPITAL LETTER U
|
||||
0x0056, //LATIN CAPITAL LETTER V
|
||||
0x0057, //LATIN CAPITAL LETTER W
|
||||
0x0058, //LATIN CAPITAL LETTER X
|
||||
0x0059, //LATIN CAPITAL LETTER Y
|
||||
0x005A, //LATIN CAPITAL LETTER Z
|
||||
0x005B, //LEFT SQUARE BRACKET
|
||||
0x005C, //REVERSE SOLIDUS
|
||||
0x005D, //RIGHT SQUARE BRACKET
|
||||
0x005E, //CIRCUMFLEX ACCENT
|
||||
0x005F, //LOW LINE
|
||||
0x0060, //GRAVE ACCENT
|
||||
0x0061, //LATIN SMALL LETTER A
|
||||
0x0062, //LATIN SMALL LETTER B
|
||||
0x0063, //LATIN SMALL LETTER C
|
||||
0x0064, //LATIN SMALL LETTER D
|
||||
0x0065, //LATIN SMALL LETTER E
|
||||
0x0066, //LATIN SMALL LETTER F
|
||||
0x0067, //LATIN SMALL LETTER G
|
||||
0x0068, //LATIN SMALL LETTER H
|
||||
0x0069, //LATIN SMALL LETTER I
|
||||
0x006A, //LATIN SMALL LETTER J
|
||||
0x006B, //LATIN SMALL LETTER K
|
||||
0x006C, //LATIN SMALL LETTER L
|
||||
0x006D, //LATIN SMALL LETTER M
|
||||
0x006E, //LATIN SMALL LETTER N
|
||||
0x006F, //LATIN SMALL LETTER O
|
||||
0x0070, //LATIN SMALL LETTER P
|
||||
0x0071, //LATIN SMALL LETTER Q
|
||||
0x0072, //LATIN SMALL LETTER R
|
||||
0x0073, //LATIN SMALL LETTER S
|
||||
0x0074, //LATIN SMALL LETTER T
|
||||
0x0075, //LATIN SMALL LETTER U
|
||||
0x0076, //LATIN SMALL LETTER V
|
||||
0x0077, //LATIN SMALL LETTER W
|
||||
0x0078, //LATIN SMALL LETTER X
|
||||
0x0079, //LATIN SMALL LETTER Y
|
||||
0x007A, //LATIN SMALL LETTER Z
|
||||
0x007B, //LEFT CURLY BRACKET
|
||||
0x007C, //VERTICAL LINE
|
||||
0x007D, //RIGHT CURLY BRACKET
|
||||
0x007E, //TILDE
|
||||
0x007F, //DELETE
|
||||
0x20AC, //EURO SIGN
|
||||
0xFFFD, //UNDEFINED
|
||||
0x201A, //SINGLE LOW-9 QUOTATION MARK
|
||||
0x0192, //LATIN SMALL LETTER F WITH HOOK
|
||||
0x201E, //DOUBLE LOW-9 QUOTATION MARK
|
||||
0x2026, //HORIZONTAL ELLIPSIS
|
||||
0x2020, //DAGGER
|
||||
0x2021, //DOUBLE DAGGER
|
||||
0x02C6, //MODIFIER LETTER CIRCUMFLEX ACCENT
|
||||
0x2030, //PER MILLE SIGN
|
||||
0xFFFD, //UNDEFINED
|
||||
0x2039, //SINGLE LEFT-POINTING ANGLE QUOTATION MARK
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0x2018, //LEFT SINGLE QUOTATION MARK
|
||||
0x2019, //RIGHT SINGLE QUOTATION MARK
|
||||
0x201C, //LEFT DOUBLE QUOTATION MARK
|
||||
0x201D, //RIGHT DOUBLE QUOTATION MARK
|
||||
0x2022, //BULLET
|
||||
0x2013, //EN DASH
|
||||
0x2014, //EM DASH
|
||||
0x02DC, //SMALL TILDE
|
||||
0x2122, //TRADE MARK SIGN
|
||||
0xFFFD, //UNDEFINED
|
||||
0x203A, //SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0x00A0, //NO-BREAK SPACE
|
||||
0x00A1, //INVERTED EXCLAMATION MARK
|
||||
0x00A2, //CENT SIGN
|
||||
0x00A3, //POUND SIGN
|
||||
0x20AA, //NEW SHEQEL SIGN
|
||||
0x00A5, //YEN SIGN
|
||||
0x00A6, //BROKEN BAR
|
||||
0x00A7, //SECTION SIGN
|
||||
0x00A8, //DIAERESIS
|
||||
0x00A9, //COPYRIGHT SIGN
|
||||
0x00D7, //MULTIPLICATION SIGN
|
||||
0x00AB, //LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
|
||||
0x00AC, //NOT SIGN
|
||||
0x00AD, //SOFT HYPHEN
|
||||
0x00AE, //REGISTERED SIGN
|
||||
0x00AF, //MACRON
|
||||
0x00B0, //DEGREE SIGN
|
||||
0x00B1, //PLUS-MINUS SIGN
|
||||
0x00B2, //SUPERSCRIPT TWO
|
||||
0x00B3, //SUPERSCRIPT THREE
|
||||
0x00B4, //ACUTE ACCENT
|
||||
0x00B5, //MICRO SIGN
|
||||
0x00B6, //PILCROW SIGN
|
||||
0x00B7, //MIDDLE DOT
|
||||
0x00B8, //CEDILLA
|
||||
0x00B9, //SUPERSCRIPT ONE
|
||||
0x00F7, //DIVISION SIGN
|
||||
0x00BB, //RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
|
||||
0x00BC, //VULGAR FRACTION ONE QUARTER
|
||||
0x00BD, //VULGAR FRACTION ONE HALF
|
||||
0x00BE, //VULGAR FRACTION THREE QUARTERS
|
||||
0x00BF, //INVERTED QUESTION MARK
|
||||
0x05B0, //HEBREW POINT SHEVA
|
||||
0x05B1, //HEBREW POINT HATAF SEGOL
|
||||
0x05B2, //HEBREW POINT HATAF PATAH
|
||||
0x05B3, //HEBREW POINT HATAF QAMATS
|
||||
0x05B4, //HEBREW POINT HIRIQ
|
||||
0x05B5, //HEBREW POINT TSERE
|
||||
0x05B6, //HEBREW POINT SEGOL
|
||||
0x05B7, //HEBREW POINT PATAH
|
||||
0x05B8, //HEBREW POINT QAMATS
|
||||
0x05B9, //HEBREW POINT HOLAM
|
||||
0xFFFD, //UNDEFINED
|
||||
0x05BB, //HEBREW POINT QUBUTS
|
||||
0x05BC, //HEBREW POINT DAGESH OR MAPIQ
|
||||
0x05BD, //HEBREW POINT METEG
|
||||
0x05BE, //HEBREW PUNCTUATION MAQAF
|
||||
0x05BF, //HEBREW POINT RAFE
|
||||
0x05C0, //HEBREW PUNCTUATION PASEQ
|
||||
0x05C1, //HEBREW POINT SHIN DOT
|
||||
0x05C2, //HEBREW POINT SIN DOT
|
||||
0x05C3, //HEBREW PUNCTUATION SOF PASUQ
|
||||
0x05F0, //HEBREW LIGATURE YIDDISH DOUBLE VAV
|
||||
0x05F1, //HEBREW LIGATURE YIDDISH VAV YOD
|
||||
0x05F2, //HEBREW LIGATURE YIDDISH DOUBLE YOD
|
||||
0x05F3, //HEBREW PUNCTUATION GERESH
|
||||
0x05F4, //HEBREW PUNCTUATION GERSHAYIM
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0x05D0, //HEBREW LETTER ALEF
|
||||
0x05D1, //HEBREW LETTER BET
|
||||
0x05D2, //HEBREW LETTER GIMEL
|
||||
0x05D3, //HEBREW LETTER DALET
|
||||
0x05D4, //HEBREW LETTER HE
|
||||
0x05D5, //HEBREW LETTER VAV
|
||||
0x05D6, //HEBREW LETTER ZAYIN
|
||||
0x05D7, //HEBREW LETTER HET
|
||||
0x05D8, //HEBREW LETTER TET
|
||||
0x05D9, //HEBREW LETTER YOD
|
||||
0x05DA, //HEBREW LETTER FINAL KAF
|
||||
0x05DB, //HEBREW LETTER KAF
|
||||
0x05DC, //HEBREW LETTER LAMED
|
||||
0x05DD, //HEBREW LETTER FINAL MEM
|
||||
0x05DE, //HEBREW LETTER MEM
|
||||
0x05DF, //HEBREW LETTER FINAL NUN
|
||||
0x05E0, //HEBREW LETTER NUN
|
||||
0x05E1, //HEBREW LETTER SAMEKH
|
||||
0x05E2, //HEBREW LETTER AYIN
|
||||
0x05E3, //HEBREW LETTER FINAL PE
|
||||
0x05E4, //HEBREW LETTER PE
|
||||
0x05E5, //HEBREW LETTER FINAL TSADI
|
||||
0x05E6, //HEBREW LETTER TSADI
|
||||
0x05E7, //HEBREW LETTER QOF
|
||||
0x05E8, //HEBREW LETTER RESH
|
||||
0x05E9, //HEBREW LETTER SHIN
|
||||
0x05EA, //HEBREW LETTER TAV
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0x200E, //LEFT-TO-RIGHT MARK
|
||||
0x200F, //RIGHT-TO-LEFT MARK
|
||||
0xFFFD, //UNDEFINED
|
||||
},
|
||||
}
|
|
@ -0,0 +1,262 @@
|
|||
package cp
|
||||
|
||||
var cp1256 *charsetMap = &charsetMap{
|
||||
sb: [256]rune{
|
||||
0x0000, //NULL
|
||||
0x0001, //START OF HEADING
|
||||
0x0002, //START OF TEXT
|
||||
0x0003, //END OF TEXT
|
||||
0x0004, //END OF TRANSMISSION
|
||||
0x0005, //ENQUIRY
|
||||
0x0006, //ACKNOWLEDGE
|
||||
0x0007, //BELL
|
||||
0x0008, //BACKSPACE
|
||||
0x0009, //HORIZONTAL TABULATION
|
||||
0x000A, //LINE FEED
|
||||
0x000B, //VERTICAL TABULATION
|
||||
0x000C, //FORM FEED
|
||||
0x000D, //CARRIAGE RETURN
|
||||
0x000E, //SHIFT OUT
|
||||
0x000F, //SHIFT IN
|
||||
0x0010, //DATA LINK ESCAPE
|
||||
0x0011, //DEVICE CONTROL ONE
|
||||
0x0012, //DEVICE CONTROL TWO
|
||||
0x0013, //DEVICE CONTROL THREE
|
||||
0x0014, //DEVICE CONTROL FOUR
|
||||
0x0015, //NEGATIVE ACKNOWLEDGE
|
||||
0x0016, //SYNCHRONOUS IDLE
|
||||
0x0017, //END OF TRANSMISSION BLOCK
|
||||
0x0018, //CANCEL
|
||||
0x0019, //END OF MEDIUM
|
||||
0x001A, //SUBSTITUTE
|
||||
0x001B, //ESCAPE
|
||||
0x001C, //FILE SEPARATOR
|
||||
0x001D, //GROUP SEPARATOR
|
||||
0x001E, //RECORD SEPARATOR
|
||||
0x001F, //UNIT SEPARATOR
|
||||
0x0020, //SPACE
|
||||
0x0021, //EXCLAMATION MARK
|
||||
0x0022, //QUOTATION MARK
|
||||
0x0023, //NUMBER SIGN
|
||||
0x0024, //DOLLAR SIGN
|
||||
0x0025, //PERCENT SIGN
|
||||
0x0026, //AMPERSAND
|
||||
0x0027, //APOSTROPHE
|
||||
0x0028, //LEFT PARENTHESIS
|
||||
0x0029, //RIGHT PARENTHESIS
|
||||
0x002A, //ASTERISK
|
||||
0x002B, //PLUS SIGN
|
||||
0x002C, //COMMA
|
||||
0x002D, //HYPHEN-MINUS
|
||||
0x002E, //FULL STOP
|
||||
0x002F, //SOLIDUS
|
||||
0x0030, //DIGIT ZERO
|
||||
0x0031, //DIGIT ONE
|
||||
0x0032, //DIGIT TWO
|
||||
0x0033, //DIGIT THREE
|
||||
0x0034, //DIGIT FOUR
|
||||
0x0035, //DIGIT FIVE
|
||||
0x0036, //DIGIT SIX
|
||||
0x0037, //DIGIT SEVEN
|
||||
0x0038, //DIGIT EIGHT
|
||||
0x0039, //DIGIT NINE
|
||||
0x003A, //COLON
|
||||
0x003B, //SEMICOLON
|
||||
0x003C, //LESS-THAN SIGN
|
||||
0x003D, //EQUALS SIGN
|
||||
0x003E, //GREATER-THAN SIGN
|
||||
0x003F, //QUESTION MARK
|
||||
0x0040, //COMMERCIAL AT
|
||||
0x0041, //LATIN CAPITAL LETTER A
|
||||
0x0042, //LATIN CAPITAL LETTER B
|
||||
0x0043, //LATIN CAPITAL LETTER C
|
||||
0x0044, //LATIN CAPITAL LETTER D
|
||||
0x0045, //LATIN CAPITAL LETTER E
|
||||
0x0046, //LATIN CAPITAL LETTER F
|
||||
0x0047, //LATIN CAPITAL LETTER G
|
||||
0x0048, //LATIN CAPITAL LETTER H
|
||||
0x0049, //LATIN CAPITAL LETTER I
|
||||
0x004A, //LATIN CAPITAL LETTER J
|
||||
0x004B, //LATIN CAPITAL LETTER K
|
||||
0x004C, //LATIN CAPITAL LETTER L
|
||||
0x004D, //LATIN CAPITAL LETTER M
|
||||
0x004E, //LATIN CAPITAL LETTER N
|
||||
0x004F, //LATIN CAPITAL LETTER O
|
||||
0x0050, //LATIN CAPITAL LETTER P
|
||||
0x0051, //LATIN CAPITAL LETTER Q
|
||||
0x0052, //LATIN CAPITAL LETTER R
|
||||
0x0053, //LATIN CAPITAL LETTER S
|
||||
0x0054, //LATIN CAPITAL LETTER T
|
||||
0x0055, //LATIN CAPITAL LETTER U
|
||||
0x0056, //LATIN CAPITAL LETTER V
|
||||
0x0057, //LATIN CAPITAL LETTER W
|
||||
0x0058, //LATIN CAPITAL LETTER X
|
||||
0x0059, //LATIN CAPITAL LETTER Y
|
||||
0x005A, //LATIN CAPITAL LETTER Z
|
||||
0x005B, //LEFT SQUARE BRACKET
|
||||
0x005C, //REVERSE SOLIDUS
|
||||
0x005D, //RIGHT SQUARE BRACKET
|
||||
0x005E, //CIRCUMFLEX ACCENT
|
||||
0x005F, //LOW LINE
|
||||
0x0060, //GRAVE ACCENT
|
||||
0x0061, //LATIN SMALL LETTER A
|
||||
0x0062, //LATIN SMALL LETTER B
|
||||
0x0063, //LATIN SMALL LETTER C
|
||||
0x0064, //LATIN SMALL LETTER D
|
||||
0x0065, //LATIN SMALL LETTER E
|
||||
0x0066, //LATIN SMALL LETTER F
|
||||
0x0067, //LATIN SMALL LETTER G
|
||||
0x0068, //LATIN SMALL LETTER H
|
||||
0x0069, //LATIN SMALL LETTER I
|
||||
0x006A, //LATIN SMALL LETTER J
|
||||
0x006B, //LATIN SMALL LETTER K
|
||||
0x006C, //LATIN SMALL LETTER L
|
||||
0x006D, //LATIN SMALL LETTER M
|
||||
0x006E, //LATIN SMALL LETTER N
|
||||
0x006F, //LATIN SMALL LETTER O
|
||||
0x0070, //LATIN SMALL LETTER P
|
||||
0x0071, //LATIN SMALL LETTER Q
|
||||
0x0072, //LATIN SMALL LETTER R
|
||||
0x0073, //LATIN SMALL LETTER S
|
||||
0x0074, //LATIN SMALL LETTER T
|
||||
0x0075, //LATIN SMALL LETTER U
|
||||
0x0076, //LATIN SMALL LETTER V
|
||||
0x0077, //LATIN SMALL LETTER W
|
||||
0x0078, //LATIN SMALL LETTER X
|
||||
0x0079, //LATIN SMALL LETTER Y
|
||||
0x007A, //LATIN SMALL LETTER Z
|
||||
0x007B, //LEFT CURLY BRACKET
|
||||
0x007C, //VERTICAL LINE
|
||||
0x007D, //RIGHT CURLY BRACKET
|
||||
0x007E, //TILDE
|
||||
0x007F, //DELETE
|
||||
0x20AC, //EURO SIGN
|
||||
0x067E, //ARABIC LETTER PEH
|
||||
0x201A, //SINGLE LOW-9 QUOTATION MARK
|
||||
0x0192, //LATIN SMALL LETTER F WITH HOOK
|
||||
0x201E, //DOUBLE LOW-9 QUOTATION MARK
|
||||
0x2026, //HORIZONTAL ELLIPSIS
|
||||
0x2020, //DAGGER
|
||||
0x2021, //DOUBLE DAGGER
|
||||
0x02C6, //MODIFIER LETTER CIRCUMFLEX ACCENT
|
||||
0x2030, //PER MILLE SIGN
|
||||
0x0679, //ARABIC LETTER TTEH
|
||||
0x2039, //SINGLE LEFT-POINTING ANGLE QUOTATION MARK
|
||||
0x0152, //LATIN CAPITAL LIGATURE OE
|
||||
0x0686, //ARABIC LETTER TCHEH
|
||||
0x0698, //ARABIC LETTER JEH
|
||||
0x0688, //ARABIC LETTER DDAL
|
||||
0x06AF, //ARABIC LETTER GAF
|
||||
0x2018, //LEFT SINGLE QUOTATION MARK
|
||||
0x2019, //RIGHT SINGLE QUOTATION MARK
|
||||
0x201C, //LEFT DOUBLE QUOTATION MARK
|
||||
0x201D, //RIGHT DOUBLE QUOTATION MARK
|
||||
0x2022, //BULLET
|
||||
0x2013, //EN DASH
|
||||
0x2014, //EM DASH
|
||||
0x06A9, //ARABIC LETTER KEHEH
|
||||
0x2122, //TRADE MARK SIGN
|
||||
0x0691, //ARABIC LETTER RREH
|
||||
0x203A, //SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
|
||||
0x0153, //LATIN SMALL LIGATURE OE
|
||||
0x200C, //ZERO WIDTH NON-JOINER
|
||||
0x200D, //ZERO WIDTH JOINER
|
||||
0x06BA, //ARABIC LETTER NOON GHUNNA
|
||||
0x00A0, //NO-BREAK SPACE
|
||||
0x060C, //ARABIC COMMA
|
||||
0x00A2, //CENT SIGN
|
||||
0x00A3, //POUND SIGN
|
||||
0x00A4, //CURRENCY SIGN
|
||||
0x00A5, //YEN SIGN
|
||||
0x00A6, //BROKEN BAR
|
||||
0x00A7, //SECTION SIGN
|
||||
0x00A8, //DIAERESIS
|
||||
0x00A9, //COPYRIGHT SIGN
|
||||
0x06BE, //ARABIC LETTER HEH DOACHASHMEE
|
||||
0x00AB, //LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
|
||||
0x00AC, //NOT SIGN
|
||||
0x00AD, //SOFT HYPHEN
|
||||
0x00AE, //REGISTERED SIGN
|
||||
0x00AF, //MACRON
|
||||
0x00B0, //DEGREE SIGN
|
||||
0x00B1, //PLUS-MINUS SIGN
|
||||
0x00B2, //SUPERSCRIPT TWO
|
||||
0x00B3, //SUPERSCRIPT THREE
|
||||
0x00B4, //ACUTE ACCENT
|
||||
0x00B5, //MICRO SIGN
|
||||
0x00B6, //PILCROW SIGN
|
||||
0x00B7, //MIDDLE DOT
|
||||
0x00B8, //CEDILLA
|
||||
0x00B9, //SUPERSCRIPT ONE
|
||||
0x061B, //ARABIC SEMICOLON
|
||||
0x00BB, //RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
|
||||
0x00BC, //VULGAR FRACTION ONE QUARTER
|
||||
0x00BD, //VULGAR FRACTION ONE HALF
|
||||
0x00BE, //VULGAR FRACTION THREE QUARTERS
|
||||
0x061F, //ARABIC QUESTION MARK
|
||||
0x06C1, //ARABIC LETTER HEH GOAL
|
||||
0x0621, //ARABIC LETTER HAMZA
|
||||
0x0622, //ARABIC LETTER ALEF WITH MADDA ABOVE
|
||||
0x0623, //ARABIC LETTER ALEF WITH HAMZA ABOVE
|
||||
0x0624, //ARABIC LETTER WAW WITH HAMZA ABOVE
|
||||
0x0625, //ARABIC LETTER ALEF WITH HAMZA BELOW
|
||||
0x0626, //ARABIC LETTER YEH WITH HAMZA ABOVE
|
||||
0x0627, //ARABIC LETTER ALEF
|
||||
0x0628, //ARABIC LETTER BEH
|
||||
0x0629, //ARABIC LETTER TEH MARBUTA
|
||||
0x062A, //ARABIC LETTER TEH
|
||||
0x062B, //ARABIC LETTER THEH
|
||||
0x062C, //ARABIC LETTER JEEM
|
||||
0x062D, //ARABIC LETTER HAH
|
||||
0x062E, //ARABIC LETTER KHAH
|
||||
0x062F, //ARABIC LETTER DAL
|
||||
0x0630, //ARABIC LETTER THAL
|
||||
0x0631, //ARABIC LETTER REH
|
||||
0x0632, //ARABIC LETTER ZAIN
|
||||
0x0633, //ARABIC LETTER SEEN
|
||||
0x0634, //ARABIC LETTER SHEEN
|
||||
0x0635, //ARABIC LETTER SAD
|
||||
0x0636, //ARABIC LETTER DAD
|
||||
0x00D7, //MULTIPLICATION SIGN
|
||||
0x0637, //ARABIC LETTER TAH
|
||||
0x0638, //ARABIC LETTER ZAH
|
||||
0x0639, //ARABIC LETTER AIN
|
||||
0x063A, //ARABIC LETTER GHAIN
|
||||
0x0640, //ARABIC TATWEEL
|
||||
0x0641, //ARABIC LETTER FEH
|
||||
0x0642, //ARABIC LETTER QAF
|
||||
0x0643, //ARABIC LETTER KAF
|
||||
0x00E0, //LATIN SMALL LETTER A WITH GRAVE
|
||||
0x0644, //ARABIC LETTER LAM
|
||||
0x00E2, //LATIN SMALL LETTER A WITH CIRCUMFLEX
|
||||
0x0645, //ARABIC LETTER MEEM
|
||||
0x0646, //ARABIC LETTER NOON
|
||||
0x0647, //ARABIC LETTER HEH
|
||||
0x0648, //ARABIC LETTER WAW
|
||||
0x00E7, //LATIN SMALL LETTER C WITH CEDILLA
|
||||
0x00E8, //LATIN SMALL LETTER E WITH GRAVE
|
||||
0x00E9, //LATIN SMALL LETTER E WITH ACUTE
|
||||
0x00EA, //LATIN SMALL LETTER E WITH CIRCUMFLEX
|
||||
0x00EB, //LATIN SMALL LETTER E WITH DIAERESIS
|
||||
0x0649, //ARABIC LETTER ALEF MAKSURA
|
||||
0x064A, //ARABIC LETTER YEH
|
||||
0x00EE, //LATIN SMALL LETTER I WITH CIRCUMFLEX
|
||||
0x00EF, //LATIN SMALL LETTER I WITH DIAERESIS
|
||||
0x064B, //ARABIC FATHATAN
|
||||
0x064C, //ARABIC DAMMATAN
|
||||
0x064D, //ARABIC KASRATAN
|
||||
0x064E, //ARABIC FATHA
|
||||
0x00F4, //LATIN SMALL LETTER O WITH CIRCUMFLEX
|
||||
0x064F, //ARABIC DAMMA
|
||||
0x0650, //ARABIC KASRA
|
||||
0x00F7, //DIVISION SIGN
|
||||
0x0651, //ARABIC SHADDA
|
||||
0x00F9, //LATIN SMALL LETTER U WITH GRAVE
|
||||
0x0652, //ARABIC SUKUN
|
||||
0x00FB, //LATIN SMALL LETTER U WITH CIRCUMFLEX
|
||||
0x00FC, //LATIN SMALL LETTER U WITH DIAERESIS
|
||||
0x200E, //LEFT-TO-RIGHT MARK
|
||||
0x200F, //RIGHT-TO-LEFT MARK
|
||||
0x06D2, //ARABIC LETTER YEH BARREE
|
||||
},
|
||||
}
|
|
@ -0,0 +1,262 @@
|
|||
package cp
|
||||
|
||||
var cp1257 *charsetMap = &charsetMap{
|
||||
sb: [256]rune{
|
||||
0x0000, //NULL
|
||||
0x0001, //START OF HEADING
|
||||
0x0002, //START OF TEXT
|
||||
0x0003, //END OF TEXT
|
||||
0x0004, //END OF TRANSMISSION
|
||||
0x0005, //ENQUIRY
|
||||
0x0006, //ACKNOWLEDGE
|
||||
0x0007, //BELL
|
||||
0x0008, //BACKSPACE
|
||||
0x0009, //HORIZONTAL TABULATION
|
||||
0x000A, //LINE FEED
|
||||
0x000B, //VERTICAL TABULATION
|
||||
0x000C, //FORM FEED
|
||||
0x000D, //CARRIAGE RETURN
|
||||
0x000E, //SHIFT OUT
|
||||
0x000F, //SHIFT IN
|
||||
0x0010, //DATA LINK ESCAPE
|
||||
0x0011, //DEVICE CONTROL ONE
|
||||
0x0012, //DEVICE CONTROL TWO
|
||||
0x0013, //DEVICE CONTROL THREE
|
||||
0x0014, //DEVICE CONTROL FOUR
|
||||
0x0015, //NEGATIVE ACKNOWLEDGE
|
||||
0x0016, //SYNCHRONOUS IDLE
|
||||
0x0017, //END OF TRANSMISSION BLOCK
|
||||
0x0018, //CANCEL
|
||||
0x0019, //END OF MEDIUM
|
||||
0x001A, //SUBSTITUTE
|
||||
0x001B, //ESCAPE
|
||||
0x001C, //FILE SEPARATOR
|
||||
0x001D, //GROUP SEPARATOR
|
||||
0x001E, //RECORD SEPARATOR
|
||||
0x001F, //UNIT SEPARATOR
|
||||
0x0020, //SPACE
|
||||
0x0021, //EXCLAMATION MARK
|
||||
0x0022, //QUOTATION MARK
|
||||
0x0023, //NUMBER SIGN
|
||||
0x0024, //DOLLAR SIGN
|
||||
0x0025, //PERCENT SIGN
|
||||
0x0026, //AMPERSAND
|
||||
0x0027, //APOSTROPHE
|
||||
0x0028, //LEFT PARENTHESIS
|
||||
0x0029, //RIGHT PARENTHESIS
|
||||
0x002A, //ASTERISK
|
||||
0x002B, //PLUS SIGN
|
||||
0x002C, //COMMA
|
||||
0x002D, //HYPHEN-MINUS
|
||||
0x002E, //FULL STOP
|
||||
0x002F, //SOLIDUS
|
||||
0x0030, //DIGIT ZERO
|
||||
0x0031, //DIGIT ONE
|
||||
0x0032, //DIGIT TWO
|
||||
0x0033, //DIGIT THREE
|
||||
0x0034, //DIGIT FOUR
|
||||
0x0035, //DIGIT FIVE
|
||||
0x0036, //DIGIT SIX
|
||||
0x0037, //DIGIT SEVEN
|
||||
0x0038, //DIGIT EIGHT
|
||||
0x0039, //DIGIT NINE
|
||||
0x003A, //COLON
|
||||
0x003B, //SEMICOLON
|
||||
0x003C, //LESS-THAN SIGN
|
||||
0x003D, //EQUALS SIGN
|
||||
0x003E, //GREATER-THAN SIGN
|
||||
0x003F, //QUESTION MARK
|
||||
0x0040, //COMMERCIAL AT
|
||||
0x0041, //LATIN CAPITAL LETTER A
|
||||
0x0042, //LATIN CAPITAL LETTER B
|
||||
0x0043, //LATIN CAPITAL LETTER C
|
||||
0x0044, //LATIN CAPITAL LETTER D
|
||||
0x0045, //LATIN CAPITAL LETTER E
|
||||
0x0046, //LATIN CAPITAL LETTER F
|
||||
0x0047, //LATIN CAPITAL LETTER G
|
||||
0x0048, //LATIN CAPITAL LETTER H
|
||||
0x0049, //LATIN CAPITAL LETTER I
|
||||
0x004A, //LATIN CAPITAL LETTER J
|
||||
0x004B, //LATIN CAPITAL LETTER K
|
||||
0x004C, //LATIN CAPITAL LETTER L
|
||||
0x004D, //LATIN CAPITAL LETTER M
|
||||
0x004E, //LATIN CAPITAL LETTER N
|
||||
0x004F, //LATIN CAPITAL LETTER O
|
||||
0x0050, //LATIN CAPITAL LETTER P
|
||||
0x0051, //LATIN CAPITAL LETTER Q
|
||||
0x0052, //LATIN CAPITAL LETTER R
|
||||
0x0053, //LATIN CAPITAL LETTER S
|
||||
0x0054, //LATIN CAPITAL LETTER T
|
||||
0x0055, //LATIN CAPITAL LETTER U
|
||||
0x0056, //LATIN CAPITAL LETTER V
|
||||
0x0057, //LATIN CAPITAL LETTER W
|
||||
0x0058, //LATIN CAPITAL LETTER X
|
||||
0x0059, //LATIN CAPITAL LETTER Y
|
||||
0x005A, //LATIN CAPITAL LETTER Z
|
||||
0x005B, //LEFT SQUARE BRACKET
|
||||
0x005C, //REVERSE SOLIDUS
|
||||
0x005D, //RIGHT SQUARE BRACKET
|
||||
0x005E, //CIRCUMFLEX ACCENT
|
||||
0x005F, //LOW LINE
|
||||
0x0060, //GRAVE ACCENT
|
||||
0x0061, //LATIN SMALL LETTER A
|
||||
0x0062, //LATIN SMALL LETTER B
|
||||
0x0063, //LATIN SMALL LETTER C
|
||||
0x0064, //LATIN SMALL LETTER D
|
||||
0x0065, //LATIN SMALL LETTER E
|
||||
0x0066, //LATIN SMALL LETTER F
|
||||
0x0067, //LATIN SMALL LETTER G
|
||||
0x0068, //LATIN SMALL LETTER H
|
||||
0x0069, //LATIN SMALL LETTER I
|
||||
0x006A, //LATIN SMALL LETTER J
|
||||
0x006B, //LATIN SMALL LETTER K
|
||||
0x006C, //LATIN SMALL LETTER L
|
||||
0x006D, //LATIN SMALL LETTER M
|
||||
0x006E, //LATIN SMALL LETTER N
|
||||
0x006F, //LATIN SMALL LETTER O
|
||||
0x0070, //LATIN SMALL LETTER P
|
||||
0x0071, //LATIN SMALL LETTER Q
|
||||
0x0072, //LATIN SMALL LETTER R
|
||||
0x0073, //LATIN SMALL LETTER S
|
||||
0x0074, //LATIN SMALL LETTER T
|
||||
0x0075, //LATIN SMALL LETTER U
|
||||
0x0076, //LATIN SMALL LETTER V
|
||||
0x0077, //LATIN SMALL LETTER W
|
||||
0x0078, //LATIN SMALL LETTER X
|
||||
0x0079, //LATIN SMALL LETTER Y
|
||||
0x007A, //LATIN SMALL LETTER Z
|
||||
0x007B, //LEFT CURLY BRACKET
|
||||
0x007C, //VERTICAL LINE
|
||||
0x007D, //RIGHT CURLY BRACKET
|
||||
0x007E, //TILDE
|
||||
0x007F, //DELETE
|
||||
0x20AC, //EURO SIGN
|
||||
0xFFFD, //UNDEFINED
|
||||
0x201A, //SINGLE LOW-9 QUOTATION MARK
|
||||
0xFFFD, //UNDEFINED
|
||||
0x201E, //DOUBLE LOW-9 QUOTATION MARK
|
||||
0x2026, //HORIZONTAL ELLIPSIS
|
||||
0x2020, //DAGGER
|
||||
0x2021, //DOUBLE DAGGER
|
||||
0xFFFD, //UNDEFINED
|
||||
0x2030, //PER MILLE SIGN
|
||||
0xFFFD, //UNDEFINED
|
||||
0x2039, //SINGLE LEFT-POINTING ANGLE QUOTATION MARK
|
||||
0xFFFD, //UNDEFINED
|
||||
0x00A8, //DIAERESIS
|
||||
0x02C7, //CARON
|
||||
0x00B8, //CEDILLA
|
||||
0xFFFD, //UNDEFINED
|
||||
0x2018, //LEFT SINGLE QUOTATION MARK
|
||||
0x2019, //RIGHT SINGLE QUOTATION MARK
|
||||
0x201C, //LEFT DOUBLE QUOTATION MARK
|
||||
0x201D, //RIGHT DOUBLE QUOTATION MARK
|
||||
0x2022, //BULLET
|
||||
0x2013, //EN DASH
|
||||
0x2014, //EM DASH
|
||||
0xFFFD, //UNDEFINED
|
||||
0x2122, //TRADE MARK SIGN
|
||||
0xFFFD, //UNDEFINED
|
||||
0x203A, //SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
|
||||
0xFFFD, //UNDEFINED
|
||||
0x00AF, //MACRON
|
||||
0x02DB, //OGONEK
|
||||
0xFFFD, //UNDEFINED
|
||||
0x00A0, //NO-BREAK SPACE
|
||||
0xFFFD, //UNDEFINED
|
||||
0x00A2, //CENT SIGN
|
||||
0x00A3, //POUND SIGN
|
||||
0x00A4, //CURRENCY SIGN
|
||||
0xFFFD, //UNDEFINED
|
||||
0x00A6, //BROKEN BAR
|
||||
0x00A7, //SECTION SIGN
|
||||
0x00D8, //LATIN CAPITAL LETTER O WITH STROKE
|
||||
0x00A9, //COPYRIGHT SIGN
|
||||
0x0156, //LATIN CAPITAL LETTER R WITH CEDILLA
|
||||
0x00AB, //LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
|
||||
0x00AC, //NOT SIGN
|
||||
0x00AD, //SOFT HYPHEN
|
||||
0x00AE, //REGISTERED SIGN
|
||||
0x00C6, //LATIN CAPITAL LETTER AE
|
||||
0x00B0, //DEGREE SIGN
|
||||
0x00B1, //PLUS-MINUS SIGN
|
||||
0x00B2, //SUPERSCRIPT TWO
|
||||
0x00B3, //SUPERSCRIPT THREE
|
||||
0x00B4, //ACUTE ACCENT
|
||||
0x00B5, //MICRO SIGN
|
||||
0x00B6, //PILCROW SIGN
|
||||
0x00B7, //MIDDLE DOT
|
||||
0x00F8, //LATIN SMALL LETTER O WITH STROKE
|
||||
0x00B9, //SUPERSCRIPT ONE
|
||||
0x0157, //LATIN SMALL LETTER R WITH CEDILLA
|
||||
0x00BB, //RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
|
||||
0x00BC, //VULGAR FRACTION ONE QUARTER
|
||||
0x00BD, //VULGAR FRACTION ONE HALF
|
||||
0x00BE, //VULGAR FRACTION THREE QUARTERS
|
||||
0x00E6, //LATIN SMALL LETTER AE
|
||||
0x0104, //LATIN CAPITAL LETTER A WITH OGONEK
|
||||
0x012E, //LATIN CAPITAL LETTER I WITH OGONEK
|
||||
0x0100, //LATIN CAPITAL LETTER A WITH MACRON
|
||||
0x0106, //LATIN CAPITAL LETTER C WITH ACUTE
|
||||
0x00C4, //LATIN CAPITAL LETTER A WITH DIAERESIS
|
||||
0x00C5, //LATIN CAPITAL LETTER A WITH RING ABOVE
|
||||
0x0118, //LATIN CAPITAL LETTER E WITH OGONEK
|
||||
0x0112, //LATIN CAPITAL LETTER E WITH MACRON
|
||||
0x010C, //LATIN CAPITAL LETTER C WITH CARON
|
||||
0x00C9, //LATIN CAPITAL LETTER E WITH ACUTE
|
||||
0x0179, //LATIN CAPITAL LETTER Z WITH ACUTE
|
||||
0x0116, //LATIN CAPITAL LETTER E WITH DOT ABOVE
|
||||
0x0122, //LATIN CAPITAL LETTER G WITH CEDILLA
|
||||
0x0136, //LATIN CAPITAL LETTER K WITH CEDILLA
|
||||
0x012A, //LATIN CAPITAL LETTER I WITH MACRON
|
||||
0x013B, //LATIN CAPITAL LETTER L WITH CEDILLA
|
||||
0x0160, //LATIN CAPITAL LETTER S WITH CARON
|
||||
0x0143, //LATIN CAPITAL LETTER N WITH ACUTE
|
||||
0x0145, //LATIN CAPITAL LETTER N WITH CEDILLA
|
||||
0x00D3, //LATIN CAPITAL LETTER O WITH ACUTE
|
||||
0x014C, //LATIN CAPITAL LETTER O WITH MACRON
|
||||
0x00D5, //LATIN CAPITAL LETTER O WITH TILDE
|
||||
0x00D6, //LATIN CAPITAL LETTER O WITH DIAERESIS
|
||||
0x00D7, //MULTIPLICATION SIGN
|
||||
0x0172, //LATIN CAPITAL LETTER U WITH OGONEK
|
||||
0x0141, //LATIN CAPITAL LETTER L WITH STROKE
|
||||
0x015A, //LATIN CAPITAL LETTER S WITH ACUTE
|
||||
0x016A, //LATIN CAPITAL LETTER U WITH MACRON
|
||||
0x00DC, //LATIN CAPITAL LETTER U WITH DIAERESIS
|
||||
0x017B, //LATIN CAPITAL LETTER Z WITH DOT ABOVE
|
||||
0x017D, //LATIN CAPITAL LETTER Z WITH CARON
|
||||
0x00DF, //LATIN SMALL LETTER SHARP S
|
||||
0x0105, //LATIN SMALL LETTER A WITH OGONEK
|
||||
0x012F, //LATIN SMALL LETTER I WITH OGONEK
|
||||
0x0101, //LATIN SMALL LETTER A WITH MACRON
|
||||
0x0107, //LATIN SMALL LETTER C WITH ACUTE
|
||||
0x00E4, //LATIN SMALL LETTER A WITH DIAERESIS
|
||||
0x00E5, //LATIN SMALL LETTER A WITH RING ABOVE
|
||||
0x0119, //LATIN SMALL LETTER E WITH OGONEK
|
||||
0x0113, //LATIN SMALL LETTER E WITH MACRON
|
||||
0x010D, //LATIN SMALL LETTER C WITH CARON
|
||||
0x00E9, //LATIN SMALL LETTER E WITH ACUTE
|
||||
0x017A, //LATIN SMALL LETTER Z WITH ACUTE
|
||||
0x0117, //LATIN SMALL LETTER E WITH DOT ABOVE
|
||||
0x0123, //LATIN SMALL LETTER G WITH CEDILLA
|
||||
0x0137, //LATIN SMALL LETTER K WITH CEDILLA
|
||||
0x012B, //LATIN SMALL LETTER I WITH MACRON
|
||||
0x013C, //LATIN SMALL LETTER L WITH CEDILLA
|
||||
0x0161, //LATIN SMALL LETTER S WITH CARON
|
||||
0x0144, //LATIN SMALL LETTER N WITH ACUTE
|
||||
0x0146, //LATIN SMALL LETTER N WITH CEDILLA
|
||||
0x00F3, //LATIN SMALL LETTER O WITH ACUTE
|
||||
0x014D, //LATIN SMALL LETTER O WITH MACRON
|
||||
0x00F5, //LATIN SMALL LETTER O WITH TILDE
|
||||
0x00F6, //LATIN SMALL LETTER O WITH DIAERESIS
|
||||
0x00F7, //DIVISION SIGN
|
||||
0x0173, //LATIN SMALL LETTER U WITH OGONEK
|
||||
0x0142, //LATIN SMALL LETTER L WITH STROKE
|
||||
0x015B, //LATIN SMALL LETTER S WITH ACUTE
|
||||
0x016B, //LATIN SMALL LETTER U WITH MACRON
|
||||
0x00FC, //LATIN SMALL LETTER U WITH DIAERESIS
|
||||
0x017C, //LATIN SMALL LETTER Z WITH DOT ABOVE
|
||||
0x017E, //LATIN SMALL LETTER Z WITH CARON
|
||||
0x02D9, //DOT ABOVE
|
||||
},
|
||||
}
|
|
@ -0,0 +1,262 @@
|
|||
package cp
|
||||
|
||||
var cp1258 *charsetMap = &charsetMap{
|
||||
sb: [256]rune{
|
||||
0x0000, //NULL
|
||||
0x0001, //START OF HEADING
|
||||
0x0002, //START OF TEXT
|
||||
0x0003, //END OF TEXT
|
||||
0x0004, //END OF TRANSMISSION
|
||||
0x0005, //ENQUIRY
|
||||
0x0006, //ACKNOWLEDGE
|
||||
0x0007, //BELL
|
||||
0x0008, //BACKSPACE
|
||||
0x0009, //HORIZONTAL TABULATION
|
||||
0x000A, //LINE FEED
|
||||
0x000B, //VERTICAL TABULATION
|
||||
0x000C, //FORM FEED
|
||||
0x000D, //CARRIAGE RETURN
|
||||
0x000E, //SHIFT OUT
|
||||
0x000F, //SHIFT IN
|
||||
0x0010, //DATA LINK ESCAPE
|
||||
0x0011, //DEVICE CONTROL ONE
|
||||
0x0012, //DEVICE CONTROL TWO
|
||||
0x0013, //DEVICE CONTROL THREE
|
||||
0x0014, //DEVICE CONTROL FOUR
|
||||
0x0015, //NEGATIVE ACKNOWLEDGE
|
||||
0x0016, //SYNCHRONOUS IDLE
|
||||
0x0017, //END OF TRANSMISSION BLOCK
|
||||
0x0018, //CANCEL
|
||||
0x0019, //END OF MEDIUM
|
||||
0x001A, //SUBSTITUTE
|
||||
0x001B, //ESCAPE
|
||||
0x001C, //FILE SEPARATOR
|
||||
0x001D, //GROUP SEPARATOR
|
||||
0x001E, //RECORD SEPARATOR
|
||||
0x001F, //UNIT SEPARATOR
|
||||
0x0020, //SPACE
|
||||
0x0021, //EXCLAMATION MARK
|
||||
0x0022, //QUOTATION MARK
|
||||
0x0023, //NUMBER SIGN
|
||||
0x0024, //DOLLAR SIGN
|
||||
0x0025, //PERCENT SIGN
|
||||
0x0026, //AMPERSAND
|
||||
0x0027, //APOSTROPHE
|
||||
0x0028, //LEFT PARENTHESIS
|
||||
0x0029, //RIGHT PARENTHESIS
|
||||
0x002A, //ASTERISK
|
||||
0x002B, //PLUS SIGN
|
||||
0x002C, //COMMA
|
||||
0x002D, //HYPHEN-MINUS
|
||||
0x002E, //FULL STOP
|
||||
0x002F, //SOLIDUS
|
||||
0x0030, //DIGIT ZERO
|
||||
0x0031, //DIGIT ONE
|
||||
0x0032, //DIGIT TWO
|
||||
0x0033, //DIGIT THREE
|
||||
0x0034, //DIGIT FOUR
|
||||
0x0035, //DIGIT FIVE
|
||||
0x0036, //DIGIT SIX
|
||||
0x0037, //DIGIT SEVEN
|
||||
0x0038, //DIGIT EIGHT
|
||||
0x0039, //DIGIT NINE
|
||||
0x003A, //COLON
|
||||
0x003B, //SEMICOLON
|
||||
0x003C, //LESS-THAN SIGN
|
||||
0x003D, //EQUALS SIGN
|
||||
0x003E, //GREATER-THAN SIGN
|
||||
0x003F, //QUESTION MARK
|
||||
0x0040, //COMMERCIAL AT
|
||||
0x0041, //LATIN CAPITAL LETTER A
|
||||
0x0042, //LATIN CAPITAL LETTER B
|
||||
0x0043, //LATIN CAPITAL LETTER C
|
||||
0x0044, //LATIN CAPITAL LETTER D
|
||||
0x0045, //LATIN CAPITAL LETTER E
|
||||
0x0046, //LATIN CAPITAL LETTER F
|
||||
0x0047, //LATIN CAPITAL LETTER G
|
||||
0x0048, //LATIN CAPITAL LETTER H
|
||||
0x0049, //LATIN CAPITAL LETTER I
|
||||
0x004A, //LATIN CAPITAL LETTER J
|
||||
0x004B, //LATIN CAPITAL LETTER K
|
||||
0x004C, //LATIN CAPITAL LETTER L
|
||||
0x004D, //LATIN CAPITAL LETTER M
|
||||
0x004E, //LATIN CAPITAL LETTER N
|
||||
0x004F, //LATIN CAPITAL LETTER O
|
||||
0x0050, //LATIN CAPITAL LETTER P
|
||||
0x0051, //LATIN CAPITAL LETTER Q
|
||||
0x0052, //LATIN CAPITAL LETTER R
|
||||
0x0053, //LATIN CAPITAL LETTER S
|
||||
0x0054, //LATIN CAPITAL LETTER T
|
||||
0x0055, //LATIN CAPITAL LETTER U
|
||||
0x0056, //LATIN CAPITAL LETTER V
|
||||
0x0057, //LATIN CAPITAL LETTER W
|
||||
0x0058, //LATIN CAPITAL LETTER X
|
||||
0x0059, //LATIN CAPITAL LETTER Y
|
||||
0x005A, //LATIN CAPITAL LETTER Z
|
||||
0x005B, //LEFT SQUARE BRACKET
|
||||
0x005C, //REVERSE SOLIDUS
|
||||
0x005D, //RIGHT SQUARE BRACKET
|
||||
0x005E, //CIRCUMFLEX ACCENT
|
||||
0x005F, //LOW LINE
|
||||
0x0060, //GRAVE ACCENT
|
||||
0x0061, //LATIN SMALL LETTER A
|
||||
0x0062, //LATIN SMALL LETTER B
|
||||
0x0063, //LATIN SMALL LETTER C
|
||||
0x0064, //LATIN SMALL LETTER D
|
||||
0x0065, //LATIN SMALL LETTER E
|
||||
0x0066, //LATIN SMALL LETTER F
|
||||
0x0067, //LATIN SMALL LETTER G
|
||||
0x0068, //LATIN SMALL LETTER H
|
||||
0x0069, //LATIN SMALL LETTER I
|
||||
0x006A, //LATIN SMALL LETTER J
|
||||
0x006B, //LATIN SMALL LETTER K
|
||||
0x006C, //LATIN SMALL LETTER L
|
||||
0x006D, //LATIN SMALL LETTER M
|
||||
0x006E, //LATIN SMALL LETTER N
|
||||
0x006F, //LATIN SMALL LETTER O
|
||||
0x0070, //LATIN SMALL LETTER P
|
||||
0x0071, //LATIN SMALL LETTER Q
|
||||
0x0072, //LATIN SMALL LETTER R
|
||||
0x0073, //LATIN SMALL LETTER S
|
||||
0x0074, //LATIN SMALL LETTER T
|
||||
0x0075, //LATIN SMALL LETTER U
|
||||
0x0076, //LATIN SMALL LETTER V
|
||||
0x0077, //LATIN SMALL LETTER W
|
||||
0x0078, //LATIN SMALL LETTER X
|
||||
0x0079, //LATIN SMALL LETTER Y
|
||||
0x007A, //LATIN SMALL LETTER Z
|
||||
0x007B, //LEFT CURLY BRACKET
|
||||
0x007C, //VERTICAL LINE
|
||||
0x007D, //RIGHT CURLY BRACKET
|
||||
0x007E, //TILDE
|
||||
0x007F, //DELETE
|
||||
0x20AC, //EURO SIGN
|
||||
0xFFFD, //UNDEFINED
|
||||
0x201A, //SINGLE LOW-9 QUOTATION MARK
|
||||
0x0192, //LATIN SMALL LETTER F WITH HOOK
|
||||
0x201E, //DOUBLE LOW-9 QUOTATION MARK
|
||||
0x2026, //HORIZONTAL ELLIPSIS
|
||||
0x2020, //DAGGER
|
||||
0x2021, //DOUBLE DAGGER
|
||||
0x02C6, //MODIFIER LETTER CIRCUMFLEX ACCENT
|
||||
0x2030, //PER MILLE SIGN
|
||||
0xFFFD, //UNDEFINED
|
||||
0x2039, //SINGLE LEFT-POINTING ANGLE QUOTATION MARK
|
||||
0x0152, //LATIN CAPITAL LIGATURE OE
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0x2018, //LEFT SINGLE QUOTATION MARK
|
||||
0x2019, //RIGHT SINGLE QUOTATION MARK
|
||||
0x201C, //LEFT DOUBLE QUOTATION MARK
|
||||
0x201D, //RIGHT DOUBLE QUOTATION MARK
|
||||
0x2022, //BULLET
|
||||
0x2013, //EN DASH
|
||||
0x2014, //EM DASH
|
||||
0x02DC, //SMALL TILDE
|
||||
0x2122, //TRADE MARK SIGN
|
||||
0xFFFD, //UNDEFINED
|
||||
0x203A, //SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
|
||||
0x0153, //LATIN SMALL LIGATURE OE
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0x0178, //LATIN CAPITAL LETTER Y WITH DIAERESIS
|
||||
0x00A0, //NO-BREAK SPACE
|
||||
0x00A1, //INVERTED EXCLAMATION MARK
|
||||
0x00A2, //CENT SIGN
|
||||
0x00A3, //POUND SIGN
|
||||
0x00A4, //CURRENCY SIGN
|
||||
0x00A5, //YEN SIGN
|
||||
0x00A6, //BROKEN BAR
|
||||
0x00A7, //SECTION SIGN
|
||||
0x00A8, //DIAERESIS
|
||||
0x00A9, //COPYRIGHT SIGN
|
||||
0x00AA, //FEMININE ORDINAL INDICATOR
|
||||
0x00AB, //LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
|
||||
0x00AC, //NOT SIGN
|
||||
0x00AD, //SOFT HYPHEN
|
||||
0x00AE, //REGISTERED SIGN
|
||||
0x00AF, //MACRON
|
||||
0x00B0, //DEGREE SIGN
|
||||
0x00B1, //PLUS-MINUS SIGN
|
||||
0x00B2, //SUPERSCRIPT TWO
|
||||
0x00B3, //SUPERSCRIPT THREE
|
||||
0x00B4, //ACUTE ACCENT
|
||||
0x00B5, //MICRO SIGN
|
||||
0x00B6, //PILCROW SIGN
|
||||
0x00B7, //MIDDLE DOT
|
||||
0x00B8, //CEDILLA
|
||||
0x00B9, //SUPERSCRIPT ONE
|
||||
0x00BA, //MASCULINE ORDINAL INDICATOR
|
||||
0x00BB, //RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
|
||||
0x00BC, //VULGAR FRACTION ONE QUARTER
|
||||
0x00BD, //VULGAR FRACTION ONE HALF
|
||||
0x00BE, //VULGAR FRACTION THREE QUARTERS
|
||||
0x00BF, //INVERTED QUESTION MARK
|
||||
0x00C0, //LATIN CAPITAL LETTER A WITH GRAVE
|
||||
0x00C1, //LATIN CAPITAL LETTER A WITH ACUTE
|
||||
0x00C2, //LATIN CAPITAL LETTER A WITH CIRCUMFLEX
|
||||
0x0102, //LATIN CAPITAL LETTER A WITH BREVE
|
||||
0x00C4, //LATIN CAPITAL LETTER A WITH DIAERESIS
|
||||
0x00C5, //LATIN CAPITAL LETTER A WITH RING ABOVE
|
||||
0x00C6, //LATIN CAPITAL LETTER AE
|
||||
0x00C7, //LATIN CAPITAL LETTER C WITH CEDILLA
|
||||
0x00C8, //LATIN CAPITAL LETTER E WITH GRAVE
|
||||
0x00C9, //LATIN CAPITAL LETTER E WITH ACUTE
|
||||
0x00CA, //LATIN CAPITAL LETTER E WITH CIRCUMFLEX
|
||||
0x00CB, //LATIN CAPITAL LETTER E WITH DIAERESIS
|
||||
0x0300, //COMBINING GRAVE ACCENT
|
||||
0x00CD, //LATIN CAPITAL LETTER I WITH ACUTE
|
||||
0x00CE, //LATIN CAPITAL LETTER I WITH CIRCUMFLEX
|
||||
0x00CF, //LATIN CAPITAL LETTER I WITH DIAERESIS
|
||||
0x0110, //LATIN CAPITAL LETTER D WITH STROKE
|
||||
0x00D1, //LATIN CAPITAL LETTER N WITH TILDE
|
||||
0x0309, //COMBINING HOOK ABOVE
|
||||
0x00D3, //LATIN CAPITAL LETTER O WITH ACUTE
|
||||
0x00D4, //LATIN CAPITAL LETTER O WITH CIRCUMFLEX
|
||||
0x01A0, //LATIN CAPITAL LETTER O WITH HORN
|
||||
0x00D6, //LATIN CAPITAL LETTER O WITH DIAERESIS
|
||||
0x00D7, //MULTIPLICATION SIGN
|
||||
0x00D8, //LATIN CAPITAL LETTER O WITH STROKE
|
||||
0x00D9, //LATIN CAPITAL LETTER U WITH GRAVE
|
||||
0x00DA, //LATIN CAPITAL LETTER U WITH ACUTE
|
||||
0x00DB, //LATIN CAPITAL LETTER U WITH CIRCUMFLEX
|
||||
0x00DC, //LATIN CAPITAL LETTER U WITH DIAERESIS
|
||||
0x01AF, //LATIN CAPITAL LETTER U WITH HORN
|
||||
0x0303, //COMBINING TILDE
|
||||
0x00DF, //LATIN SMALL LETTER SHARP S
|
||||
0x00E0, //LATIN SMALL LETTER A WITH GRAVE
|
||||
0x00E1, //LATIN SMALL LETTER A WITH ACUTE
|
||||
0x00E2, //LATIN SMALL LETTER A WITH CIRCUMFLEX
|
||||
0x0103, //LATIN SMALL LETTER A WITH BREVE
|
||||
0x00E4, //LATIN SMALL LETTER A WITH DIAERESIS
|
||||
0x00E5, //LATIN SMALL LETTER A WITH RING ABOVE
|
||||
0x00E6, //LATIN SMALL LETTER AE
|
||||
0x00E7, //LATIN SMALL LETTER C WITH CEDILLA
|
||||
0x00E8, //LATIN SMALL LETTER E WITH GRAVE
|
||||
0x00E9, //LATIN SMALL LETTER E WITH ACUTE
|
||||
0x00EA, //LATIN SMALL LETTER E WITH CIRCUMFLEX
|
||||
0x00EB, //LATIN SMALL LETTER E WITH DIAERESIS
|
||||
0x0301, //COMBINING ACUTE ACCENT
|
||||
0x00ED, //LATIN SMALL LETTER I WITH ACUTE
|
||||
0x00EE, //LATIN SMALL LETTER I WITH CIRCUMFLEX
|
||||
0x00EF, //LATIN SMALL LETTER I WITH DIAERESIS
|
||||
0x0111, //LATIN SMALL LETTER D WITH STROKE
|
||||
0x00F1, //LATIN SMALL LETTER N WITH TILDE
|
||||
0x0323, //COMBINING DOT BELOW
|
||||
0x00F3, //LATIN SMALL LETTER O WITH ACUTE
|
||||
0x00F4, //LATIN SMALL LETTER O WITH CIRCUMFLEX
|
||||
0x01A1, //LATIN SMALL LETTER O WITH HORN
|
||||
0x00F6, //LATIN SMALL LETTER O WITH DIAERESIS
|
||||
0x00F7, //DIVISION SIGN
|
||||
0x00F8, //LATIN SMALL LETTER O WITH STROKE
|
||||
0x00F9, //LATIN SMALL LETTER U WITH GRAVE
|
||||
0x00FA, //LATIN SMALL LETTER U WITH ACUTE
|
||||
0x00FB, //LATIN SMALL LETTER U WITH CIRCUMFLEX
|
||||
0x00FC, //LATIN SMALL LETTER U WITH DIAERESIS
|
||||
0x01B0, //LATIN SMALL LETTER U WITH HORN
|
||||
0x20AB, //DONG SIGN
|
||||
0x00FF, //LATIN SMALL LETTER Y WITH DIAERESIS
|
||||
},
|
||||
}
|
|
@ -0,0 +1,262 @@
|
|||
package cp
|
||||
|
||||
var cp437 *charsetMap = &charsetMap{
|
||||
sb: [256]rune{
|
||||
0x0000, //NULL
|
||||
0x0001, //START OF HEADING
|
||||
0x0002, //START OF TEXT
|
||||
0x0003, //END OF TEXT
|
||||
0x0004, //END OF TRANSMISSION
|
||||
0x0005, //ENQUIRY
|
||||
0x0006, //ACKNOWLEDGE
|
||||
0x0007, //BELL
|
||||
0x0008, //BACKSPACE
|
||||
0x0009, //HORIZONTAL TABULATION
|
||||
0x000a, //LINE FEED
|
||||
0x000b, //VERTICAL TABULATION
|
||||
0x000c, //FORM FEED
|
||||
0x000d, //CARRIAGE RETURN
|
||||
0x000e, //SHIFT OUT
|
||||
0x000f, //SHIFT IN
|
||||
0x0010, //DATA LINK ESCAPE
|
||||
0x0011, //DEVICE CONTROL ONE
|
||||
0x0012, //DEVICE CONTROL TWO
|
||||
0x0013, //DEVICE CONTROL THREE
|
||||
0x0014, //DEVICE CONTROL FOUR
|
||||
0x0015, //NEGATIVE ACKNOWLEDGE
|
||||
0x0016, //SYNCHRONOUS IDLE
|
||||
0x0017, //END OF TRANSMISSION BLOCK
|
||||
0x0018, //CANCEL
|
||||
0x0019, //END OF MEDIUM
|
||||
0x001a, //SUBSTITUTE
|
||||
0x001b, //ESCAPE
|
||||
0x001c, //FILE SEPARATOR
|
||||
0x001d, //GROUP SEPARATOR
|
||||
0x001e, //RECORD SEPARATOR
|
||||
0x001f, //UNIT SEPARATOR
|
||||
0x0020, //SPACE
|
||||
0x0021, //EXCLAMATION MARK
|
||||
0x0022, //QUOTATION MARK
|
||||
0x0023, //NUMBER SIGN
|
||||
0x0024, //DOLLAR SIGN
|
||||
0x0025, //PERCENT SIGN
|
||||
0x0026, //AMPERSAND
|
||||
0x0027, //APOSTROPHE
|
||||
0x0028, //LEFT PARENTHESIS
|
||||
0x0029, //RIGHT PARENTHESIS
|
||||
0x002a, //ASTERISK
|
||||
0x002b, //PLUS SIGN
|
||||
0x002c, //COMMA
|
||||
0x002d, //HYPHEN-MINUS
|
||||
0x002e, //FULL STOP
|
||||
0x002f, //SOLIDUS
|
||||
0x0030, //DIGIT ZERO
|
||||
0x0031, //DIGIT ONE
|
||||
0x0032, //DIGIT TWO
|
||||
0x0033, //DIGIT THREE
|
||||
0x0034, //DIGIT FOUR
|
||||
0x0035, //DIGIT FIVE
|
||||
0x0036, //DIGIT SIX
|
||||
0x0037, //DIGIT SEVEN
|
||||
0x0038, //DIGIT EIGHT
|
||||
0x0039, //DIGIT NINE
|
||||
0x003a, //COLON
|
||||
0x003b, //SEMICOLON
|
||||
0x003c, //LESS-THAN SIGN
|
||||
0x003d, //EQUALS SIGN
|
||||
0x003e, //GREATER-THAN SIGN
|
||||
0x003f, //QUESTION MARK
|
||||
0x0040, //COMMERCIAL AT
|
||||
0x0041, //LATIN CAPITAL LETTER A
|
||||
0x0042, //LATIN CAPITAL LETTER B
|
||||
0x0043, //LATIN CAPITAL LETTER C
|
||||
0x0044, //LATIN CAPITAL LETTER D
|
||||
0x0045, //LATIN CAPITAL LETTER E
|
||||
0x0046, //LATIN CAPITAL LETTER F
|
||||
0x0047, //LATIN CAPITAL LETTER G
|
||||
0x0048, //LATIN CAPITAL LETTER H
|
||||
0x0049, //LATIN CAPITAL LETTER I
|
||||
0x004a, //LATIN CAPITAL LETTER J
|
||||
0x004b, //LATIN CAPITAL LETTER K
|
||||
0x004c, //LATIN CAPITAL LETTER L
|
||||
0x004d, //LATIN CAPITAL LETTER M
|
||||
0x004e, //LATIN CAPITAL LETTER N
|
||||
0x004f, //LATIN CAPITAL LETTER O
|
||||
0x0050, //LATIN CAPITAL LETTER P
|
||||
0x0051, //LATIN CAPITAL LETTER Q
|
||||
0x0052, //LATIN CAPITAL LETTER R
|
||||
0x0053, //LATIN CAPITAL LETTER S
|
||||
0x0054, //LATIN CAPITAL LETTER T
|
||||
0x0055, //LATIN CAPITAL LETTER U
|
||||
0x0056, //LATIN CAPITAL LETTER V
|
||||
0x0057, //LATIN CAPITAL LETTER W
|
||||
0x0058, //LATIN CAPITAL LETTER X
|
||||
0x0059, //LATIN CAPITAL LETTER Y
|
||||
0x005a, //LATIN CAPITAL LETTER Z
|
||||
0x005b, //LEFT SQUARE BRACKET
|
||||
0x005c, //REVERSE SOLIDUS
|
||||
0x005d, //RIGHT SQUARE BRACKET
|
||||
0x005e, //CIRCUMFLEX ACCENT
|
||||
0x005f, //LOW LINE
|
||||
0x0060, //GRAVE ACCENT
|
||||
0x0061, //LATIN SMALL LETTER A
|
||||
0x0062, //LATIN SMALL LETTER B
|
||||
0x0063, //LATIN SMALL LETTER C
|
||||
0x0064, //LATIN SMALL LETTER D
|
||||
0x0065, //LATIN SMALL LETTER E
|
||||
0x0066, //LATIN SMALL LETTER F
|
||||
0x0067, //LATIN SMALL LETTER G
|
||||
0x0068, //LATIN SMALL LETTER H
|
||||
0x0069, //LATIN SMALL LETTER I
|
||||
0x006a, //LATIN SMALL LETTER J
|
||||
0x006b, //LATIN SMALL LETTER K
|
||||
0x006c, //LATIN SMALL LETTER L
|
||||
0x006d, //LATIN SMALL LETTER M
|
||||
0x006e, //LATIN SMALL LETTER N
|
||||
0x006f, //LATIN SMALL LETTER O
|
||||
0x0070, //LATIN SMALL LETTER P
|
||||
0x0071, //LATIN SMALL LETTER Q
|
||||
0x0072, //LATIN SMALL LETTER R
|
||||
0x0073, //LATIN SMALL LETTER S
|
||||
0x0074, //LATIN SMALL LETTER T
|
||||
0x0075, //LATIN SMALL LETTER U
|
||||
0x0076, //LATIN SMALL LETTER V
|
||||
0x0077, //LATIN SMALL LETTER W
|
||||
0x0078, //LATIN SMALL LETTER X
|
||||
0x0079, //LATIN SMALL LETTER Y
|
||||
0x007a, //LATIN SMALL LETTER Z
|
||||
0x007b, //LEFT CURLY BRACKET
|
||||
0x007c, //VERTICAL LINE
|
||||
0x007d, //RIGHT CURLY BRACKET
|
||||
0x007e, //TILDE
|
||||
0x007f, //DELETE
|
||||
0x00c7, //LATIN CAPITAL LETTER C WITH CEDILLA
|
||||
0x00fc, //LATIN SMALL LETTER U WITH DIAERESIS
|
||||
0x00e9, //LATIN SMALL LETTER E WITH ACUTE
|
||||
0x00e2, //LATIN SMALL LETTER A WITH CIRCUMFLEX
|
||||
0x00e4, //LATIN SMALL LETTER A WITH DIAERESIS
|
||||
0x00e0, //LATIN SMALL LETTER A WITH GRAVE
|
||||
0x00e5, //LATIN SMALL LETTER A WITH RING ABOVE
|
||||
0x00e7, //LATIN SMALL LETTER C WITH CEDILLA
|
||||
0x00ea, //LATIN SMALL LETTER E WITH CIRCUMFLEX
|
||||
0x00eb, //LATIN SMALL LETTER E WITH DIAERESIS
|
||||
0x00e8, //LATIN SMALL LETTER E WITH GRAVE
|
||||
0x00ef, //LATIN SMALL LETTER I WITH DIAERESIS
|
||||
0x00ee, //LATIN SMALL LETTER I WITH CIRCUMFLEX
|
||||
0x00ec, //LATIN SMALL LETTER I WITH GRAVE
|
||||
0x00c4, //LATIN CAPITAL LETTER A WITH DIAERESIS
|
||||
0x00c5, //LATIN CAPITAL LETTER A WITH RING ABOVE
|
||||
0x00c9, //LATIN CAPITAL LETTER E WITH ACUTE
|
||||
0x00e6, //LATIN SMALL LIGATURE AE
|
||||
0x00c6, //LATIN CAPITAL LIGATURE AE
|
||||
0x00f4, //LATIN SMALL LETTER O WITH CIRCUMFLEX
|
||||
0x00f6, //LATIN SMALL LETTER O WITH DIAERESIS
|
||||
0x00f2, //LATIN SMALL LETTER O WITH GRAVE
|
||||
0x00fb, //LATIN SMALL LETTER U WITH CIRCUMFLEX
|
||||
0x00f9, //LATIN SMALL LETTER U WITH GRAVE
|
||||
0x00ff, //LATIN SMALL LETTER Y WITH DIAERESIS
|
||||
0x00d6, //LATIN CAPITAL LETTER O WITH DIAERESIS
|
||||
0x00dc, //LATIN CAPITAL LETTER U WITH DIAERESIS
|
||||
0x00a2, //CENT SIGN
|
||||
0x00a3, //POUND SIGN
|
||||
0x00a5, //YEN SIGN
|
||||
0x20a7, //PESETA SIGN
|
||||
0x0192, //LATIN SMALL LETTER F WITH HOOK
|
||||
0x00e1, //LATIN SMALL LETTER A WITH ACUTE
|
||||
0x00ed, //LATIN SMALL LETTER I WITH ACUTE
|
||||
0x00f3, //LATIN SMALL LETTER O WITH ACUTE
|
||||
0x00fa, //LATIN SMALL LETTER U WITH ACUTE
|
||||
0x00f1, //LATIN SMALL LETTER N WITH TILDE
|
||||
0x00d1, //LATIN CAPITAL LETTER N WITH TILDE
|
||||
0x00aa, //FEMININE ORDINAL INDICATOR
|
||||
0x00ba, //MASCULINE ORDINAL INDICATOR
|
||||
0x00bf, //INVERTED QUESTION MARK
|
||||
0x2310, //REVERSED NOT SIGN
|
||||
0x00ac, //NOT SIGN
|
||||
0x00bd, //VULGAR FRACTION ONE HALF
|
||||
0x00bc, //VULGAR FRACTION ONE QUARTER
|
||||
0x00a1, //INVERTED EXCLAMATION MARK
|
||||
0x00ab, //LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
|
||||
0x00bb, //RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
|
||||
0x2591, //LIGHT SHADE
|
||||
0x2592, //MEDIUM SHADE
|
||||
0x2593, //DARK SHADE
|
||||
0x2502, //BOX DRAWINGS LIGHT VERTICAL
|
||||
0x2524, //BOX DRAWINGS LIGHT VERTICAL AND LEFT
|
||||
0x2561, //BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE
|
||||
0x2562, //BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE
|
||||
0x2556, //BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE
|
||||
0x2555, //BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE
|
||||
0x2563, //BOX DRAWINGS DOUBLE VERTICAL AND LEFT
|
||||
0x2551, //BOX DRAWINGS DOUBLE VERTICAL
|
||||
0x2557, //BOX DRAWINGS DOUBLE DOWN AND LEFT
|
||||
0x255d, //BOX DRAWINGS DOUBLE UP AND LEFT
|
||||
0x255c, //BOX DRAWINGS UP DOUBLE AND LEFT SINGLE
|
||||
0x255b, //BOX DRAWINGS UP SINGLE AND LEFT DOUBLE
|
||||
0x2510, //BOX DRAWINGS LIGHT DOWN AND LEFT
|
||||
0x2514, //BOX DRAWINGS LIGHT UP AND RIGHT
|
||||
0x2534, //BOX DRAWINGS LIGHT UP AND HORIZONTAL
|
||||
0x252c, //BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
|
||||
0x251c, //BOX DRAWINGS LIGHT VERTICAL AND RIGHT
|
||||
0x2500, //BOX DRAWINGS LIGHT HORIZONTAL
|
||||
0x253c, //BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
|
||||
0x255e, //BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE
|
||||
0x255f, //BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE
|
||||
0x255a, //BOX DRAWINGS DOUBLE UP AND RIGHT
|
||||
0x2554, //BOX DRAWINGS DOUBLE DOWN AND RIGHT
|
||||
0x2569, //BOX DRAWINGS DOUBLE UP AND HORIZONTAL
|
||||
0x2566, //BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
|
||||
0x2560, //BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
|
||||
0x2550, //BOX DRAWINGS DOUBLE HORIZONTAL
|
||||
0x256c, //BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
|
||||
0x2567, //BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE
|
||||
0x2568, //BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE
|
||||
0x2564, //BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE
|
||||
0x2565, //BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE
|
||||
0x2559, //BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE
|
||||
0x2558, //BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE
|
||||
0x2552, //BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE
|
||||
0x2553, //BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE
|
||||
0x256b, //BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE
|
||||
0x256a, //BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE
|
||||
0x2518, //BOX DRAWINGS LIGHT UP AND LEFT
|
||||
0x250c, //BOX DRAWINGS LIGHT DOWN AND RIGHT
|
||||
0x2588, //FULL BLOCK
|
||||
0x2584, //LOWER HALF BLOCK
|
||||
0x258c, //LEFT HALF BLOCK
|
||||
0x2590, //RIGHT HALF BLOCK
|
||||
0x2580, //UPPER HALF BLOCK
|
||||
0x03b1, //GREEK SMALL LETTER ALPHA
|
||||
0x00df, //LATIN SMALL LETTER SHARP S
|
||||
0x0393, //GREEK CAPITAL LETTER GAMMA
|
||||
0x03c0, //GREEK SMALL LETTER PI
|
||||
0x03a3, //GREEK CAPITAL LETTER SIGMA
|
||||
0x03c3, //GREEK SMALL LETTER SIGMA
|
||||
0x00b5, //MICRO SIGN
|
||||
0x03c4, //GREEK SMALL LETTER TAU
|
||||
0x03a6, //GREEK CAPITAL LETTER PHI
|
||||
0x0398, //GREEK CAPITAL LETTER THETA
|
||||
0x03a9, //GREEK CAPITAL LETTER OMEGA
|
||||
0x03b4, //GREEK SMALL LETTER DELTA
|
||||
0x221e, //INFINITY
|
||||
0x03c6, //GREEK SMALL LETTER PHI
|
||||
0x03b5, //GREEK SMALL LETTER EPSILON
|
||||
0x2229, //INTERSECTION
|
||||
0x2261, //IDENTICAL TO
|
||||
0x00b1, //PLUS-MINUS SIGN
|
||||
0x2265, //GREATER-THAN OR EQUAL TO
|
||||
0x2264, //LESS-THAN OR EQUAL TO
|
||||
0x2320, //TOP HALF INTEGRAL
|
||||
0x2321, //BOTTOM HALF INTEGRAL
|
||||
0x00f7, //DIVISION SIGN
|
||||
0x2248, //ALMOST EQUAL TO
|
||||
0x00b0, //DEGREE SIGN
|
||||
0x2219, //BULLET OPERATOR
|
||||
0x00b7, //MIDDLE DOT
|
||||
0x221a, //SQUARE ROOT
|
||||
0x207f, //SUPERSCRIPT LATIN SMALL LETTER N
|
||||
0x00b2, //SUPERSCRIPT TWO
|
||||
0x25a0, //BLACK SQUARE
|
||||
0x00a0, //NO-BREAK SPACE
|
||||
},
|
||||
}
|
|
@ -0,0 +1,262 @@
|
|||
package cp
|
||||
|
||||
var cp850 *charsetMap = &charsetMap{
|
||||
sb: [256]rune{
|
||||
0x0000, //NULL
|
||||
0x0001, //START OF HEADING
|
||||
0x0002, //START OF TEXT
|
||||
0x0003, //END OF TEXT
|
||||
0x0004, //END OF TRANSMISSION
|
||||
0x0005, //ENQUIRY
|
||||
0x0006, //ACKNOWLEDGE
|
||||
0x0007, //BELL
|
||||
0x0008, //BACKSPACE
|
||||
0x0009, //HORIZONTAL TABULATION
|
||||
0x000a, //LINE FEED
|
||||
0x000b, //VERTICAL TABULATION
|
||||
0x000c, //FORM FEED
|
||||
0x000d, //CARRIAGE RETURN
|
||||
0x000e, //SHIFT OUT
|
||||
0x000f, //SHIFT IN
|
||||
0x0010, //DATA LINK ESCAPE
|
||||
0x0011, //DEVICE CONTROL ONE
|
||||
0x0012, //DEVICE CONTROL TWO
|
||||
0x0013, //DEVICE CONTROL THREE
|
||||
0x0014, //DEVICE CONTROL FOUR
|
||||
0x0015, //NEGATIVE ACKNOWLEDGE
|
||||
0x0016, //SYNCHRONOUS IDLE
|
||||
0x0017, //END OF TRANSMISSION BLOCK
|
||||
0x0018, //CANCEL
|
||||
0x0019, //END OF MEDIUM
|
||||
0x001a, //SUBSTITUTE
|
||||
0x001b, //ESCAPE
|
||||
0x001c, //FILE SEPARATOR
|
||||
0x001d, //GROUP SEPARATOR
|
||||
0x001e, //RECORD SEPARATOR
|
||||
0x001f, //UNIT SEPARATOR
|
||||
0x0020, //SPACE
|
||||
0x0021, //EXCLAMATION MARK
|
||||
0x0022, //QUOTATION MARK
|
||||
0x0023, //NUMBER SIGN
|
||||
0x0024, //DOLLAR SIGN
|
||||
0x0025, //PERCENT SIGN
|
||||
0x0026, //AMPERSAND
|
||||
0x0027, //APOSTROPHE
|
||||
0x0028, //LEFT PARENTHESIS
|
||||
0x0029, //RIGHT PARENTHESIS
|
||||
0x002a, //ASTERISK
|
||||
0x002b, //PLUS SIGN
|
||||
0x002c, //COMMA
|
||||
0x002d, //HYPHEN-MINUS
|
||||
0x002e, //FULL STOP
|
||||
0x002f, //SOLIDUS
|
||||
0x0030, //DIGIT ZERO
|
||||
0x0031, //DIGIT ONE
|
||||
0x0032, //DIGIT TWO
|
||||
0x0033, //DIGIT THREE
|
||||
0x0034, //DIGIT FOUR
|
||||
0x0035, //DIGIT FIVE
|
||||
0x0036, //DIGIT SIX
|
||||
0x0037, //DIGIT SEVEN
|
||||
0x0038, //DIGIT EIGHT
|
||||
0x0039, //DIGIT NINE
|
||||
0x003a, //COLON
|
||||
0x003b, //SEMICOLON
|
||||
0x003c, //LESS-THAN SIGN
|
||||
0x003d, //EQUALS SIGN
|
||||
0x003e, //GREATER-THAN SIGN
|
||||
0x003f, //QUESTION MARK
|
||||
0x0040, //COMMERCIAL AT
|
||||
0x0041, //LATIN CAPITAL LETTER A
|
||||
0x0042, //LATIN CAPITAL LETTER B
|
||||
0x0043, //LATIN CAPITAL LETTER C
|
||||
0x0044, //LATIN CAPITAL LETTER D
|
||||
0x0045, //LATIN CAPITAL LETTER E
|
||||
0x0046, //LATIN CAPITAL LETTER F
|
||||
0x0047, //LATIN CAPITAL LETTER G
|
||||
0x0048, //LATIN CAPITAL LETTER H
|
||||
0x0049, //LATIN CAPITAL LETTER I
|
||||
0x004a, //LATIN CAPITAL LETTER J
|
||||
0x004b, //LATIN CAPITAL LETTER K
|
||||
0x004c, //LATIN CAPITAL LETTER L
|
||||
0x004d, //LATIN CAPITAL LETTER M
|
||||
0x004e, //LATIN CAPITAL LETTER N
|
||||
0x004f, //LATIN CAPITAL LETTER O
|
||||
0x0050, //LATIN CAPITAL LETTER P
|
||||
0x0051, //LATIN CAPITAL LETTER Q
|
||||
0x0052, //LATIN CAPITAL LETTER R
|
||||
0x0053, //LATIN CAPITAL LETTER S
|
||||
0x0054, //LATIN CAPITAL LETTER T
|
||||
0x0055, //LATIN CAPITAL LETTER U
|
||||
0x0056, //LATIN CAPITAL LETTER V
|
||||
0x0057, //LATIN CAPITAL LETTER W
|
||||
0x0058, //LATIN CAPITAL LETTER X
|
||||
0x0059, //LATIN CAPITAL LETTER Y
|
||||
0x005a, //LATIN CAPITAL LETTER Z
|
||||
0x005b, //LEFT SQUARE BRACKET
|
||||
0x005c, //REVERSE SOLIDUS
|
||||
0x005d, //RIGHT SQUARE BRACKET
|
||||
0x005e, //CIRCUMFLEX ACCENT
|
||||
0x005f, //LOW LINE
|
||||
0x0060, //GRAVE ACCENT
|
||||
0x0061, //LATIN SMALL LETTER A
|
||||
0x0062, //LATIN SMALL LETTER B
|
||||
0x0063, //LATIN SMALL LETTER C
|
||||
0x0064, //LATIN SMALL LETTER D
|
||||
0x0065, //LATIN SMALL LETTER E
|
||||
0x0066, //LATIN SMALL LETTER F
|
||||
0x0067, //LATIN SMALL LETTER G
|
||||
0x0068, //LATIN SMALL LETTER H
|
||||
0x0069, //LATIN SMALL LETTER I
|
||||
0x006a, //LATIN SMALL LETTER J
|
||||
0x006b, //LATIN SMALL LETTER K
|
||||
0x006c, //LATIN SMALL LETTER L
|
||||
0x006d, //LATIN SMALL LETTER M
|
||||
0x006e, //LATIN SMALL LETTER N
|
||||
0x006f, //LATIN SMALL LETTER O
|
||||
0x0070, //LATIN SMALL LETTER P
|
||||
0x0071, //LATIN SMALL LETTER Q
|
||||
0x0072, //LATIN SMALL LETTER R
|
||||
0x0073, //LATIN SMALL LETTER S
|
||||
0x0074, //LATIN SMALL LETTER T
|
||||
0x0075, //LATIN SMALL LETTER U
|
||||
0x0076, //LATIN SMALL LETTER V
|
||||
0x0077, //LATIN SMALL LETTER W
|
||||
0x0078, //LATIN SMALL LETTER X
|
||||
0x0079, //LATIN SMALL LETTER Y
|
||||
0x007a, //LATIN SMALL LETTER Z
|
||||
0x007b, //LEFT CURLY BRACKET
|
||||
0x007c, //VERTICAL LINE
|
||||
0x007d, //RIGHT CURLY BRACKET
|
||||
0x007e, //TILDE
|
||||
0x007f, //DELETE
|
||||
0x00c7, //LATIN CAPITAL LETTER C WITH CEDILLA
|
||||
0x00fc, //LATIN SMALL LETTER U WITH DIAERESIS
|
||||
0x00e9, //LATIN SMALL LETTER E WITH ACUTE
|
||||
0x00e2, //LATIN SMALL LETTER A WITH CIRCUMFLEX
|
||||
0x00e4, //LATIN SMALL LETTER A WITH DIAERESIS
|
||||
0x00e0, //LATIN SMALL LETTER A WITH GRAVE
|
||||
0x00e5, //LATIN SMALL LETTER A WITH RING ABOVE
|
||||
0x00e7, //LATIN SMALL LETTER C WITH CEDILLA
|
||||
0x00ea, //LATIN SMALL LETTER E WITH CIRCUMFLEX
|
||||
0x00eb, //LATIN SMALL LETTER E WITH DIAERESIS
|
||||
0x00e8, //LATIN SMALL LETTER E WITH GRAVE
|
||||
0x00ef, //LATIN SMALL LETTER I WITH DIAERESIS
|
||||
0x00ee, //LATIN SMALL LETTER I WITH CIRCUMFLEX
|
||||
0x00ec, //LATIN SMALL LETTER I WITH GRAVE
|
||||
0x00c4, //LATIN CAPITAL LETTER A WITH DIAERESIS
|
||||
0x00c5, //LATIN CAPITAL LETTER A WITH RING ABOVE
|
||||
0x00c9, //LATIN CAPITAL LETTER E WITH ACUTE
|
||||
0x00e6, //LATIN SMALL LIGATURE AE
|
||||
0x00c6, //LATIN CAPITAL LIGATURE AE
|
||||
0x00f4, //LATIN SMALL LETTER O WITH CIRCUMFLEX
|
||||
0x00f6, //LATIN SMALL LETTER O WITH DIAERESIS
|
||||
0x00f2, //LATIN SMALL LETTER O WITH GRAVE
|
||||
0x00fb, //LATIN SMALL LETTER U WITH CIRCUMFLEX
|
||||
0x00f9, //LATIN SMALL LETTER U WITH GRAVE
|
||||
0x00ff, //LATIN SMALL LETTER Y WITH DIAERESIS
|
||||
0x00d6, //LATIN CAPITAL LETTER O WITH DIAERESIS
|
||||
0x00dc, //LATIN CAPITAL LETTER U WITH DIAERESIS
|
||||
0x00f8, //LATIN SMALL LETTER O WITH STROKE
|
||||
0x00a3, //POUND SIGN
|
||||
0x00d8, //LATIN CAPITAL LETTER O WITH STROKE
|
||||
0x00d7, //MULTIPLICATION SIGN
|
||||
0x0192, //LATIN SMALL LETTER F WITH HOOK
|
||||
0x00e1, //LATIN SMALL LETTER A WITH ACUTE
|
||||
0x00ed, //LATIN SMALL LETTER I WITH ACUTE
|
||||
0x00f3, //LATIN SMALL LETTER O WITH ACUTE
|
||||
0x00fa, //LATIN SMALL LETTER U WITH ACUTE
|
||||
0x00f1, //LATIN SMALL LETTER N WITH TILDE
|
||||
0x00d1, //LATIN CAPITAL LETTER N WITH TILDE
|
||||
0x00aa, //FEMININE ORDINAL INDICATOR
|
||||
0x00ba, //MASCULINE ORDINAL INDICATOR
|
||||
0x00bf, //INVERTED QUESTION MARK
|
||||
0x00ae, //REGISTERED SIGN
|
||||
0x00ac, //NOT SIGN
|
||||
0x00bd, //VULGAR FRACTION ONE HALF
|
||||
0x00bc, //VULGAR FRACTION ONE QUARTER
|
||||
0x00a1, //INVERTED EXCLAMATION MARK
|
||||
0x00ab, //LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
|
||||
0x00bb, //RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
|
||||
0x2591, //LIGHT SHADE
|
||||
0x2592, //MEDIUM SHADE
|
||||
0x2593, //DARK SHADE
|
||||
0x2502, //BOX DRAWINGS LIGHT VERTICAL
|
||||
0x2524, //BOX DRAWINGS LIGHT VERTICAL AND LEFT
|
||||
0x00c1, //LATIN CAPITAL LETTER A WITH ACUTE
|
||||
0x00c2, //LATIN CAPITAL LETTER A WITH CIRCUMFLEX
|
||||
0x00c0, //LATIN CAPITAL LETTER A WITH GRAVE
|
||||
0x00a9, //COPYRIGHT SIGN
|
||||
0x2563, //BOX DRAWINGS DOUBLE VERTICAL AND LEFT
|
||||
0x2551, //BOX DRAWINGS DOUBLE VERTICAL
|
||||
0x2557, //BOX DRAWINGS DOUBLE DOWN AND LEFT
|
||||
0x255d, //BOX DRAWINGS DOUBLE UP AND LEFT
|
||||
0x00a2, //CENT SIGN
|
||||
0x00a5, //YEN SIGN
|
||||
0x2510, //BOX DRAWINGS LIGHT DOWN AND LEFT
|
||||
0x2514, //BOX DRAWINGS LIGHT UP AND RIGHT
|
||||
0x2534, //BOX DRAWINGS LIGHT UP AND HORIZONTAL
|
||||
0x252c, //BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
|
||||
0x251c, //BOX DRAWINGS LIGHT VERTICAL AND RIGHT
|
||||
0x2500, //BOX DRAWINGS LIGHT HORIZONTAL
|
||||
0x253c, //BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
|
||||
0x00e3, //LATIN SMALL LETTER A WITH TILDE
|
||||
0x00c3, //LATIN CAPITAL LETTER A WITH TILDE
|
||||
0x255a, //BOX DRAWINGS DOUBLE UP AND RIGHT
|
||||
0x2554, //BOX DRAWINGS DOUBLE DOWN AND RIGHT
|
||||
0x2569, //BOX DRAWINGS DOUBLE UP AND HORIZONTAL
|
||||
0x2566, //BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
|
||||
0x2560, //BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
|
||||
0x2550, //BOX DRAWINGS DOUBLE HORIZONTAL
|
||||
0x256c, //BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
|
||||
0x00a4, //CURRENCY SIGN
|
||||
0x00f0, //LATIN SMALL LETTER ETH
|
||||
0x00d0, //LATIN CAPITAL LETTER ETH
|
||||
0x00ca, //LATIN CAPITAL LETTER E WITH CIRCUMFLEX
|
||||
0x00cb, //LATIN CAPITAL LETTER E WITH DIAERESIS
|
||||
0x00c8, //LATIN CAPITAL LETTER E WITH GRAVE
|
||||
0x0131, //LATIN SMALL LETTER DOTLESS I
|
||||
0x00cd, //LATIN CAPITAL LETTER I WITH ACUTE
|
||||
0x00ce, //LATIN CAPITAL LETTER I WITH CIRCUMFLEX
|
||||
0x00cf, //LATIN CAPITAL LETTER I WITH DIAERESIS
|
||||
0x2518, //BOX DRAWINGS LIGHT UP AND LEFT
|
||||
0x250c, //BOX DRAWINGS LIGHT DOWN AND RIGHT
|
||||
0x2588, //FULL BLOCK
|
||||
0x2584, //LOWER HALF BLOCK
|
||||
0x00a6, //BROKEN BAR
|
||||
0x00cc, //LATIN CAPITAL LETTER I WITH GRAVE
|
||||
0x2580, //UPPER HALF BLOCK
|
||||
0x00d3, //LATIN CAPITAL LETTER O WITH ACUTE
|
||||
0x00df, //LATIN SMALL LETTER SHARP S
|
||||
0x00d4, //LATIN CAPITAL LETTER O WITH CIRCUMFLEX
|
||||
0x00d2, //LATIN CAPITAL LETTER O WITH GRAVE
|
||||
0x00f5, //LATIN SMALL LETTER O WITH TILDE
|
||||
0x00d5, //LATIN CAPITAL LETTER O WITH TILDE
|
||||
0x00b5, //MICRO SIGN
|
||||
0x00fe, //LATIN SMALL LETTER THORN
|
||||
0x00de, //LATIN CAPITAL LETTER THORN
|
||||
0x00da, //LATIN CAPITAL LETTER U WITH ACUTE
|
||||
0x00db, //LATIN CAPITAL LETTER U WITH CIRCUMFLEX
|
||||
0x00d9, //LATIN CAPITAL LETTER U WITH GRAVE
|
||||
0x00fd, //LATIN SMALL LETTER Y WITH ACUTE
|
||||
0x00dd, //LATIN CAPITAL LETTER Y WITH ACUTE
|
||||
0x00af, //MACRON
|
||||
0x00b4, //ACUTE ACCENT
|
||||
0x00ad, //SOFT HYPHEN
|
||||
0x00b1, //PLUS-MINUS SIGN
|
||||
0x2017, //DOUBLE LOW LINE
|
||||
0x00be, //VULGAR FRACTION THREE QUARTERS
|
||||
0x00b6, //PILCROW SIGN
|
||||
0x00a7, //SECTION SIGN
|
||||
0x00f7, //DIVISION SIGN
|
||||
0x00b8, //CEDILLA
|
||||
0x00b0, //DEGREE SIGN
|
||||
0x00a8, //DIAERESIS
|
||||
0x00b7, //MIDDLE DOT
|
||||
0x00b9, //SUPERSCRIPT ONE
|
||||
0x00b3, //SUPERSCRIPT THREE
|
||||
0x00b2, //SUPERSCRIPT TWO
|
||||
0x25a0, //BLACK SQUARE
|
||||
0x00a0, //NO-BREAK SPACE
|
||||
},
|
||||
}
|
|
@ -0,0 +1,262 @@
|
|||
package cp
|
||||
|
||||
var cp874 *charsetMap = &charsetMap{
|
||||
sb: [256]rune{
|
||||
0x0000, //NULL
|
||||
0x0001, //START OF HEADING
|
||||
0x0002, //START OF TEXT
|
||||
0x0003, //END OF TEXT
|
||||
0x0004, //END OF TRANSMISSION
|
||||
0x0005, //ENQUIRY
|
||||
0x0006, //ACKNOWLEDGE
|
||||
0x0007, //BELL
|
||||
0x0008, //BACKSPACE
|
||||
0x0009, //HORIZONTAL TABULATION
|
||||
0x000A, //LINE FEED
|
||||
0x000B, //VERTICAL TABULATION
|
||||
0x000C, //FORM FEED
|
||||
0x000D, //CARRIAGE RETURN
|
||||
0x000E, //SHIFT OUT
|
||||
0x000F, //SHIFT IN
|
||||
0x0010, //DATA LINK ESCAPE
|
||||
0x0011, //DEVICE CONTROL ONE
|
||||
0x0012, //DEVICE CONTROL TWO
|
||||
0x0013, //DEVICE CONTROL THREE
|
||||
0x0014, //DEVICE CONTROL FOUR
|
||||
0x0015, //NEGATIVE ACKNOWLEDGE
|
||||
0x0016, //SYNCHRONOUS IDLE
|
||||
0x0017, //END OF TRANSMISSION BLOCK
|
||||
0x0018, //CANCEL
|
||||
0x0019, //END OF MEDIUM
|
||||
0x001A, //SUBSTITUTE
|
||||
0x001B, //ESCAPE
|
||||
0x001C, //FILE SEPARATOR
|
||||
0x001D, //GROUP SEPARATOR
|
||||
0x001E, //RECORD SEPARATOR
|
||||
0x001F, //UNIT SEPARATOR
|
||||
0x0020, //SPACE
|
||||
0x0021, //EXCLAMATION MARK
|
||||
0x0022, //QUOTATION MARK
|
||||
0x0023, //NUMBER SIGN
|
||||
0x0024, //DOLLAR SIGN
|
||||
0x0025, //PERCENT SIGN
|
||||
0x0026, //AMPERSAND
|
||||
0x0027, //APOSTROPHE
|
||||
0x0028, //LEFT PARENTHESIS
|
||||
0x0029, //RIGHT PARENTHESIS
|
||||
0x002A, //ASTERISK
|
||||
0x002B, //PLUS SIGN
|
||||
0x002C, //COMMA
|
||||
0x002D, //HYPHEN-MINUS
|
||||
0x002E, //FULL STOP
|
||||
0x002F, //SOLIDUS
|
||||
0x0030, //DIGIT ZERO
|
||||
0x0031, //DIGIT ONE
|
||||
0x0032, //DIGIT TWO
|
||||
0x0033, //DIGIT THREE
|
||||
0x0034, //DIGIT FOUR
|
||||
0x0035, //DIGIT FIVE
|
||||
0x0036, //DIGIT SIX
|
||||
0x0037, //DIGIT SEVEN
|
||||
0x0038, //DIGIT EIGHT
|
||||
0x0039, //DIGIT NINE
|
||||
0x003A, //COLON
|
||||
0x003B, //SEMICOLON
|
||||
0x003C, //LESS-THAN SIGN
|
||||
0x003D, //EQUALS SIGN
|
||||
0x003E, //GREATER-THAN SIGN
|
||||
0x003F, //QUESTION MARK
|
||||
0x0040, //COMMERCIAL AT
|
||||
0x0041, //LATIN CAPITAL LETTER A
|
||||
0x0042, //LATIN CAPITAL LETTER B
|
||||
0x0043, //LATIN CAPITAL LETTER C
|
||||
0x0044, //LATIN CAPITAL LETTER D
|
||||
0x0045, //LATIN CAPITAL LETTER E
|
||||
0x0046, //LATIN CAPITAL LETTER F
|
||||
0x0047, //LATIN CAPITAL LETTER G
|
||||
0x0048, //LATIN CAPITAL LETTER H
|
||||
0x0049, //LATIN CAPITAL LETTER I
|
||||
0x004A, //LATIN CAPITAL LETTER J
|
||||
0x004B, //LATIN CAPITAL LETTER K
|
||||
0x004C, //LATIN CAPITAL LETTER L
|
||||
0x004D, //LATIN CAPITAL LETTER M
|
||||
0x004E, //LATIN CAPITAL LETTER N
|
||||
0x004F, //LATIN CAPITAL LETTER O
|
||||
0x0050, //LATIN CAPITAL LETTER P
|
||||
0x0051, //LATIN CAPITAL LETTER Q
|
||||
0x0052, //LATIN CAPITAL LETTER R
|
||||
0x0053, //LATIN CAPITAL LETTER S
|
||||
0x0054, //LATIN CAPITAL LETTER T
|
||||
0x0055, //LATIN CAPITAL LETTER U
|
||||
0x0056, //LATIN CAPITAL LETTER V
|
||||
0x0057, //LATIN CAPITAL LETTER W
|
||||
0x0058, //LATIN CAPITAL LETTER X
|
||||
0x0059, //LATIN CAPITAL LETTER Y
|
||||
0x005A, //LATIN CAPITAL LETTER Z
|
||||
0x005B, //LEFT SQUARE BRACKET
|
||||
0x005C, //REVERSE SOLIDUS
|
||||
0x005D, //RIGHT SQUARE BRACKET
|
||||
0x005E, //CIRCUMFLEX ACCENT
|
||||
0x005F, //LOW LINE
|
||||
0x0060, //GRAVE ACCENT
|
||||
0x0061, //LATIN SMALL LETTER A
|
||||
0x0062, //LATIN SMALL LETTER B
|
||||
0x0063, //LATIN SMALL LETTER C
|
||||
0x0064, //LATIN SMALL LETTER D
|
||||
0x0065, //LATIN SMALL LETTER E
|
||||
0x0066, //LATIN SMALL LETTER F
|
||||
0x0067, //LATIN SMALL LETTER G
|
||||
0x0068, //LATIN SMALL LETTER H
|
||||
0x0069, //LATIN SMALL LETTER I
|
||||
0x006A, //LATIN SMALL LETTER J
|
||||
0x006B, //LATIN SMALL LETTER K
|
||||
0x006C, //LATIN SMALL LETTER L
|
||||
0x006D, //LATIN SMALL LETTER M
|
||||
0x006E, //LATIN SMALL LETTER N
|
||||
0x006F, //LATIN SMALL LETTER O
|
||||
0x0070, //LATIN SMALL LETTER P
|
||||
0x0071, //LATIN SMALL LETTER Q
|
||||
0x0072, //LATIN SMALL LETTER R
|
||||
0x0073, //LATIN SMALL LETTER S
|
||||
0x0074, //LATIN SMALL LETTER T
|
||||
0x0075, //LATIN SMALL LETTER U
|
||||
0x0076, //LATIN SMALL LETTER V
|
||||
0x0077, //LATIN SMALL LETTER W
|
||||
0x0078, //LATIN SMALL LETTER X
|
||||
0x0079, //LATIN SMALL LETTER Y
|
||||
0x007A, //LATIN SMALL LETTER Z
|
||||
0x007B, //LEFT CURLY BRACKET
|
||||
0x007C, //VERTICAL LINE
|
||||
0x007D, //RIGHT CURLY BRACKET
|
||||
0x007E, //TILDE
|
||||
0x007F, //DELETE
|
||||
0x20AC, //EURO SIGN
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0x2026, //HORIZONTAL ELLIPSIS
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0x2018, //LEFT SINGLE QUOTATION MARK
|
||||
0x2019, //RIGHT SINGLE QUOTATION MARK
|
||||
0x201C, //LEFT DOUBLE QUOTATION MARK
|
||||
0x201D, //RIGHT DOUBLE QUOTATION MARK
|
||||
0x2022, //BULLET
|
||||
0x2013, //EN DASH
|
||||
0x2014, //EM DASH
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0x00A0, //NO-BREAK SPACE
|
||||
0x0E01, //THAI CHARACTER KO KAI
|
||||
0x0E02, //THAI CHARACTER KHO KHAI
|
||||
0x0E03, //THAI CHARACTER KHO KHUAT
|
||||
0x0E04, //THAI CHARACTER KHO KHWAI
|
||||
0x0E05, //THAI CHARACTER KHO KHON
|
||||
0x0E06, //THAI CHARACTER KHO RAKHANG
|
||||
0x0E07, //THAI CHARACTER NGO NGU
|
||||
0x0E08, //THAI CHARACTER CHO CHAN
|
||||
0x0E09, //THAI CHARACTER CHO CHING
|
||||
0x0E0A, //THAI CHARACTER CHO CHANG
|
||||
0x0E0B, //THAI CHARACTER SO SO
|
||||
0x0E0C, //THAI CHARACTER CHO CHOE
|
||||
0x0E0D, //THAI CHARACTER YO YING
|
||||
0x0E0E, //THAI CHARACTER DO CHADA
|
||||
0x0E0F, //THAI CHARACTER TO PATAK
|
||||
0x0E10, //THAI CHARACTER THO THAN
|
||||
0x0E11, //THAI CHARACTER THO NANGMONTHO
|
||||
0x0E12, //THAI CHARACTER THO PHUTHAO
|
||||
0x0E13, //THAI CHARACTER NO NEN
|
||||
0x0E14, //THAI CHARACTER DO DEK
|
||||
0x0E15, //THAI CHARACTER TO TAO
|
||||
0x0E16, //THAI CHARACTER THO THUNG
|
||||
0x0E17, //THAI CHARACTER THO THAHAN
|
||||
0x0E18, //THAI CHARACTER THO THONG
|
||||
0x0E19, //THAI CHARACTER NO NU
|
||||
0x0E1A, //THAI CHARACTER BO BAIMAI
|
||||
0x0E1B, //THAI CHARACTER PO PLA
|
||||
0x0E1C, //THAI CHARACTER PHO PHUNG
|
||||
0x0E1D, //THAI CHARACTER FO FA
|
||||
0x0E1E, //THAI CHARACTER PHO PHAN
|
||||
0x0E1F, //THAI CHARACTER FO FAN
|
||||
0x0E20, //THAI CHARACTER PHO SAMPHAO
|
||||
0x0E21, //THAI CHARACTER MO MA
|
||||
0x0E22, //THAI CHARACTER YO YAK
|
||||
0x0E23, //THAI CHARACTER RO RUA
|
||||
0x0E24, //THAI CHARACTER RU
|
||||
0x0E25, //THAI CHARACTER LO LING
|
||||
0x0E26, //THAI CHARACTER LU
|
||||
0x0E27, //THAI CHARACTER WO WAEN
|
||||
0x0E28, //THAI CHARACTER SO SALA
|
||||
0x0E29, //THAI CHARACTER SO RUSI
|
||||
0x0E2A, //THAI CHARACTER SO SUA
|
||||
0x0E2B, //THAI CHARACTER HO HIP
|
||||
0x0E2C, //THAI CHARACTER LO CHULA
|
||||
0x0E2D, //THAI CHARACTER O ANG
|
||||
0x0E2E, //THAI CHARACTER HO NOKHUK
|
||||
0x0E2F, //THAI CHARACTER PAIYANNOI
|
||||
0x0E30, //THAI CHARACTER SARA A
|
||||
0x0E31, //THAI CHARACTER MAI HAN-AKAT
|
||||
0x0E32, //THAI CHARACTER SARA AA
|
||||
0x0E33, //THAI CHARACTER SARA AM
|
||||
0x0E34, //THAI CHARACTER SARA I
|
||||
0x0E35, //THAI CHARACTER SARA II
|
||||
0x0E36, //THAI CHARACTER SARA UE
|
||||
0x0E37, //THAI CHARACTER SARA UEE
|
||||
0x0E38, //THAI CHARACTER SARA U
|
||||
0x0E39, //THAI CHARACTER SARA UU
|
||||
0x0E3A, //THAI CHARACTER PHINTHU
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0x0E3F, //THAI CURRENCY SYMBOL BAHT
|
||||
0x0E40, //THAI CHARACTER SARA E
|
||||
0x0E41, //THAI CHARACTER SARA AE
|
||||
0x0E42, //THAI CHARACTER SARA O
|
||||
0x0E43, //THAI CHARACTER SARA AI MAIMUAN
|
||||
0x0E44, //THAI CHARACTER SARA AI MAIMALAI
|
||||
0x0E45, //THAI CHARACTER LAKKHANGYAO
|
||||
0x0E46, //THAI CHARACTER MAIYAMOK
|
||||
0x0E47, //THAI CHARACTER MAITAIKHU
|
||||
0x0E48, //THAI CHARACTER MAI EK
|
||||
0x0E49, //THAI CHARACTER MAI THO
|
||||
0x0E4A, //THAI CHARACTER MAI TRI
|
||||
0x0E4B, //THAI CHARACTER MAI CHATTAWA
|
||||
0x0E4C, //THAI CHARACTER THANTHAKHAT
|
||||
0x0E4D, //THAI CHARACTER NIKHAHIT
|
||||
0x0E4E, //THAI CHARACTER YAMAKKAN
|
||||
0x0E4F, //THAI CHARACTER FONGMAN
|
||||
0x0E50, //THAI DIGIT ZERO
|
||||
0x0E51, //THAI DIGIT ONE
|
||||
0x0E52, //THAI DIGIT TWO
|
||||
0x0E53, //THAI DIGIT THREE
|
||||
0x0E54, //THAI DIGIT FOUR
|
||||
0x0E55, //THAI DIGIT FIVE
|
||||
0x0E56, //THAI DIGIT SIX
|
||||
0x0E57, //THAI DIGIT SEVEN
|
||||
0x0E58, //THAI DIGIT EIGHT
|
||||
0x0E59, //THAI DIGIT NINE
|
||||
0x0E5A, //THAI CHARACTER ANGKHANKHU
|
||||
0x0E5B, //THAI CHARACTER KHOMUT
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
0xFFFD, //UNDEFINED
|
||||
},
|
||||
}
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,30 @@
|
|||
package mssql
|
||||
|
||||
import (
|
||||
"log"
|
||||
)
|
||||
|
||||
type Logger interface {
|
||||
Printf(format string, v ...interface{})
|
||||
Println(v ...interface{})
|
||||
}
|
||||
|
||||
type optionalLogger struct {
|
||||
logger Logger
|
||||
}
|
||||
|
||||
func (o optionalLogger) Printf(format string, v ...interface{}) {
|
||||
if o.logger != nil {
|
||||
o.logger.Printf(format, v...)
|
||||
} else {
|
||||
log.Printf(format, v...)
|
||||
}
|
||||
}
|
||||
|
||||
func (o optionalLogger) Println(v ...interface{}) {
|
||||
if o.logger != nil {
|
||||
o.logger.Println(v...)
|
||||
} else {
|
||||
log.Println(v...)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,962 @@
|
|||
package mssql
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"database/sql/driver"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net"
|
||||
"reflect"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
// ReturnStatus may be used to return the return value from a proc.
|
||||
//
|
||||
// var rs mssql.ReturnStatus
|
||||
// _, err := db.Exec("theproc", &rs)
|
||||
// log.Printf("return status = %d", rs)
|
||||
type ReturnStatus int32
|
||||
|
||||
var driverInstance = &Driver{processQueryText: true}
|
||||
var driverInstanceNoProcess = &Driver{processQueryText: false}
|
||||
|
||||
func init() {
|
||||
sql.Register("mssql", driverInstance)
|
||||
sql.Register("sqlserver", driverInstanceNoProcess)
|
||||
createDialer = func(p *connectParams) dialer {
|
||||
return tcpDialer{&net.Dialer{KeepAlive: p.keepAlive}}
|
||||
}
|
||||
}
|
||||
|
||||
// Abstract the dialer for testing and for non-TCP based connections.
|
||||
type dialer interface {
|
||||
Dial(ctx context.Context, addr string) (net.Conn, error)
|
||||
}
|
||||
|
||||
var createDialer func(p *connectParams) dialer
|
||||
|
||||
type tcpDialer struct {
|
||||
nd *net.Dialer
|
||||
}
|
||||
|
||||
func (d tcpDialer) Dial(ctx context.Context, addr string) (net.Conn, error) {
|
||||
return d.nd.DialContext(ctx, "tcp", addr)
|
||||
}
|
||||
|
||||
type Driver struct {
|
||||
log optionalLogger
|
||||
|
||||
processQueryText bool
|
||||
}
|
||||
|
||||
// OpenConnector opens a new connector. Useful to dial with a context.
|
||||
func (d *Driver) OpenConnector(dsn string) (*Connector, error) {
|
||||
params, err := parseConnectParams(dsn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Connector{
|
||||
params: params,
|
||||
driver: d,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (d *Driver) Open(dsn string) (driver.Conn, error) {
|
||||
return d.open(context.Background(), dsn)
|
||||
}
|
||||
|
||||
func SetLogger(logger Logger) {
|
||||
driverInstance.SetLogger(logger)
|
||||
driverInstanceNoProcess.SetLogger(logger)
|
||||
}
|
||||
|
||||
func (d *Driver) SetLogger(logger Logger) {
|
||||
d.log = optionalLogger{logger}
|
||||
}
|
||||
|
||||
// NewConnector creates a new connector from a DSN.
|
||||
// The returned connector may be used with sql.OpenDB.
|
||||
func NewConnector(dsn string) (*Connector, error) {
|
||||
params, err := parseConnectParams(dsn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c := &Connector{
|
||||
params: params,
|
||||
driver: driverInstanceNoProcess,
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// Connector holds the parsed DSN and is ready to make a new connection
|
||||
// at any time.
|
||||
//
|
||||
// In the future, settings that cannot be passed through a string DSN
|
||||
// may be set directly on the connector.
|
||||
type Connector struct {
|
||||
params connectParams
|
||||
driver *Driver
|
||||
|
||||
// SessionInitSQL is executed after marking a given session to be reset.
|
||||
// When not present, the next query will still reset the session to the
|
||||
// database defaults.
|
||||
//
|
||||
// When present the connection will immediately mark the session to
|
||||
// be reset, then execute the SessionInitSQL text to setup the session
|
||||
// that may be different from the base database defaults.
|
||||
//
|
||||
// For Example, the application relies on the following defaults
|
||||
// but is not allowed to set them at the database system level.
|
||||
//
|
||||
// SET XACT_ABORT ON;
|
||||
// SET TEXTSIZE -1;
|
||||
// SET ANSI_NULLS ON;
|
||||
// SET LOCK_TIMEOUT 10000;
|
||||
//
|
||||
// SessionInitSQL should not attempt to manually call sp_reset_connection.
|
||||
// This will happen at the TDS layer.
|
||||
//
|
||||
// SessionInitSQL is optional. The session will be reset even if
|
||||
// SessionInitSQL is empty.
|
||||
SessionInitSQL string
|
||||
}
|
||||
|
||||
type Conn struct {
|
||||
connector *Connector
|
||||
sess *tdsSession
|
||||
transactionCtx context.Context
|
||||
resetSession bool
|
||||
|
||||
processQueryText bool
|
||||
connectionGood bool
|
||||
|
||||
outs map[string]interface{}
|
||||
returnStatus *ReturnStatus
|
||||
}
|
||||
|
||||
func (c *Conn) setReturnStatus(s ReturnStatus) {
|
||||
if c.returnStatus == nil {
|
||||
return
|
||||
}
|
||||
*c.returnStatus = s
|
||||
}
|
||||
|
||||
func (c *Conn) checkBadConn(err error) error {
|
||||
// this is a hack to address Issue #275
|
||||
// we set connectionGood flag to false if
|
||||
// error indicates that connection is not usable
|
||||
// but we return actual error instead of ErrBadConn
|
||||
// this will cause connection to stay in a pool
|
||||
// but next request to this connection will return ErrBadConn
|
||||
|
||||
// it might be possible to revise this hack after
|
||||
// https://github.com/golang/go/issues/20807
|
||||
// is implemented
|
||||
switch err {
|
||||
case nil:
|
||||
return nil
|
||||
case io.EOF:
|
||||
c.connectionGood = false
|
||||
return driver.ErrBadConn
|
||||
case driver.ErrBadConn:
|
||||
// It is an internal programming error if driver.ErrBadConn
|
||||
// is ever passed to this function. driver.ErrBadConn should
|
||||
// only ever be returned in response to a *mssql.Conn.connectionGood == false
|
||||
// check in the external facing API.
|
||||
panic("driver.ErrBadConn in checkBadConn. This should not happen.")
|
||||
}
|
||||
|
||||
switch err.(type) {
|
||||
case net.Error:
|
||||
c.connectionGood = false
|
||||
return err
|
||||
case StreamError:
|
||||
c.connectionGood = false
|
||||
return err
|
||||
default:
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Conn) clearOuts() {
|
||||
c.outs = nil
|
||||
}
|
||||
|
||||
func (c *Conn) simpleProcessResp(ctx context.Context) error {
|
||||
tokchan := make(chan tokenStruct, 5)
|
||||
go processResponse(ctx, c.sess, tokchan, c.outs)
|
||||
c.clearOuts()
|
||||
for tok := range tokchan {
|
||||
switch token := tok.(type) {
|
||||
case doneStruct:
|
||||
if token.isError() {
|
||||
return c.checkBadConn(token.getError())
|
||||
}
|
||||
case error:
|
||||
return c.checkBadConn(token)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Conn) Commit() error {
|
||||
if !c.connectionGood {
|
||||
return driver.ErrBadConn
|
||||
}
|
||||
if err := c.sendCommitRequest(); err != nil {
|
||||
return c.checkBadConn(err)
|
||||
}
|
||||
return c.simpleProcessResp(c.transactionCtx)
|
||||
}
|
||||
|
||||
func (c *Conn) sendCommitRequest() error {
|
||||
headers := []headerStruct{
|
||||
{hdrtype: dataStmHdrTransDescr,
|
||||
data: transDescrHdr{c.sess.tranid, 1}.pack()},
|
||||
}
|
||||
reset := c.resetSession
|
||||
c.resetSession = false
|
||||
if err := sendCommitXact(c.sess.buf, headers, "", 0, 0, "", reset); err != nil {
|
||||
if c.sess.logFlags&logErrors != 0 {
|
||||
c.sess.log.Printf("Failed to send CommitXact with %v", err)
|
||||
}
|
||||
c.connectionGood = false
|
||||
return fmt.Errorf("Faild to send CommitXact: %v", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Conn) Rollback() error {
|
||||
if !c.connectionGood {
|
||||
return driver.ErrBadConn
|
||||
}
|
||||
if err := c.sendRollbackRequest(); err != nil {
|
||||
return c.checkBadConn(err)
|
||||
}
|
||||
return c.simpleProcessResp(c.transactionCtx)
|
||||
}
|
||||
|
||||
func (c *Conn) sendRollbackRequest() error {
|
||||
headers := []headerStruct{
|
||||
{hdrtype: dataStmHdrTransDescr,
|
||||
data: transDescrHdr{c.sess.tranid, 1}.pack()},
|
||||
}
|
||||
reset := c.resetSession
|
||||
c.resetSession = false
|
||||
if err := sendRollbackXact(c.sess.buf, headers, "", 0, 0, "", reset); err != nil {
|
||||
if c.sess.logFlags&logErrors != 0 {
|
||||
c.sess.log.Printf("Failed to send RollbackXact with %v", err)
|
||||
}
|
||||
c.connectionGood = false
|
||||
return fmt.Errorf("Failed to send RollbackXact: %v", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Conn) Begin() (driver.Tx, error) {
|
||||
return c.begin(context.Background(), isolationUseCurrent)
|
||||
}
|
||||
|
||||
func (c *Conn) begin(ctx context.Context, tdsIsolation isoLevel) (tx driver.Tx, err error) {
|
||||
if !c.connectionGood {
|
||||
return nil, driver.ErrBadConn
|
||||
}
|
||||
err = c.sendBeginRequest(ctx, tdsIsolation)
|
||||
if err != nil {
|
||||
return nil, c.checkBadConn(err)
|
||||
}
|
||||
tx, err = c.processBeginResponse(ctx)
|
||||
if err != nil {
|
||||
return nil, c.checkBadConn(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (c *Conn) sendBeginRequest(ctx context.Context, tdsIsolation isoLevel) error {
|
||||
c.transactionCtx = ctx
|
||||
headers := []headerStruct{
|
||||
{hdrtype: dataStmHdrTransDescr,
|
||||
data: transDescrHdr{0, 1}.pack()},
|
||||
}
|
||||
reset := c.resetSession
|
||||
c.resetSession = false
|
||||
if err := sendBeginXact(c.sess.buf, headers, tdsIsolation, "", reset); err != nil {
|
||||
if c.sess.logFlags&logErrors != 0 {
|
||||
c.sess.log.Printf("Failed to send BeginXact with %v", err)
|
||||
}
|
||||
c.connectionGood = false
|
||||
return fmt.Errorf("Failed to send BeginXact: %v", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Conn) processBeginResponse(ctx context.Context) (driver.Tx, error) {
|
||||
if err := c.simpleProcessResp(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// successful BEGINXACT request will return sess.tranid
|
||||
// for started transaction
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (d *Driver) open(ctx context.Context, dsn string) (*Conn, error) {
|
||||
params, err := parseConnectParams(dsn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return d.connect(ctx, params)
|
||||
}
|
||||
|
||||
// connect to the server, using the provided context for dialing only.
|
||||
func (d *Driver) connect(ctx context.Context, params connectParams) (*Conn, error) {
|
||||
sess, err := connect(ctx, d.log, params)
|
||||
if err != nil {
|
||||
// main server failed, try fail-over partner
|
||||
if params.failOverPartner == "" {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
params.host = params.failOverPartner
|
||||
if params.failOverPort != 0 {
|
||||
params.port = params.failOverPort
|
||||
}
|
||||
|
||||
sess, err = connect(ctx, d.log, params)
|
||||
if err != nil {
|
||||
// fail-over partner also failed, now fail
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
conn := &Conn{
|
||||
sess: sess,
|
||||
transactionCtx: context.Background(),
|
||||
processQueryText: d.processQueryText,
|
||||
connectionGood: true,
|
||||
}
|
||||
conn.sess.log = d.log
|
||||
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
func (c *Conn) Close() error {
|
||||
return c.sess.buf.transport.Close()
|
||||
}
|
||||
|
||||
type Stmt struct {
|
||||
c *Conn
|
||||
query string
|
||||
paramCount int
|
||||
notifSub *queryNotifSub
|
||||
}
|
||||
|
||||
type queryNotifSub struct {
|
||||
msgText string
|
||||
options string
|
||||
timeout uint32
|
||||
}
|
||||
|
||||
func (c *Conn) Prepare(query string) (driver.Stmt, error) {
|
||||
if !c.connectionGood {
|
||||
return nil, driver.ErrBadConn
|
||||
}
|
||||
if len(query) > 10 && strings.EqualFold(query[:10], "INSERTBULK") {
|
||||
return c.prepareCopyIn(context.Background(), query)
|
||||
}
|
||||
return c.prepareContext(context.Background(), query)
|
||||
}
|
||||
|
||||
func (c *Conn) prepareContext(ctx context.Context, query string) (*Stmt, error) {
|
||||
paramCount := -1
|
||||
if c.processQueryText {
|
||||
query, paramCount = parseParams(query)
|
||||
}
|
||||
return &Stmt{c, query, paramCount, nil}, nil
|
||||
}
|
||||
|
||||
func (s *Stmt) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Stmt) SetQueryNotification(id, options string, timeout time.Duration) {
|
||||
to := uint32(timeout / time.Second)
|
||||
if to < 1 {
|
||||
to = 1
|
||||
}
|
||||
s.notifSub = &queryNotifSub{id, options, to}
|
||||
}
|
||||
|
||||
func (s *Stmt) NumInput() int {
|
||||
return s.paramCount
|
||||
}
|
||||
|
||||
func (s *Stmt) sendQuery(args []namedValue) (err error) {
|
||||
headers := []headerStruct{
|
||||
{hdrtype: dataStmHdrTransDescr,
|
||||
data: transDescrHdr{s.c.sess.tranid, 1}.pack()},
|
||||
}
|
||||
|
||||
if s.notifSub != nil {
|
||||
headers = append(headers,
|
||||
headerStruct{
|
||||
hdrtype: dataStmHdrQueryNotif,
|
||||
data: queryNotifHdr{
|
||||
s.notifSub.msgText,
|
||||
s.notifSub.options,
|
||||
s.notifSub.timeout,
|
||||
}.pack(),
|
||||
})
|
||||
}
|
||||
|
||||
conn := s.c
|
||||
|
||||
// no need to check number of parameters here, it is checked by database/sql
|
||||
if conn.sess.logFlags&logSQL != 0 {
|
||||
conn.sess.log.Println(s.query)
|
||||
}
|
||||
if conn.sess.logFlags&logParams != 0 && len(args) > 0 {
|
||||
for i := 0; i < len(args); i++ {
|
||||
if len(args[i].Name) > 0 {
|
||||
s.c.sess.log.Printf("\t@%s\t%v\n", args[i].Name, args[i].Value)
|
||||
} else {
|
||||
s.c.sess.log.Printf("\t@p%d\t%v\n", i+1, args[i].Value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
reset := conn.resetSession
|
||||
conn.resetSession = false
|
||||
if len(args) == 0 {
|
||||
if err = sendSqlBatch72(conn.sess.buf, s.query, headers, reset); err != nil {
|
||||
if conn.sess.logFlags&logErrors != 0 {
|
||||
conn.sess.log.Printf("Failed to send SqlBatch with %v", err)
|
||||
}
|
||||
conn.connectionGood = false
|
||||
return fmt.Errorf("failed to send SQL Batch: %v", err)
|
||||
}
|
||||
} else {
|
||||
proc := sp_ExecuteSql
|
||||
var params []param
|
||||
if isProc(s.query) {
|
||||
proc.name = s.query
|
||||
params, _, err = s.makeRPCParams(args, 0)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
} else {
|
||||
var decls []string
|
||||
params, decls, err = s.makeRPCParams(args, 2)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
params[0] = makeStrParam(s.query)
|
||||
params[1] = makeStrParam(strings.Join(decls, ","))
|
||||
}
|
||||
if err = sendRpc(conn.sess.buf, headers, proc, 0, params, reset); err != nil {
|
||||
if conn.sess.logFlags&logErrors != 0 {
|
||||
conn.sess.log.Printf("Failed to send Rpc with %v", err)
|
||||
}
|
||||
conn.connectionGood = false
|
||||
return fmt.Errorf("Failed to send RPC: %v", err)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// isProc takes the query text in s and determines if it is a stored proc name
|
||||
// or SQL text.
|
||||
func isProc(s string) bool {
|
||||
if len(s) == 0 {
|
||||
return false
|
||||
}
|
||||
const (
|
||||
outside = iota
|
||||
text
|
||||
escaped
|
||||
)
|
||||
st := outside
|
||||
var rn1, rPrev rune
|
||||
for _, r := range s {
|
||||
rPrev = rn1
|
||||
rn1 = r
|
||||
switch r {
|
||||
// No newlines or string sequences.
|
||||
case '\n', '\r', '\'', ';':
|
||||
return false
|
||||
}
|
||||
switch st {
|
||||
case outside:
|
||||
switch {
|
||||
case unicode.IsSpace(r):
|
||||
return false
|
||||
case r == '[':
|
||||
st = escaped
|
||||
continue
|
||||
case r == ']' && rPrev == ']':
|
||||
st = escaped
|
||||
continue
|
||||
case unicode.IsLetter(r):
|
||||
st = text
|
||||
}
|
||||
case text:
|
||||
switch {
|
||||
case r == '.':
|
||||
st = outside
|
||||
continue
|
||||
case unicode.IsSpace(r):
|
||||
return false
|
||||
}
|
||||
case escaped:
|
||||
switch {
|
||||
case r == ']':
|
||||
st = outside
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Stmt) makeRPCParams(args []namedValue, offset int) ([]param, []string, error) {
|
||||
var err error
|
||||
params := make([]param, len(args)+offset)
|
||||
decls := make([]string, len(args))
|
||||
for i, val := range args {
|
||||
params[i+offset], err = s.makeParam(val.Value)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
var name string
|
||||
if len(val.Name) > 0 {
|
||||
name = "@" + val.Name
|
||||
} else {
|
||||
name = fmt.Sprintf("@p%d", val.Ordinal)
|
||||
}
|
||||
params[i+offset].Name = name
|
||||
decls[i] = fmt.Sprintf("%s %s", name, makeDecl(params[i+offset].ti))
|
||||
}
|
||||
return params, decls, nil
|
||||
}
|
||||
|
||||
type namedValue struct {
|
||||
Name string
|
||||
Ordinal int
|
||||
Value driver.Value
|
||||
}
|
||||
|
||||
func convertOldArgs(args []driver.Value) []namedValue {
|
||||
list := make([]namedValue, len(args))
|
||||
for i, v := range args {
|
||||
list[i] = namedValue{
|
||||
Ordinal: i + 1,
|
||||
Value: v,
|
||||
}
|
||||
}
|
||||
return list
|
||||
}
|
||||
|
||||
func (s *Stmt) Query(args []driver.Value) (driver.Rows, error) {
|
||||
return s.queryContext(context.Background(), convertOldArgs(args))
|
||||
}
|
||||
|
||||
func (s *Stmt) queryContext(ctx context.Context, args []namedValue) (rows driver.Rows, err error) {
|
||||
if !s.c.connectionGood {
|
||||
return nil, driver.ErrBadConn
|
||||
}
|
||||
if err = s.sendQuery(args); err != nil {
|
||||
return nil, s.c.checkBadConn(err)
|
||||
}
|
||||
return s.processQueryResponse(ctx)
|
||||
}
|
||||
|
||||
func (s *Stmt) processQueryResponse(ctx context.Context) (res driver.Rows, err error) {
|
||||
tokchan := make(chan tokenStruct, 5)
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
go processResponse(ctx, s.c.sess, tokchan, s.c.outs)
|
||||
s.c.clearOuts()
|
||||
// process metadata
|
||||
var cols []columnStruct
|
||||
loop:
|
||||
for tok := range tokchan {
|
||||
switch token := tok.(type) {
|
||||
// By ignoring DONE token we effectively
|
||||
// skip empty result-sets.
|
||||
// This improves results in queries like that:
|
||||
// set nocount on; select 1
|
||||
// see TestIgnoreEmptyResults test
|
||||
//case doneStruct:
|
||||
//break loop
|
||||
case []columnStruct:
|
||||
cols = token
|
||||
break loop
|
||||
case doneStruct:
|
||||
if token.isError() {
|
||||
return nil, s.c.checkBadConn(token.getError())
|
||||
}
|
||||
case ReturnStatus:
|
||||
s.c.setReturnStatus(token)
|
||||
case error:
|
||||
return nil, s.c.checkBadConn(token)
|
||||
}
|
||||
}
|
||||
res = &Rows{stmt: s, tokchan: tokchan, cols: cols, cancel: cancel}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Stmt) Exec(args []driver.Value) (driver.Result, error) {
|
||||
return s.exec(context.Background(), convertOldArgs(args))
|
||||
}
|
||||
|
||||
func (s *Stmt) exec(ctx context.Context, args []namedValue) (res driver.Result, err error) {
|
||||
if !s.c.connectionGood {
|
||||
return nil, driver.ErrBadConn
|
||||
}
|
||||
if err = s.sendQuery(args); err != nil {
|
||||
return nil, s.c.checkBadConn(err)
|
||||
}
|
||||
if res, err = s.processExec(ctx); err != nil {
|
||||
return nil, s.c.checkBadConn(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Stmt) processExec(ctx context.Context) (res driver.Result, err error) {
|
||||
tokchan := make(chan tokenStruct, 5)
|
||||
go processResponse(ctx, s.c.sess, tokchan, s.c.outs)
|
||||
s.c.clearOuts()
|
||||
var rowCount int64
|
||||
for token := range tokchan {
|
||||
switch token := token.(type) {
|
||||
case doneInProcStruct:
|
||||
if token.Status&doneCount != 0 {
|
||||
rowCount += int64(token.RowCount)
|
||||
}
|
||||
case doneStruct:
|
||||
if token.Status&doneCount != 0 {
|
||||
rowCount += int64(token.RowCount)
|
||||
}
|
||||
if token.isError() {
|
||||
return nil, token.getError()
|
||||
}
|
||||
case ReturnStatus:
|
||||
s.c.setReturnStatus(token)
|
||||
case error:
|
||||
return nil, token
|
||||
}
|
||||
}
|
||||
return &Result{s.c, rowCount}, nil
|
||||
}
|
||||
|
||||
type Rows struct {
|
||||
stmt *Stmt
|
||||
cols []columnStruct
|
||||
tokchan chan tokenStruct
|
||||
|
||||
nextCols []columnStruct
|
||||
|
||||
cancel func()
|
||||
}
|
||||
|
||||
func (rc *Rows) Close() error {
|
||||
rc.cancel()
|
||||
for _ = range rc.tokchan {
|
||||
}
|
||||
rc.tokchan = nil
|
||||
return nil
|
||||
}
|
||||
|
||||
func (rc *Rows) Columns() (res []string) {
|
||||
res = make([]string, len(rc.cols))
|
||||
for i, col := range rc.cols {
|
||||
res[i] = col.ColName
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (rc *Rows) Next(dest []driver.Value) error {
|
||||
if !rc.stmt.c.connectionGood {
|
||||
return driver.ErrBadConn
|
||||
}
|
||||
if rc.nextCols != nil {
|
||||
return io.EOF
|
||||
}
|
||||
for tok := range rc.tokchan {
|
||||
switch tokdata := tok.(type) {
|
||||
case []columnStruct:
|
||||
rc.nextCols = tokdata
|
||||
return io.EOF
|
||||
case []interface{}:
|
||||
for i := range dest {
|
||||
dest[i] = tokdata[i]
|
||||
}
|
||||
return nil
|
||||
case doneStruct:
|
||||
if tokdata.isError() {
|
||||
return rc.stmt.c.checkBadConn(tokdata.getError())
|
||||
}
|
||||
case error:
|
||||
return rc.stmt.c.checkBadConn(tokdata)
|
||||
}
|
||||
}
|
||||
return io.EOF
|
||||
}
|
||||
|
||||
func (rc *Rows) HasNextResultSet() bool {
|
||||
return rc.nextCols != nil
|
||||
}
|
||||
|
||||
func (rc *Rows) NextResultSet() error {
|
||||
rc.cols = rc.nextCols
|
||||
rc.nextCols = nil
|
||||
if rc.cols == nil {
|
||||
return io.EOF
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// It should return
|
||||
// the value type that can be used to scan types into. For example, the database
|
||||
// column type "bigint" this should return "reflect.TypeOf(int64(0))".
|
||||
func (r *Rows) ColumnTypeScanType(index int) reflect.Type {
|
||||
return makeGoLangScanType(r.cols[index].ti)
|
||||
}
|
||||
|
||||
// RowsColumnTypeDatabaseTypeName may be implemented by Rows. It should return the
|
||||
// database system type name without the length. Type names should be uppercase.
|
||||
// Examples of returned types: "VARCHAR", "NVARCHAR", "VARCHAR2", "CHAR", "TEXT",
|
||||
// "DECIMAL", "SMALLINT", "INT", "BIGINT", "BOOL", "[]BIGINT", "JSONB", "XML",
|
||||
// "TIMESTAMP".
|
||||
func (r *Rows) ColumnTypeDatabaseTypeName(index int) string {
|
||||
return makeGoLangTypeName(r.cols[index].ti)
|
||||
}
|
||||
|
||||
// RowsColumnTypeLength may be implemented by Rows. It should return the length
|
||||
// of the column type if the column is a variable length type. If the column is
|
||||
// not a variable length type ok should return false.
|
||||
// If length is not limited other than system limits, it should return math.MaxInt64.
|
||||
// The following are examples of returned values for various types:
|
||||
// TEXT (math.MaxInt64, true)
|
||||
// varchar(10) (10, true)
|
||||
// nvarchar(10) (10, true)
|
||||
// decimal (0, false)
|
||||
// int (0, false)
|
||||
// bytea(30) (30, true)
|
||||
func (r *Rows) ColumnTypeLength(index int) (int64, bool) {
|
||||
return makeGoLangTypeLength(r.cols[index].ti)
|
||||
}
|
||||
|
||||
// It should return
|
||||
// the precision and scale for decimal types. If not applicable, ok should be false.
|
||||
// The following are examples of returned values for various types:
|
||||
// decimal(38, 4) (38, 4, true)
|
||||
// int (0, 0, false)
|
||||
// decimal (math.MaxInt64, math.MaxInt64, true)
|
||||
func (r *Rows) ColumnTypePrecisionScale(index int) (int64, int64, bool) {
|
||||
return makeGoLangTypePrecisionScale(r.cols[index].ti)
|
||||
}
|
||||
|
||||
// The nullable value should
|
||||
// be true if it is known the column may be null, or false if the column is known
|
||||
// to be not nullable.
|
||||
// If the column nullability is unknown, ok should be false.
|
||||
func (r *Rows) ColumnTypeNullable(index int) (nullable, ok bool) {
|
||||
nullable = r.cols[index].Flags&colFlagNullable != 0
|
||||
ok = true
|
||||
return
|
||||
}
|
||||
|
||||
func makeStrParam(val string) (res param) {
|
||||
res.ti.TypeId = typeNVarChar
|
||||
res.buffer = str2ucs2(val)
|
||||
res.ti.Size = len(res.buffer)
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Stmt) makeParam(val driver.Value) (res param, err error) {
|
||||
if val == nil {
|
||||
res.ti.TypeId = typeNull
|
||||
res.buffer = nil
|
||||
res.ti.Size = 0
|
||||
return
|
||||
}
|
||||
switch val := val.(type) {
|
||||
case int64:
|
||||
res.ti.TypeId = typeIntN
|
||||
res.buffer = make([]byte, 8)
|
||||
res.ti.Size = 8
|
||||
binary.LittleEndian.PutUint64(res.buffer, uint64(val))
|
||||
case sql.NullInt64:
|
||||
// only null values should be getting here
|
||||
res.ti.TypeId = typeIntN
|
||||
res.ti.Size = 8
|
||||
res.buffer = []byte{}
|
||||
|
||||
case float64:
|
||||
res.ti.TypeId = typeFltN
|
||||
res.ti.Size = 8
|
||||
res.buffer = make([]byte, 8)
|
||||
binary.LittleEndian.PutUint64(res.buffer, math.Float64bits(val))
|
||||
case sql.NullFloat64:
|
||||
// only null values should be getting here
|
||||
res.ti.TypeId = typeFltN
|
||||
res.ti.Size = 8
|
||||
res.buffer = []byte{}
|
||||
|
||||
case []byte:
|
||||
res.ti.TypeId = typeBigVarBin
|
||||
res.ti.Size = len(val)
|
||||
res.buffer = val
|
||||
case string:
|
||||
res = makeStrParam(val)
|
||||
case sql.NullString:
|
||||
// only null values should be getting here
|
||||
res.ti.TypeId = typeNVarChar
|
||||
res.buffer = nil
|
||||
res.ti.Size = 8000
|
||||
case bool:
|
||||
res.ti.TypeId = typeBitN
|
||||
res.ti.Size = 1
|
||||
res.buffer = make([]byte, 1)
|
||||
if val {
|
||||
res.buffer[0] = 1
|
||||
}
|
||||
case sql.NullBool:
|
||||
// only null values should be getting here
|
||||
res.ti.TypeId = typeBitN
|
||||
res.ti.Size = 1
|
||||
res.buffer = []byte{}
|
||||
|
||||
case time.Time:
|
||||
if s.c.sess.loginAck.TDSVersion >= verTDS73 {
|
||||
res.ti.TypeId = typeDateTimeOffsetN
|
||||
res.ti.Scale = 7
|
||||
res.buffer = encodeDateTimeOffset(val, int(res.ti.Scale))
|
||||
res.ti.Size = len(res.buffer)
|
||||
} else {
|
||||
res.ti.TypeId = typeDateTimeN
|
||||
res.buffer = encodeDateTime(val)
|
||||
res.ti.Size = len(res.buffer)
|
||||
}
|
||||
default:
|
||||
return s.makeParamExtra(val)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type Result struct {
|
||||
c *Conn
|
||||
rowsAffected int64
|
||||
}
|
||||
|
||||
func (r *Result) RowsAffected() (int64, error) {
|
||||
return r.rowsAffected, nil
|
||||
}
|
||||
|
||||
func (r *Result) LastInsertId() (int64, error) {
|
||||
s, err := r.c.Prepare("select cast(@@identity as bigint)")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer s.Close()
|
||||
rows, err := s.Query(nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
dest := make([]driver.Value, 1)
|
||||
err = rows.Next(dest)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if dest[0] == nil {
|
||||
return -1, errors.New("There is no generated identity value")
|
||||
}
|
||||
lastInsertId := dest[0].(int64)
|
||||
return lastInsertId, nil
|
||||
}
|
||||
|
||||
var _ driver.Pinger = &Conn{}
|
||||
|
||||
// Ping is used to check if the remote server is available and satisfies the Pinger interface.
|
||||
func (c *Conn) Ping(ctx context.Context) error {
|
||||
if !c.connectionGood {
|
||||
return driver.ErrBadConn
|
||||
}
|
||||
stmt := &Stmt{c, `select 1;`, 0, nil}
|
||||
_, err := stmt.ExecContext(ctx, nil)
|
||||
return err
|
||||
}
|
||||
|
||||
var _ driver.ConnBeginTx = &Conn{}
|
||||
|
||||
// BeginTx satisfies ConnBeginTx.
|
||||
func (c *Conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) {
|
||||
if !c.connectionGood {
|
||||
return nil, driver.ErrBadConn
|
||||
}
|
||||
if opts.ReadOnly {
|
||||
return nil, errors.New("Read-only transactions are not supported")
|
||||
}
|
||||
|
||||
var tdsIsolation isoLevel
|
||||
switch sql.IsolationLevel(opts.Isolation) {
|
||||
case sql.LevelDefault:
|
||||
tdsIsolation = isolationUseCurrent
|
||||
case sql.LevelReadUncommitted:
|
||||
tdsIsolation = isolationReadUncommited
|
||||
case sql.LevelReadCommitted:
|
||||
tdsIsolation = isolationReadCommited
|
||||
case sql.LevelWriteCommitted:
|
||||
return nil, errors.New("LevelWriteCommitted isolation level is not supported")
|
||||
case sql.LevelRepeatableRead:
|
||||
tdsIsolation = isolationRepeatableRead
|
||||
case sql.LevelSnapshot:
|
||||
tdsIsolation = isolationSnapshot
|
||||
case sql.LevelSerializable:
|
||||
tdsIsolation = isolationSerializable
|
||||
case sql.LevelLinearizable:
|
||||
return nil, errors.New("LevelLinearizable isolation level is not supported")
|
||||
default:
|
||||
return nil, errors.New("Isolation level is not supported or unknown")
|
||||
}
|
||||
return c.begin(ctx, tdsIsolation)
|
||||
}
|
||||
|
||||
func (c *Conn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) {
|
||||
if !c.connectionGood {
|
||||
return nil, driver.ErrBadConn
|
||||
}
|
||||
if len(query) > 10 && strings.EqualFold(query[:10], "INSERTBULK") {
|
||||
return c.prepareCopyIn(ctx, query)
|
||||
}
|
||||
|
||||
return c.prepareContext(ctx, query)
|
||||
}
|
||||
|
||||
func (s *Stmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) {
|
||||
if !s.c.connectionGood {
|
||||
return nil, driver.ErrBadConn
|
||||
}
|
||||
list := make([]namedValue, len(args))
|
||||
for i, nv := range args {
|
||||
list[i] = namedValue(nv)
|
||||
}
|
||||
return s.queryContext(ctx, list)
|
||||
}
|
||||
|
||||
func (s *Stmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error) {
|
||||
if !s.c.connectionGood {
|
||||
return nil, driver.ErrBadConn
|
||||
}
|
||||
list := make([]namedValue, len(args))
|
||||
for i, nv := range args {
|
||||
list[i] = namedValue(nv)
|
||||
}
|
||||
return s.exec(ctx, list)
|
||||
}
|
|
@ -0,0 +1,50 @@
|
|||
// +build go1.10
|
||||
|
||||
package mssql
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql/driver"
|
||||
)
|
||||
|
||||
var _ driver.Connector = &Connector{}
|
||||
var _ driver.SessionResetter = &Conn{}
|
||||
|
||||
func (c *Conn) ResetSession(ctx context.Context) error {
|
||||
if !c.connectionGood {
|
||||
return driver.ErrBadConn
|
||||
}
|
||||
c.resetSession = true
|
||||
|
||||
if c.connector == nil || len(c.connector.SessionInitSQL) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
s, err := c.prepareContext(ctx, c.connector.SessionInitSQL)
|
||||
if err != nil {
|
||||
return driver.ErrBadConn
|
||||
}
|
||||
_, err = s.exec(ctx, nil)
|
||||
if err != nil {
|
||||
return driver.ErrBadConn
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Connect to the server and return a TDS connection.
|
||||
func (c *Connector) Connect(ctx context.Context) (driver.Conn, error) {
|
||||
conn, err := c.driver.connect(ctx, c.params)
|
||||
if conn != nil {
|
||||
conn.connector = c
|
||||
}
|
||||
if err == nil {
|
||||
err = conn.ResetSession(ctx)
|
||||
}
|
||||
return conn, err
|
||||
}
|
||||
|
||||
// Driver underlying the Connector.
|
||||
func (c *Connector) Driver() driver.Driver {
|
||||
return c.driver
|
||||
}
|
|
@ -0,0 +1,171 @@
|
|||
// +build go1.9
|
||||
|
||||
package mssql
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"database/sql/driver"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"time"
|
||||
|
||||
// "github.com/cockroachdb/apd"
|
||||
"cloud.google.com/go/civil"
|
||||
)
|
||||
|
||||
// Type alias provided for compatibility.
|
||||
|
||||
type MssqlDriver = Driver // Deprecated: users should transition to the new name when possible.
|
||||
type MssqlBulk = Bulk // Deprecated: users should transition to the new name when possible.
|
||||
type MssqlBulkOptions = BulkOptions // Deprecated: users should transition to the new name when possible.
|
||||
type MssqlConn = Conn // Deprecated: users should transition to the new name when possible.
|
||||
type MssqlResult = Result // Deprecated: users should transition to the new name when possible.
|
||||
type MssqlRows = Rows // Deprecated: users should transition to the new name when possible.
|
||||
type MssqlStmt = Stmt // Deprecated: users should transition to the new name when possible.
|
||||
|
||||
var _ driver.NamedValueChecker = &Conn{}
|
||||
|
||||
// VarChar parameter types.
|
||||
type VarChar string
|
||||
|
||||
type NVarCharMax string
|
||||
type VarCharMax string
|
||||
|
||||
// DateTime1 encodes parameters to original DateTime SQL types.
|
||||
type DateTime1 time.Time
|
||||
|
||||
// DateTimeOffset encodes parameters to DateTimeOffset, preserving the UTC offset.
|
||||
type DateTimeOffset time.Time
|
||||
|
||||
func convertInputParameter(val interface{}) (interface{}, error) {
|
||||
switch v := val.(type) {
|
||||
case VarChar:
|
||||
return val, nil
|
||||
case NVarCharMax:
|
||||
return val, nil
|
||||
case VarCharMax:
|
||||
return val, nil
|
||||
case DateTime1:
|
||||
return val, nil
|
||||
case DateTimeOffset:
|
||||
return val, nil
|
||||
case civil.Date:
|
||||
return val, nil
|
||||
case civil.DateTime:
|
||||
return val, nil
|
||||
case civil.Time:
|
||||
return val, nil
|
||||
// case *apd.Decimal:
|
||||
// return nil
|
||||
default:
|
||||
return driver.DefaultParameterConverter.ConvertValue(v)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Conn) CheckNamedValue(nv *driver.NamedValue) error {
|
||||
switch v := nv.Value.(type) {
|
||||
case sql.Out:
|
||||
if c.outs == nil {
|
||||
c.outs = make(map[string]interface{})
|
||||
}
|
||||
c.outs[nv.Name] = v.Dest
|
||||
|
||||
if v.Dest == nil {
|
||||
return errors.New("destination is a nil pointer")
|
||||
}
|
||||
|
||||
dest_info := reflect.ValueOf(v.Dest)
|
||||
if dest_info.Kind() != reflect.Ptr {
|
||||
return errors.New("destination not a pointer")
|
||||
}
|
||||
|
||||
if dest_info.IsNil() {
|
||||
return errors.New("destination is a nil pointer")
|
||||
}
|
||||
|
||||
pointed_value := reflect.Indirect(dest_info)
|
||||
|
||||
// don't allow pointer to a pointer, only pointer to a value can be handled
|
||||
// correctly
|
||||
if pointed_value.Kind() == reflect.Ptr {
|
||||
return errors.New("destination is a pointer to a pointer")
|
||||
}
|
||||
|
||||
// Unwrap the Out value and check the inner value.
|
||||
val := pointed_value.Interface()
|
||||
if val == nil {
|
||||
return errors.New("MSSQL does not allow NULL value without type for OUTPUT parameters")
|
||||
}
|
||||
conv, err := convertInputParameter(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if conv == nil {
|
||||
// if we replace with nil we would lose type information
|
||||
nv.Value = sql.Out{Dest: val}
|
||||
} else {
|
||||
nv.Value = sql.Out{Dest: conv}
|
||||
}
|
||||
return nil
|
||||
case *ReturnStatus:
|
||||
*v = 0 // By default the return value should be zero.
|
||||
c.returnStatus = v
|
||||
return driver.ErrRemoveArgument
|
||||
default:
|
||||
var err error
|
||||
nv.Value, err = convertInputParameter(nv.Value)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Stmt) makeParamExtra(val driver.Value) (res param, err error) {
|
||||
switch val := val.(type) {
|
||||
case VarChar:
|
||||
res.ti.TypeId = typeBigVarChar
|
||||
res.buffer = []byte(val)
|
||||
res.ti.Size = len(res.buffer)
|
||||
case VarCharMax:
|
||||
res.ti.TypeId = typeBigVarChar
|
||||
res.buffer = []byte(val)
|
||||
res.ti.Size = 0 // currently zero forces varchar(max)
|
||||
case NVarCharMax:
|
||||
res.ti.TypeId = typeNVarChar
|
||||
res.buffer = str2ucs2(string(val))
|
||||
res.ti.Size = 0 // currently zero forces nvarchar(max)
|
||||
case DateTime1:
|
||||
t := time.Time(val)
|
||||
res.ti.TypeId = typeDateTimeN
|
||||
res.buffer = encodeDateTime(t)
|
||||
res.ti.Size = len(res.buffer)
|
||||
case DateTimeOffset:
|
||||
res.ti.TypeId = typeDateTimeOffsetN
|
||||
res.ti.Scale = 7
|
||||
res.buffer = encodeDateTimeOffset(time.Time(val), int(res.ti.Scale))
|
||||
res.ti.Size = len(res.buffer)
|
||||
case civil.Date:
|
||||
res.ti.TypeId = typeDateN
|
||||
res.buffer = encodeDate(val.In(time.UTC))
|
||||
res.ti.Size = len(res.buffer)
|
||||
case civil.DateTime:
|
||||
res.ti.TypeId = typeDateTime2N
|
||||
res.ti.Scale = 7
|
||||
res.buffer = encodeDateTime2(val.In(time.UTC), int(res.ti.Scale))
|
||||
res.ti.Size = len(res.buffer)
|
||||
case civil.Time:
|
||||
res.ti.TypeId = typeTimeN
|
||||
res.ti.Scale = 7
|
||||
res.buffer = encodeTime(val.Hour, val.Minute, val.Second, val.Nanosecond, int(res.ti.Scale))
|
||||
res.ti.Size = len(res.buffer)
|
||||
case sql.Out:
|
||||
res, err = s.makeParam(val.Dest)
|
||||
res.Flags = fByRevValue
|
||||
default:
|
||||
err = fmt.Errorf("mssql: unknown type for %T", val)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func scanIntoOut(name string, fromServer, scanInto interface{}) error {
|
||||
return convertAssign(scanInto, fromServer)
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
// +build !go1.9
|
||||
|
||||
package mssql
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func (s *Stmt) makeParamExtra(val driver.Value) (param, error) {
|
||||
return param{}, fmt.Errorf("mssql: unknown type for %T", val)
|
||||
}
|
||||
|
||||
func scanIntoOut(name string, fromServer, scanInto interface{}) error {
|
||||
return fmt.Errorf("mssql: unsupported OUTPUT type, use a newer Go version")
|
||||
}
|
|
@ -0,0 +1,103 @@
|
|||
package mssql
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"time"
|
||||
)
|
||||
|
||||
type timeoutConn struct {
|
||||
c net.Conn
|
||||
timeout time.Duration
|
||||
buf *tdsBuffer
|
||||
packetPending bool
|
||||
continueRead bool
|
||||
}
|
||||
|
||||
func newTimeoutConn(conn net.Conn, timeout time.Duration) *timeoutConn {
|
||||
return &timeoutConn{
|
||||
c: conn,
|
||||
timeout: timeout,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *timeoutConn) Read(b []byte) (n int, err error) {
|
||||
if c.buf != nil {
|
||||
if c.packetPending {
|
||||
c.packetPending = false
|
||||
err = c.buf.FinishPacket()
|
||||
if err != nil {
|
||||
err = fmt.Errorf("Cannot send handshake packet: %s", err.Error())
|
||||
return
|
||||
}
|
||||
c.continueRead = false
|
||||
}
|
||||
if !c.continueRead {
|
||||
var packet packetType
|
||||
packet, err = c.buf.BeginRead()
|
||||
if err != nil {
|
||||
err = fmt.Errorf("Cannot read handshake packet: %s", err.Error())
|
||||
return
|
||||
}
|
||||
if packet != packPrelogin {
|
||||
err = fmt.Errorf("unexpected packet %d, expecting prelogin", packet)
|
||||
return
|
||||
}
|
||||
c.continueRead = true
|
||||
}
|
||||
n, err = c.buf.Read(b)
|
||||
return
|
||||
}
|
||||
if c.timeout > 0 {
|
||||
err = c.c.SetDeadline(time.Now().Add(c.timeout))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
return c.c.Read(b)
|
||||
}
|
||||
|
||||
func (c *timeoutConn) Write(b []byte) (n int, err error) {
|
||||
if c.buf != nil {
|
||||
if !c.packetPending {
|
||||
c.buf.BeginPacket(packPrelogin, false)
|
||||
c.packetPending = true
|
||||
}
|
||||
n, err = c.buf.Write(b)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
if c.timeout > 0 {
|
||||
err = c.c.SetDeadline(time.Now().Add(c.timeout))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
return c.c.Write(b)
|
||||
}
|
||||
|
||||
func (c timeoutConn) Close() error {
|
||||
return c.c.Close()
|
||||
}
|
||||
|
||||
func (c timeoutConn) LocalAddr() net.Addr {
|
||||
return c.c.LocalAddr()
|
||||
}
|
||||
|
||||
func (c timeoutConn) RemoteAddr() net.Addr {
|
||||
return c.c.RemoteAddr()
|
||||
}
|
||||
|
||||
func (c timeoutConn) SetDeadline(t time.Time) error {
|
||||
panic("Not implemented")
|
||||
}
|
||||
|
||||
func (c timeoutConn) SetReadDeadline(t time.Time) error {
|
||||
panic("Not implemented")
|
||||
}
|
||||
|
||||
func (c timeoutConn) SetWriteDeadline(t time.Time) error {
|
||||
panic("Not implemented")
|
||||
}
|
|
@ -0,0 +1,283 @@
|
|||
// +build !windows
|
||||
|
||||
package mssql
|
||||
|
||||
import (
|
||||
"crypto/des"
|
||||
"crypto/md5"
|
||||
"crypto/rand"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"strings"
|
||||
"unicode/utf16"
|
||||
|
||||
"golang.org/x/crypto/md4"
|
||||
)
|
||||
|
||||
const (
|
||||
_NEGOTIATE_MESSAGE = 1
|
||||
_CHALLENGE_MESSAGE = 2
|
||||
_AUTHENTICATE_MESSAGE = 3
|
||||
)
|
||||
|
||||
const (
|
||||
_NEGOTIATE_UNICODE = 0x00000001
|
||||
_NEGOTIATE_OEM = 0x00000002
|
||||
_NEGOTIATE_TARGET = 0x00000004
|
||||
_NEGOTIATE_SIGN = 0x00000010
|
||||
_NEGOTIATE_SEAL = 0x00000020
|
||||
_NEGOTIATE_DATAGRAM = 0x00000040
|
||||
_NEGOTIATE_LMKEY = 0x00000080
|
||||
_NEGOTIATE_NTLM = 0x00000200
|
||||
_NEGOTIATE_ANONYMOUS = 0x00000800
|
||||
_NEGOTIATE_OEM_DOMAIN_SUPPLIED = 0x00001000
|
||||
_NEGOTIATE_OEM_WORKSTATION_SUPPLIED = 0x00002000
|
||||
_NEGOTIATE_ALWAYS_SIGN = 0x00008000
|
||||
_NEGOTIATE_TARGET_TYPE_DOMAIN = 0x00010000
|
||||
_NEGOTIATE_TARGET_TYPE_SERVER = 0x00020000
|
||||
_NEGOTIATE_EXTENDED_SESSIONSECURITY = 0x00080000
|
||||
_NEGOTIATE_IDENTIFY = 0x00100000
|
||||
_REQUEST_NON_NT_SESSION_KEY = 0x00400000
|
||||
_NEGOTIATE_TARGET_INFO = 0x00800000
|
||||
_NEGOTIATE_VERSION = 0x02000000
|
||||
_NEGOTIATE_128 = 0x20000000
|
||||
_NEGOTIATE_KEY_EXCH = 0x40000000
|
||||
_NEGOTIATE_56 = 0x80000000
|
||||
)
|
||||
|
||||
const _NEGOTIATE_FLAGS = _NEGOTIATE_UNICODE |
|
||||
_NEGOTIATE_NTLM |
|
||||
_NEGOTIATE_OEM_DOMAIN_SUPPLIED |
|
||||
_NEGOTIATE_OEM_WORKSTATION_SUPPLIED |
|
||||
_NEGOTIATE_ALWAYS_SIGN |
|
||||
_NEGOTIATE_EXTENDED_SESSIONSECURITY
|
||||
|
||||
type ntlmAuth struct {
|
||||
Domain string
|
||||
UserName string
|
||||
Password string
|
||||
Workstation string
|
||||
}
|
||||
|
||||
func getAuth(user, password, service, workstation string) (auth, bool) {
|
||||
if !strings.ContainsRune(user, '\\') {
|
||||
return nil, false
|
||||
}
|
||||
domain_user := strings.SplitN(user, "\\", 2)
|
||||
return &ntlmAuth{
|
||||
Domain: domain_user[0],
|
||||
UserName: domain_user[1],
|
||||
Password: password,
|
||||
Workstation: workstation,
|
||||
}, true
|
||||
}
|
||||
|
||||
func utf16le(val string) []byte {
|
||||
var v []byte
|
||||
for _, r := range val {
|
||||
if utf16.IsSurrogate(r) {
|
||||
r1, r2 := utf16.EncodeRune(r)
|
||||
v = append(v, byte(r1), byte(r1>>8))
|
||||
v = append(v, byte(r2), byte(r2>>8))
|
||||
} else {
|
||||
v = append(v, byte(r), byte(r>>8))
|
||||
}
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func (auth *ntlmAuth) InitialBytes() ([]byte, error) {
|
||||
domain_len := len(auth.Domain)
|
||||
workstation_len := len(auth.Workstation)
|
||||
msg := make([]byte, 40+domain_len+workstation_len)
|
||||
copy(msg, []byte("NTLMSSP\x00"))
|
||||
binary.LittleEndian.PutUint32(msg[8:], _NEGOTIATE_MESSAGE)
|
||||
binary.LittleEndian.PutUint32(msg[12:], _NEGOTIATE_FLAGS)
|
||||
// Domain Name Fields
|
||||
binary.LittleEndian.PutUint16(msg[16:], uint16(domain_len))
|
||||
binary.LittleEndian.PutUint16(msg[18:], uint16(domain_len))
|
||||
binary.LittleEndian.PutUint32(msg[20:], 40)
|
||||
// Workstation Fields
|
||||
binary.LittleEndian.PutUint16(msg[24:], uint16(workstation_len))
|
||||
binary.LittleEndian.PutUint16(msg[26:], uint16(workstation_len))
|
||||
binary.LittleEndian.PutUint32(msg[28:], uint32(40+domain_len))
|
||||
// Version
|
||||
binary.LittleEndian.PutUint32(msg[32:], 0)
|
||||
binary.LittleEndian.PutUint32(msg[36:], 0)
|
||||
// Payload
|
||||
copy(msg[40:], auth.Domain)
|
||||
copy(msg[40+domain_len:], auth.Workstation)
|
||||
return msg, nil
|
||||
}
|
||||
|
||||
var errorNTLM = errors.New("NTLM protocol error")
|
||||
|
||||
func createDesKey(bytes, material []byte) {
|
||||
material[0] = bytes[0]
|
||||
material[1] = (byte)(bytes[0]<<7 | (bytes[1]&0xff)>>1)
|
||||
material[2] = (byte)(bytes[1]<<6 | (bytes[2]&0xff)>>2)
|
||||
material[3] = (byte)(bytes[2]<<5 | (bytes[3]&0xff)>>3)
|
||||
material[4] = (byte)(bytes[3]<<4 | (bytes[4]&0xff)>>4)
|
||||
material[5] = (byte)(bytes[4]<<3 | (bytes[5]&0xff)>>5)
|
||||
material[6] = (byte)(bytes[5]<<2 | (bytes[6]&0xff)>>6)
|
||||
material[7] = (byte)(bytes[6] << 1)
|
||||
}
|
||||
|
||||
func oddParity(bytes []byte) {
|
||||
for i := 0; i < len(bytes); i++ {
|
||||
b := bytes[i]
|
||||
needsParity := (((b >> 7) ^ (b >> 6) ^ (b >> 5) ^ (b >> 4) ^ (b >> 3) ^ (b >> 2) ^ (b >> 1)) & 0x01) == 0
|
||||
if needsParity {
|
||||
bytes[i] = bytes[i] | byte(0x01)
|
||||
} else {
|
||||
bytes[i] = bytes[i] & byte(0xfe)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func encryptDes(key []byte, cleartext []byte, ciphertext []byte) {
|
||||
var desKey [8]byte
|
||||
createDesKey(key, desKey[:])
|
||||
cipher, err := des.NewCipher(desKey[:])
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
cipher.Encrypt(ciphertext, cleartext)
|
||||
}
|
||||
|
||||
func response(challenge [8]byte, hash [21]byte) (ret [24]byte) {
|
||||
encryptDes(hash[:7], challenge[:], ret[:8])
|
||||
encryptDes(hash[7:14], challenge[:], ret[8:16])
|
||||
encryptDes(hash[14:], challenge[:], ret[16:])
|
||||
return
|
||||
}
|
||||
|
||||
func lmHash(password string) (hash [21]byte) {
|
||||
var lmpass [14]byte
|
||||
copy(lmpass[:14], []byte(strings.ToUpper(password)))
|
||||
magic := []byte("KGS!@#$%")
|
||||
encryptDes(lmpass[:7], magic, hash[:8])
|
||||
encryptDes(lmpass[7:], magic, hash[8:])
|
||||
return
|
||||
}
|
||||
|
||||
func lmResponse(challenge [8]byte, password string) [24]byte {
|
||||
hash := lmHash(password)
|
||||
return response(challenge, hash)
|
||||
}
|
||||
|
||||
func ntlmHash(password string) (hash [21]byte) {
|
||||
h := md4.New()
|
||||
h.Write(utf16le(password))
|
||||
h.Sum(hash[:0])
|
||||
return
|
||||
}
|
||||
|
||||
func ntResponse(challenge [8]byte, password string) [24]byte {
|
||||
hash := ntlmHash(password)
|
||||
return response(challenge, hash)
|
||||
}
|
||||
|
||||
func clientChallenge() (nonce [8]byte) {
|
||||
_, err := rand.Read(nonce[:])
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func ntlmSessionResponse(clientNonce [8]byte, serverChallenge [8]byte, password string) [24]byte {
|
||||
var sessionHash [16]byte
|
||||
h := md5.New()
|
||||
h.Write(serverChallenge[:])
|
||||
h.Write(clientNonce[:])
|
||||
h.Sum(sessionHash[:0])
|
||||
var hash [8]byte
|
||||
copy(hash[:], sessionHash[:8])
|
||||
passwordHash := ntlmHash(password)
|
||||
return response(hash, passwordHash)
|
||||
}
|
||||
|
||||
func (auth *ntlmAuth) NextBytes(bytes []byte) ([]byte, error) {
|
||||
if string(bytes[0:8]) != "NTLMSSP\x00" {
|
||||
return nil, errorNTLM
|
||||
}
|
||||
if binary.LittleEndian.Uint32(bytes[8:12]) != _CHALLENGE_MESSAGE {
|
||||
return nil, errorNTLM
|
||||
}
|
||||
flags := binary.LittleEndian.Uint32(bytes[20:24])
|
||||
var challenge [8]byte
|
||||
copy(challenge[:], bytes[24:32])
|
||||
|
||||
var lm, nt []byte
|
||||
if (flags & _NEGOTIATE_EXTENDED_SESSIONSECURITY) != 0 {
|
||||
nonce := clientChallenge()
|
||||
var lm_bytes [24]byte
|
||||
copy(lm_bytes[:8], nonce[:])
|
||||
lm = lm_bytes[:]
|
||||
nt_bytes := ntlmSessionResponse(nonce, challenge, auth.Password)
|
||||
nt = nt_bytes[:]
|
||||
} else {
|
||||
lm_bytes := lmResponse(challenge, auth.Password)
|
||||
lm = lm_bytes[:]
|
||||
nt_bytes := ntResponse(challenge, auth.Password)
|
||||
nt = nt_bytes[:]
|
||||
}
|
||||
lm_len := len(lm)
|
||||
nt_len := len(nt)
|
||||
|
||||
domain16 := utf16le(auth.Domain)
|
||||
domain_len := len(domain16)
|
||||
user16 := utf16le(auth.UserName)
|
||||
user_len := len(user16)
|
||||
workstation16 := utf16le(auth.Workstation)
|
||||
workstation_len := len(workstation16)
|
||||
|
||||
msg := make([]byte, 88+lm_len+nt_len+domain_len+user_len+workstation_len)
|
||||
copy(msg, []byte("NTLMSSP\x00"))
|
||||
binary.LittleEndian.PutUint32(msg[8:], _AUTHENTICATE_MESSAGE)
|
||||
// Lm Challenge Response Fields
|
||||
binary.LittleEndian.PutUint16(msg[12:], uint16(lm_len))
|
||||
binary.LittleEndian.PutUint16(msg[14:], uint16(lm_len))
|
||||
binary.LittleEndian.PutUint32(msg[16:], 88)
|
||||
// Nt Challenge Response Fields
|
||||
binary.LittleEndian.PutUint16(msg[20:], uint16(nt_len))
|
||||
binary.LittleEndian.PutUint16(msg[22:], uint16(nt_len))
|
||||
binary.LittleEndian.PutUint32(msg[24:], uint32(88+lm_len))
|
||||
// Domain Name Fields
|
||||
binary.LittleEndian.PutUint16(msg[28:], uint16(domain_len))
|
||||
binary.LittleEndian.PutUint16(msg[30:], uint16(domain_len))
|
||||
binary.LittleEndian.PutUint32(msg[32:], uint32(88+lm_len+nt_len))
|
||||
// User Name Fields
|
||||
binary.LittleEndian.PutUint16(msg[36:], uint16(user_len))
|
||||
binary.LittleEndian.PutUint16(msg[38:], uint16(user_len))
|
||||
binary.LittleEndian.PutUint32(msg[40:], uint32(88+lm_len+nt_len+domain_len))
|
||||
// Workstation Fields
|
||||
binary.LittleEndian.PutUint16(msg[44:], uint16(workstation_len))
|
||||
binary.LittleEndian.PutUint16(msg[46:], uint16(workstation_len))
|
||||
binary.LittleEndian.PutUint32(msg[48:], uint32(88+lm_len+nt_len+domain_len+user_len))
|
||||
// Encrypted Random Session Key Fields
|
||||
binary.LittleEndian.PutUint16(msg[52:], 0)
|
||||
binary.LittleEndian.PutUint16(msg[54:], 0)
|
||||
binary.LittleEndian.PutUint32(msg[56:], uint32(88+lm_len+nt_len+domain_len+user_len+workstation_len))
|
||||
// Negotiate Flags
|
||||
binary.LittleEndian.PutUint32(msg[60:], flags)
|
||||
// Version
|
||||
binary.LittleEndian.PutUint32(msg[64:], 0)
|
||||
binary.LittleEndian.PutUint32(msg[68:], 0)
|
||||
// MIC
|
||||
binary.LittleEndian.PutUint32(msg[72:], 0)
|
||||
binary.LittleEndian.PutUint32(msg[76:], 0)
|
||||
binary.LittleEndian.PutUint32(msg[88:], 0)
|
||||
binary.LittleEndian.PutUint32(msg[84:], 0)
|
||||
// Payload
|
||||
copy(msg[88:], lm)
|
||||
copy(msg[88+lm_len:], nt)
|
||||
copy(msg[88+lm_len+nt_len:], domain16)
|
||||
copy(msg[88+lm_len+nt_len+domain_len:], user16)
|
||||
copy(msg[88+lm_len+nt_len+domain_len+user_len:], workstation16)
|
||||
return msg, nil
|
||||
}
|
||||
|
||||
func (auth *ntlmAuth) Free() {
|
||||
}
|
|
@ -0,0 +1,257 @@
|
|||
package mssql
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type parser struct {
|
||||
r *bytes.Reader
|
||||
w bytes.Buffer
|
||||
paramCount int
|
||||
paramMax int
|
||||
|
||||
// using map as a set
|
||||
namedParams map[string]bool
|
||||
}
|
||||
|
||||
func (p *parser) next() (rune, bool) {
|
||||
ch, _, err := p.r.ReadRune()
|
||||
if err != nil {
|
||||
if err != io.EOF {
|
||||
panic(err)
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
return ch, true
|
||||
}
|
||||
|
||||
func (p *parser) unread() {
|
||||
err := p.r.UnreadRune()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (p *parser) write(ch rune) {
|
||||
p.w.WriteRune(ch)
|
||||
}
|
||||
|
||||
type stateFunc func(*parser) stateFunc
|
||||
|
||||
func parseParams(query string) (string, int) {
|
||||
p := &parser{
|
||||
r: bytes.NewReader([]byte(query)),
|
||||
namedParams: map[string]bool{},
|
||||
}
|
||||
state := parseNormal
|
||||
for state != nil {
|
||||
state = state(p)
|
||||
}
|
||||
return p.w.String(), p.paramMax + len(p.namedParams)
|
||||
}
|
||||
|
||||
func parseNormal(p *parser) stateFunc {
|
||||
for {
|
||||
ch, ok := p.next()
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
if ch == '?' {
|
||||
return parseOrdinalParameter
|
||||
} else if ch == '$' || ch == ':' {
|
||||
ch2, ok := p.next()
|
||||
if !ok {
|
||||
p.write(ch)
|
||||
return nil
|
||||
}
|
||||
p.unread()
|
||||
if ch2 >= '0' && ch2 <= '9' {
|
||||
return parseOrdinalParameter
|
||||
} else if 'a' <= ch2 && ch2 <= 'z' || 'A' <= ch2 && ch2 <= 'Z' {
|
||||
return parseNamedParameter
|
||||
}
|
||||
}
|
||||
p.write(ch)
|
||||
switch ch {
|
||||
case '\'':
|
||||
return parseQuote
|
||||
case '"':
|
||||
return parseDoubleQuote
|
||||
case '[':
|
||||
return parseBracket
|
||||
case '-':
|
||||
return parseLineComment
|
||||
case '/':
|
||||
return parseComment
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func parseOrdinalParameter(p *parser) stateFunc {
|
||||
var paramN int
|
||||
var ok bool
|
||||
for {
|
||||
var ch rune
|
||||
ch, ok = p.next()
|
||||
if ok && ch >= '0' && ch <= '9' {
|
||||
paramN = paramN*10 + int(ch-'0')
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
if ok {
|
||||
p.unread()
|
||||
}
|
||||
if paramN == 0 {
|
||||
p.paramCount++
|
||||
paramN = p.paramCount
|
||||
}
|
||||
if paramN > p.paramMax {
|
||||
p.paramMax = paramN
|
||||
}
|
||||
p.w.WriteString("@p")
|
||||
p.w.WriteString(strconv.Itoa(paramN))
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return parseNormal
|
||||
}
|
||||
|
||||
func parseNamedParameter(p *parser) stateFunc {
|
||||
var paramName string
|
||||
var ok bool
|
||||
for {
|
||||
var ch rune
|
||||
ch, ok = p.next()
|
||||
if ok && (ch >= '0' && ch <= '9' || 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z') {
|
||||
paramName = paramName + string(ch)
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
if ok {
|
||||
p.unread()
|
||||
}
|
||||
p.namedParams[paramName] = true
|
||||
p.w.WriteString("@")
|
||||
p.w.WriteString(paramName)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return parseNormal
|
||||
}
|
||||
|
||||
func parseQuote(p *parser) stateFunc {
|
||||
for {
|
||||
ch, ok := p.next()
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
p.write(ch)
|
||||
if ch == '\'' {
|
||||
return parseNormal
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func parseDoubleQuote(p *parser) stateFunc {
|
||||
for {
|
||||
ch, ok := p.next()
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
p.write(ch)
|
||||
if ch == '"' {
|
||||
return parseNormal
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func parseBracket(p *parser) stateFunc {
|
||||
for {
|
||||
ch, ok := p.next()
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
p.write(ch)
|
||||
if ch == ']' {
|
||||
ch, ok = p.next()
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
if ch != ']' {
|
||||
p.unread()
|
||||
return parseNormal
|
||||
}
|
||||
p.write(ch)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func parseLineComment(p *parser) stateFunc {
|
||||
ch, ok := p.next()
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
if ch != '-' {
|
||||
p.unread()
|
||||
return parseNormal
|
||||
}
|
||||
p.write(ch)
|
||||
for {
|
||||
ch, ok = p.next()
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
p.write(ch)
|
||||
if ch == '\n' {
|
||||
return parseNormal
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func parseComment(p *parser) stateFunc {
|
||||
var nested int
|
||||
ch, ok := p.next()
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
if ch != '*' {
|
||||
p.unread()
|
||||
return parseNormal
|
||||
}
|
||||
p.write(ch)
|
||||
for {
|
||||
ch, ok = p.next()
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
p.write(ch)
|
||||
for ch == '*' {
|
||||
ch, ok = p.next()
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
p.write(ch)
|
||||
if ch == '/' {
|
||||
if nested == 0 {
|
||||
return parseNormal
|
||||
} else {
|
||||
nested--
|
||||
}
|
||||
}
|
||||
}
|
||||
for ch == '/' {
|
||||
ch, ok = p.next()
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
p.write(ch)
|
||||
if ch == '*' {
|
||||
nested++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,89 @@
|
|||
package mssql
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
)
|
||||
|
||||
type procId struct {
|
||||
id uint16
|
||||
name string
|
||||
}
|
||||
|
||||
// parameter flags
|
||||
const (
|
||||
fByRevValue = 1
|
||||
fDefaultValue = 2
|
||||
)
|
||||
|
||||
type param struct {
|
||||
Name string
|
||||
Flags uint8
|
||||
ti typeInfo
|
||||
buffer []byte
|
||||
}
|
||||
|
||||
const (
|
||||
fWithRecomp = 1
|
||||
fNoMetaData = 2
|
||||
fReuseMetaData = 4
|
||||
)
|
||||
|
||||
var (
|
||||
sp_Cursor = procId{1, ""}
|
||||
sp_CursorOpen = procId{2, ""}
|
||||
sp_CursorPrepare = procId{3, ""}
|
||||
sp_CursorExecute = procId{4, ""}
|
||||
sp_CursorPrepExec = procId{5, ""}
|
||||
sp_CursorUnprepare = procId{6, ""}
|
||||
sp_CursorFetch = procId{7, ""}
|
||||
sp_CursorOption = procId{8, ""}
|
||||
sp_CursorClose = procId{9, ""}
|
||||
sp_ExecuteSql = procId{10, ""}
|
||||
sp_Prepare = procId{11, ""}
|
||||
sp_PrepExec = procId{13, ""}
|
||||
sp_PrepExecRpc = procId{14, ""}
|
||||
sp_Unprepare = procId{15, ""}
|
||||
)
|
||||
|
||||
// http://msdn.microsoft.com/en-us/library/dd357576.aspx
|
||||
func sendRpc(buf *tdsBuffer, headers []headerStruct, proc procId, flags uint16, params []param, resetSession bool) (err error) {
|
||||
buf.BeginPacket(packRPCRequest, resetSession)
|
||||
writeAllHeaders(buf, headers)
|
||||
if len(proc.name) == 0 {
|
||||
var idswitch uint16 = 0xffff
|
||||
err = binary.Write(buf, binary.LittleEndian, &idswitch)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = binary.Write(buf, binary.LittleEndian, &proc.id)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
} else {
|
||||
err = writeUsVarChar(buf, proc.name)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
err = binary.Write(buf, binary.LittleEndian, &flags)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, param := range params {
|
||||
if err = writeBVarChar(buf, param.Name); err != nil {
|
||||
return
|
||||
}
|
||||
if err = binary.Write(buf, binary.LittleEndian, param.Flags); err != nil {
|
||||
return
|
||||
}
|
||||
err = writeTypeInfo(buf, ¶m.ti)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = param.ti.Writer(buf, param.ti, param.buffer)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
return buf.FinishPacket()
|
||||
}
|
|
@ -0,0 +1,266 @@
|
|||
package mssql
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
var (
|
||||
secur32_dll = syscall.NewLazyDLL("secur32.dll")
|
||||
initSecurityInterface = secur32_dll.NewProc("InitSecurityInterfaceW")
|
||||
sec_fn *SecurityFunctionTable
|
||||
)
|
||||
|
||||
func init() {
|
||||
ptr, _, _ := initSecurityInterface.Call()
|
||||
sec_fn = (*SecurityFunctionTable)(unsafe.Pointer(ptr))
|
||||
}
|
||||
|
||||
const (
|
||||
SEC_E_OK = 0
|
||||
SECPKG_CRED_OUTBOUND = 2
|
||||
SEC_WINNT_AUTH_IDENTITY_UNICODE = 2
|
||||
ISC_REQ_DELEGATE = 0x00000001
|
||||
ISC_REQ_REPLAY_DETECT = 0x00000004
|
||||
ISC_REQ_SEQUENCE_DETECT = 0x00000008
|
||||
ISC_REQ_CONFIDENTIALITY = 0x00000010
|
||||
ISC_REQ_CONNECTION = 0x00000800
|
||||
SECURITY_NETWORK_DREP = 0
|
||||
SEC_I_CONTINUE_NEEDED = 0x00090312
|
||||
SEC_I_COMPLETE_NEEDED = 0x00090313
|
||||
SEC_I_COMPLETE_AND_CONTINUE = 0x00090314
|
||||
SECBUFFER_VERSION = 0
|
||||
SECBUFFER_TOKEN = 2
|
||||
NTLMBUF_LEN = 12000
|
||||
)
|
||||
|
||||
const ISC_REQ = ISC_REQ_CONFIDENTIALITY |
|
||||
ISC_REQ_REPLAY_DETECT |
|
||||
ISC_REQ_SEQUENCE_DETECT |
|
||||
ISC_REQ_CONNECTION |
|
||||
ISC_REQ_DELEGATE
|
||||
|
||||
type SecurityFunctionTable struct {
|
||||
dwVersion uint32
|
||||
EnumerateSecurityPackages uintptr
|
||||
QueryCredentialsAttributes uintptr
|
||||
AcquireCredentialsHandle uintptr
|
||||
FreeCredentialsHandle uintptr
|
||||
Reserved2 uintptr
|
||||
InitializeSecurityContext uintptr
|
||||
AcceptSecurityContext uintptr
|
||||
CompleteAuthToken uintptr
|
||||
DeleteSecurityContext uintptr
|
||||
ApplyControlToken uintptr
|
||||
QueryContextAttributes uintptr
|
||||
ImpersonateSecurityContext uintptr
|
||||
RevertSecurityContext uintptr
|
||||
MakeSignature uintptr
|
||||
VerifySignature uintptr
|
||||
FreeContextBuffer uintptr
|
||||
QuerySecurityPackageInfo uintptr
|
||||
Reserved3 uintptr
|
||||
Reserved4 uintptr
|
||||
Reserved5 uintptr
|
||||
Reserved6 uintptr
|
||||
Reserved7 uintptr
|
||||
Reserved8 uintptr
|
||||
QuerySecurityContextToken uintptr
|
||||
EncryptMessage uintptr
|
||||
DecryptMessage uintptr
|
||||
}
|
||||
|
||||
type SEC_WINNT_AUTH_IDENTITY struct {
|
||||
User *uint16
|
||||
UserLength uint32
|
||||
Domain *uint16
|
||||
DomainLength uint32
|
||||
Password *uint16
|
||||
PasswordLength uint32
|
||||
Flags uint32
|
||||
}
|
||||
|
||||
type TimeStamp struct {
|
||||
LowPart uint32
|
||||
HighPart int32
|
||||
}
|
||||
|
||||
type SecHandle struct {
|
||||
dwLower uintptr
|
||||
dwUpper uintptr
|
||||
}
|
||||
|
||||
type SecBuffer struct {
|
||||
cbBuffer uint32
|
||||
BufferType uint32
|
||||
pvBuffer *byte
|
||||
}
|
||||
|
||||
type SecBufferDesc struct {
|
||||
ulVersion uint32
|
||||
cBuffers uint32
|
||||
pBuffers *SecBuffer
|
||||
}
|
||||
|
||||
type SSPIAuth struct {
|
||||
Domain string
|
||||
UserName string
|
||||
Password string
|
||||
Service string
|
||||
cred SecHandle
|
||||
ctxt SecHandle
|
||||
}
|
||||
|
||||
func getAuth(user, password, service, workstation string) (auth, bool) {
|
||||
if user == "" {
|
||||
return &SSPIAuth{Service: service}, true
|
||||
}
|
||||
if !strings.ContainsRune(user, '\\') {
|
||||
return nil, false
|
||||
}
|
||||
domain_user := strings.SplitN(user, "\\", 2)
|
||||
return &SSPIAuth{
|
||||
Domain: domain_user[0],
|
||||
UserName: domain_user[1],
|
||||
Password: password,
|
||||
Service: service,
|
||||
}, true
|
||||
}
|
||||
|
||||
func (auth *SSPIAuth) InitialBytes() ([]byte, error) {
|
||||
var identity *SEC_WINNT_AUTH_IDENTITY
|
||||
if auth.UserName != "" {
|
||||
identity = &SEC_WINNT_AUTH_IDENTITY{
|
||||
Flags: SEC_WINNT_AUTH_IDENTITY_UNICODE,
|
||||
Password: syscall.StringToUTF16Ptr(auth.Password),
|
||||
PasswordLength: uint32(len(auth.Password)),
|
||||
Domain: syscall.StringToUTF16Ptr(auth.Domain),
|
||||
DomainLength: uint32(len(auth.Domain)),
|
||||
User: syscall.StringToUTF16Ptr(auth.UserName),
|
||||
UserLength: uint32(len(auth.UserName)),
|
||||
}
|
||||
}
|
||||
var ts TimeStamp
|
||||
sec_ok, _, _ := syscall.Syscall9(sec_fn.AcquireCredentialsHandle,
|
||||
9,
|
||||
0,
|
||||
uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr("Negotiate"))),
|
||||
SECPKG_CRED_OUTBOUND,
|
||||
0,
|
||||
uintptr(unsafe.Pointer(identity)),
|
||||
0,
|
||||
0,
|
||||
uintptr(unsafe.Pointer(&auth.cred)),
|
||||
uintptr(unsafe.Pointer(&ts)))
|
||||
if sec_ok != SEC_E_OK {
|
||||
return nil, fmt.Errorf("AcquireCredentialsHandle failed %x", sec_ok)
|
||||
}
|
||||
|
||||
var buf SecBuffer
|
||||
var desc SecBufferDesc
|
||||
desc.ulVersion = SECBUFFER_VERSION
|
||||
desc.cBuffers = 1
|
||||
desc.pBuffers = &buf
|
||||
|
||||
outbuf := make([]byte, NTLMBUF_LEN)
|
||||
buf.cbBuffer = NTLMBUF_LEN
|
||||
buf.BufferType = SECBUFFER_TOKEN
|
||||
buf.pvBuffer = &outbuf[0]
|
||||
|
||||
var attrs uint32
|
||||
sec_ok, _, _ = syscall.Syscall12(sec_fn.InitializeSecurityContext,
|
||||
12,
|
||||
uintptr(unsafe.Pointer(&auth.cred)),
|
||||
0,
|
||||
uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(auth.Service))),
|
||||
ISC_REQ,
|
||||
0,
|
||||
SECURITY_NETWORK_DREP,
|
||||
0,
|
||||
0,
|
||||
uintptr(unsafe.Pointer(&auth.ctxt)),
|
||||
uintptr(unsafe.Pointer(&desc)),
|
||||
uintptr(unsafe.Pointer(&attrs)),
|
||||
uintptr(unsafe.Pointer(&ts)))
|
||||
if sec_ok == SEC_I_COMPLETE_AND_CONTINUE ||
|
||||
sec_ok == SEC_I_COMPLETE_NEEDED {
|
||||
syscall.Syscall6(sec_fn.CompleteAuthToken,
|
||||
2,
|
||||
uintptr(unsafe.Pointer(&auth.ctxt)),
|
||||
uintptr(unsafe.Pointer(&desc)),
|
||||
0, 0, 0, 0)
|
||||
} else if sec_ok != SEC_E_OK &&
|
||||
sec_ok != SEC_I_CONTINUE_NEEDED {
|
||||
syscall.Syscall6(sec_fn.FreeCredentialsHandle,
|
||||
1,
|
||||
uintptr(unsafe.Pointer(&auth.cred)),
|
||||
0, 0, 0, 0, 0)
|
||||
return nil, fmt.Errorf("InitialBytes InitializeSecurityContext failed %x", sec_ok)
|
||||
}
|
||||
return outbuf[:buf.cbBuffer], nil
|
||||
}
|
||||
|
||||
func (auth *SSPIAuth) NextBytes(bytes []byte) ([]byte, error) {
|
||||
var in_buf, out_buf SecBuffer
|
||||
var in_desc, out_desc SecBufferDesc
|
||||
|
||||
in_desc.ulVersion = SECBUFFER_VERSION
|
||||
in_desc.cBuffers = 1
|
||||
in_desc.pBuffers = &in_buf
|
||||
|
||||
out_desc.ulVersion = SECBUFFER_VERSION
|
||||
out_desc.cBuffers = 1
|
||||
out_desc.pBuffers = &out_buf
|
||||
|
||||
in_buf.BufferType = SECBUFFER_TOKEN
|
||||
in_buf.pvBuffer = &bytes[0]
|
||||
in_buf.cbBuffer = uint32(len(bytes))
|
||||
|
||||
outbuf := make([]byte, NTLMBUF_LEN)
|
||||
out_buf.BufferType = SECBUFFER_TOKEN
|
||||
out_buf.pvBuffer = &outbuf[0]
|
||||
out_buf.cbBuffer = NTLMBUF_LEN
|
||||
|
||||
var attrs uint32
|
||||
var ts TimeStamp
|
||||
sec_ok, _, _ := syscall.Syscall12(sec_fn.InitializeSecurityContext,
|
||||
12,
|
||||
uintptr(unsafe.Pointer(&auth.cred)),
|
||||
uintptr(unsafe.Pointer(&auth.ctxt)),
|
||||
uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(auth.Service))),
|
||||
ISC_REQ,
|
||||
0,
|
||||
SECURITY_NETWORK_DREP,
|
||||
uintptr(unsafe.Pointer(&in_desc)),
|
||||
0,
|
||||
uintptr(unsafe.Pointer(&auth.ctxt)),
|
||||
uintptr(unsafe.Pointer(&out_desc)),
|
||||
uintptr(unsafe.Pointer(&attrs)),
|
||||
uintptr(unsafe.Pointer(&ts)))
|
||||
if sec_ok == SEC_I_COMPLETE_AND_CONTINUE ||
|
||||
sec_ok == SEC_I_COMPLETE_NEEDED {
|
||||
syscall.Syscall6(sec_fn.CompleteAuthToken,
|
||||
2,
|
||||
uintptr(unsafe.Pointer(&auth.ctxt)),
|
||||
uintptr(unsafe.Pointer(&out_desc)),
|
||||
0, 0, 0, 0)
|
||||
} else if sec_ok != SEC_E_OK &&
|
||||
sec_ok != SEC_I_CONTINUE_NEEDED {
|
||||
return nil, fmt.Errorf("NextBytes InitializeSecurityContext failed %x", sec_ok)
|
||||
}
|
||||
|
||||
return outbuf[:out_buf.cbBuffer], nil
|
||||
}
|
||||
|
||||
func (auth *SSPIAuth) Free() {
|
||||
syscall.Syscall6(sec_fn.DeleteSecurityContext,
|
||||
1,
|
||||
uintptr(unsafe.Pointer(&auth.ctxt)),
|
||||
0, 0, 0, 0, 0)
|
||||
syscall.Syscall6(sec_fn.FreeCredentialsHandle,
|
||||
1,
|
||||
uintptr(unsafe.Pointer(&auth.cred)),
|
||||
0, 0, 0, 0, 0)
|
||||
}
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,804 @@
|
|||
package mssql
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
//go:generate stringer -type token
|
||||
|
||||
type token byte
|
||||
|
||||
// token ids
|
||||
const (
|
||||
tokenReturnStatus token = 121 // 0x79
|
||||
tokenColMetadata token = 129 // 0x81
|
||||
tokenOrder token = 169 // 0xA9
|
||||
tokenError token = 170 // 0xAA
|
||||
tokenInfo token = 171 // 0xAB
|
||||
tokenReturnValue token = 0xAC
|
||||
tokenLoginAck token = 173 // 0xad
|
||||
tokenRow token = 209 // 0xd1
|
||||
tokenNbcRow token = 210 // 0xd2
|
||||
tokenEnvChange token = 227 // 0xE3
|
||||
tokenSSPI token = 237 // 0xED
|
||||
tokenDone token = 253 // 0xFD
|
||||
tokenDoneProc token = 254
|
||||
tokenDoneInProc token = 255
|
||||
)
|
||||
|
||||
// done flags
|
||||
// https://msdn.microsoft.com/en-us/library/dd340421.aspx
|
||||
const (
|
||||
doneFinal = 0
|
||||
doneMore = 1
|
||||
doneError = 2
|
||||
doneInxact = 4
|
||||
doneCount = 0x10
|
||||
doneAttn = 0x20
|
||||
doneSrvError = 0x100
|
||||
)
|
||||
|
||||
// ENVCHANGE types
|
||||
// http://msdn.microsoft.com/en-us/library/dd303449.aspx
|
||||
const (
|
||||
envTypDatabase = 1
|
||||
envTypLanguage = 2
|
||||
envTypCharset = 3
|
||||
envTypPacketSize = 4
|
||||
envSortId = 5
|
||||
envSortFlags = 6
|
||||
envSqlCollation = 7
|
||||
envTypBeginTran = 8
|
||||
envTypCommitTran = 9
|
||||
envTypRollbackTran = 10
|
||||
envEnlistDTC = 11
|
||||
envDefectTran = 12
|
||||
envDatabaseMirrorPartner = 13
|
||||
envPromoteTran = 15
|
||||
envTranMgrAddr = 16
|
||||
envTranEnded = 17
|
||||
envResetConnAck = 18
|
||||
envStartedInstanceName = 19
|
||||
envRouting = 20
|
||||
)
|
||||
|
||||
// COLMETADATA flags
|
||||
// https://msdn.microsoft.com/en-us/library/dd357363.aspx
|
||||
const (
|
||||
colFlagNullable = 1
|
||||
// TODO implement more flags
|
||||
)
|
||||
|
||||
// interface for all tokens
|
||||
type tokenStruct interface{}
|
||||
|
||||
type orderStruct struct {
|
||||
ColIds []uint16
|
||||
}
|
||||
|
||||
type doneStruct struct {
|
||||
Status uint16
|
||||
CurCmd uint16
|
||||
RowCount uint64
|
||||
errors []Error
|
||||
}
|
||||
|
||||
func (d doneStruct) isError() bool {
|
||||
return d.Status&doneError != 0 || len(d.errors) > 0
|
||||
}
|
||||
|
||||
func (d doneStruct) getError() Error {
|
||||
if len(d.errors) > 0 {
|
||||
return d.errors[len(d.errors)-1]
|
||||
} else {
|
||||
return Error{Message: "Request failed but didn't provide reason"}
|
||||
}
|
||||
}
|
||||
|
||||
type doneInProcStruct doneStruct
|
||||
|
||||
var doneFlags2str = map[uint16]string{
|
||||
doneFinal: "final",
|
||||
doneMore: "more",
|
||||
doneError: "error",
|
||||
doneInxact: "inxact",
|
||||
doneCount: "count",
|
||||
doneAttn: "attn",
|
||||
doneSrvError: "srverror",
|
||||
}
|
||||
|
||||
func doneFlags2Str(flags uint16) string {
|
||||
strs := make([]string, 0, len(doneFlags2str))
|
||||
for flag, tag := range doneFlags2str {
|
||||
if flags&flag != 0 {
|
||||
strs = append(strs, tag)
|
||||
}
|
||||
}
|
||||
return strings.Join(strs, "|")
|
||||
}
|
||||
|
||||
// ENVCHANGE stream
|
||||
// http://msdn.microsoft.com/en-us/library/dd303449.aspx
|
||||
func processEnvChg(sess *tdsSession) {
|
||||
size := sess.buf.uint16()
|
||||
r := &io.LimitedReader{R: sess.buf, N: int64(size)}
|
||||
for {
|
||||
var err error
|
||||
var envtype uint8
|
||||
err = binary.Read(r, binary.LittleEndian, &envtype)
|
||||
if err == io.EOF {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
switch envtype {
|
||||
case envTypDatabase:
|
||||
sess.database, err = readBVarChar(r)
|
||||
if err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
_, err = readBVarChar(r)
|
||||
if err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
case envTypLanguage:
|
||||
// currently ignored
|
||||
// new value
|
||||
if _, err = readBVarChar(r); err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
// old value
|
||||
if _, err = readBVarChar(r); err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
case envTypCharset:
|
||||
// currently ignored
|
||||
// new value
|
||||
if _, err = readBVarChar(r); err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
// old value
|
||||
if _, err = readBVarChar(r); err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
case envTypPacketSize:
|
||||
packetsize, err := readBVarChar(r)
|
||||
if err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
_, err = readBVarChar(r)
|
||||
if err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
packetsizei, err := strconv.Atoi(packetsize)
|
||||
if err != nil {
|
||||
badStreamPanicf("Invalid Packet size value returned from server (%s): %s", packetsize, err.Error())
|
||||
}
|
||||
sess.buf.ResizeBuffer(packetsizei)
|
||||
case envSortId:
|
||||
// currently ignored
|
||||
// new value
|
||||
if _, err = readBVarChar(r); err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
// old value, should be 0
|
||||
if _, err = readBVarChar(r); err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
case envSortFlags:
|
||||
// currently ignored
|
||||
// new value
|
||||
if _, err = readBVarChar(r); err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
// old value, should be 0
|
||||
if _, err = readBVarChar(r); err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
case envSqlCollation:
|
||||
// currently ignored
|
||||
var collationSize uint8
|
||||
err = binary.Read(r, binary.LittleEndian, &collationSize)
|
||||
if err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
|
||||
// SQL Collation data should contain 5 bytes in length
|
||||
if collationSize != 5 {
|
||||
badStreamPanicf("Invalid SQL Collation size value returned from server: %d", collationSize)
|
||||
}
|
||||
|
||||
// 4 bytes, contains: LCID ColFlags Version
|
||||
var info uint32
|
||||
err = binary.Read(r, binary.LittleEndian, &info)
|
||||
if err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
|
||||
// 1 byte, contains: sortID
|
||||
var sortID uint8
|
||||
err = binary.Read(r, binary.LittleEndian, &sortID)
|
||||
if err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
|
||||
// old value, should be 0
|
||||
if _, err = readBVarChar(r); err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
case envTypBeginTran:
|
||||
tranid, err := readBVarByte(r)
|
||||
if len(tranid) != 8 {
|
||||
badStreamPanicf("invalid size of transaction identifier: %d", len(tranid))
|
||||
}
|
||||
sess.tranid = binary.LittleEndian.Uint64(tranid)
|
||||
if err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
if sess.logFlags&logTransaction != 0 {
|
||||
sess.log.Printf("BEGIN TRANSACTION %x\n", sess.tranid)
|
||||
}
|
||||
_, err = readBVarByte(r)
|
||||
if err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
case envTypCommitTran, envTypRollbackTran:
|
||||
_, err = readBVarByte(r)
|
||||
if err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
_, err = readBVarByte(r)
|
||||
if err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
if sess.logFlags&logTransaction != 0 {
|
||||
if envtype == envTypCommitTran {
|
||||
sess.log.Printf("COMMIT TRANSACTION %x\n", sess.tranid)
|
||||
} else {
|
||||
sess.log.Printf("ROLLBACK TRANSACTION %x\n", sess.tranid)
|
||||
}
|
||||
}
|
||||
sess.tranid = 0
|
||||
case envEnlistDTC:
|
||||
// currently ignored
|
||||
// new value, should be 0
|
||||
if _, err = readBVarChar(r); err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
// old value
|
||||
if _, err = readBVarChar(r); err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
case envDefectTran:
|
||||
// currently ignored
|
||||
// new value
|
||||
if _, err = readBVarChar(r); err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
// old value, should be 0
|
||||
if _, err = readBVarChar(r); err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
case envDatabaseMirrorPartner:
|
||||
sess.partner, err = readBVarChar(r)
|
||||
if err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
_, err = readBVarChar(r)
|
||||
if err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
case envPromoteTran:
|
||||
// currently ignored
|
||||
// old value, should be 0
|
||||
if _, err = readBVarChar(r); err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
// dtc token
|
||||
// spec says it should be L_VARBYTE, so this code might be wrong
|
||||
if _, err = readBVarChar(r); err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
case envTranMgrAddr:
|
||||
// currently ignored
|
||||
// old value, should be 0
|
||||
if _, err = readBVarChar(r); err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
// XACT_MANAGER_ADDRESS = B_VARBYTE
|
||||
if _, err = readBVarChar(r); err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
case envTranEnded:
|
||||
// currently ignored
|
||||
// old value, B_VARBYTE
|
||||
if _, err = readBVarChar(r); err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
// should be 0
|
||||
if _, err = readBVarChar(r); err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
case envResetConnAck:
|
||||
// currently ignored
|
||||
// old value, should be 0
|
||||
if _, err = readBVarChar(r); err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
// should be 0
|
||||
if _, err = readBVarChar(r); err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
case envStartedInstanceName:
|
||||
// currently ignored
|
||||
// old value, should be 0
|
||||
if _, err = readBVarChar(r); err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
// instance name
|
||||
if _, err = readBVarChar(r); err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
case envRouting:
|
||||
// RoutingData message is:
|
||||
// ValueLength USHORT
|
||||
// Protocol (TCP = 0) BYTE
|
||||
// ProtocolProperty (new port) USHORT
|
||||
// AlternateServer US_VARCHAR
|
||||
_, err := readUshort(r)
|
||||
if err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
protocol, err := readByte(r)
|
||||
if err != nil || protocol != 0 {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
newPort, err := readUshort(r)
|
||||
if err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
newServer, err := readUsVarChar(r)
|
||||
if err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
// consume the OLDVALUE = %x00 %x00
|
||||
_, err = readUshort(r)
|
||||
if err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
sess.routedServer = newServer
|
||||
sess.routedPort = newPort
|
||||
default:
|
||||
// ignore rest of records because we don't know how to skip those
|
||||
sess.log.Printf("WARN: Unknown ENVCHANGE record detected with type id = %d\n", envtype)
|
||||
break
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
// http://msdn.microsoft.com/en-us/library/dd358180.aspx
|
||||
func parseReturnStatus(r *tdsBuffer) ReturnStatus {
|
||||
return ReturnStatus(r.int32())
|
||||
}
|
||||
|
||||
func parseOrder(r *tdsBuffer) (res orderStruct) {
|
||||
len := int(r.uint16())
|
||||
res.ColIds = make([]uint16, len/2)
|
||||
for i := 0; i < len/2; i++ {
|
||||
res.ColIds[i] = r.uint16()
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// https://msdn.microsoft.com/en-us/library/dd340421.aspx
|
||||
func parseDone(r *tdsBuffer) (res doneStruct) {
|
||||
res.Status = r.uint16()
|
||||
res.CurCmd = r.uint16()
|
||||
res.RowCount = r.uint64()
|
||||
return res
|
||||
}
|
||||
|
||||
// https://msdn.microsoft.com/en-us/library/dd340553.aspx
|
||||
func parseDoneInProc(r *tdsBuffer) (res doneInProcStruct) {
|
||||
res.Status = r.uint16()
|
||||
res.CurCmd = r.uint16()
|
||||
res.RowCount = r.uint64()
|
||||
return res
|
||||
}
|
||||
|
||||
type sspiMsg []byte
|
||||
|
||||
func parseSSPIMsg(r *tdsBuffer) sspiMsg {
|
||||
size := r.uint16()
|
||||
buf := make([]byte, size)
|
||||
r.ReadFull(buf)
|
||||
return sspiMsg(buf)
|
||||
}
|
||||
|
||||
type loginAckStruct struct {
|
||||
Interface uint8
|
||||
TDSVersion uint32
|
||||
ProgName string
|
||||
ProgVer uint32
|
||||
}
|
||||
|
||||
func parseLoginAck(r *tdsBuffer) loginAckStruct {
|
||||
size := r.uint16()
|
||||
buf := make([]byte, size)
|
||||
r.ReadFull(buf)
|
||||
var res loginAckStruct
|
||||
res.Interface = buf[0]
|
||||
res.TDSVersion = binary.BigEndian.Uint32(buf[1:])
|
||||
prognamelen := buf[1+4]
|
||||
var err error
|
||||
if res.ProgName, err = ucs22str(buf[1+4+1 : 1+4+1+prognamelen*2]); err != nil {
|
||||
badStreamPanic(err)
|
||||
}
|
||||
res.ProgVer = binary.BigEndian.Uint32(buf[size-4:])
|
||||
return res
|
||||
}
|
||||
|
||||
// http://msdn.microsoft.com/en-us/library/dd357363.aspx
|
||||
func parseColMetadata72(r *tdsBuffer) (columns []columnStruct) {
|
||||
count := r.uint16()
|
||||
if count == 0xffff {
|
||||
// no metadata is sent
|
||||
return nil
|
||||
}
|
||||
columns = make([]columnStruct, count)
|
||||
for i := range columns {
|
||||
column := &columns[i]
|
||||
column.UserType = r.uint32()
|
||||
column.Flags = r.uint16()
|
||||
|
||||
// parsing TYPE_INFO structure
|
||||
column.ti = readTypeInfo(r)
|
||||
column.ColName = r.BVarChar()
|
||||
}
|
||||
return columns
|
||||
}
|
||||
|
||||
// http://msdn.microsoft.com/en-us/library/dd357254.aspx
|
||||
func parseRow(r *tdsBuffer, columns []columnStruct, row []interface{}) {
|
||||
for i, column := range columns {
|
||||
row[i] = column.ti.Reader(&column.ti, r)
|
||||
}
|
||||
}
|
||||
|
||||
// http://msdn.microsoft.com/en-us/library/dd304783.aspx
|
||||
func parseNbcRow(r *tdsBuffer, columns []columnStruct, row []interface{}) {
|
||||
bitlen := (len(columns) + 7) / 8
|
||||
pres := make([]byte, bitlen)
|
||||
r.ReadFull(pres)
|
||||
for i, col := range columns {
|
||||
if pres[i/8]&(1<<(uint(i)%8)) != 0 {
|
||||
row[i] = nil
|
||||
continue
|
||||
}
|
||||
row[i] = col.ti.Reader(&col.ti, r)
|
||||
}
|
||||
}
|
||||
|
||||
// http://msdn.microsoft.com/en-us/library/dd304156.aspx
|
||||
func parseError72(r *tdsBuffer) (res Error) {
|
||||
length := r.uint16()
|
||||
_ = length // ignore length
|
||||
res.Number = r.int32()
|
||||
res.State = r.byte()
|
||||
res.Class = r.byte()
|
||||
res.Message = r.UsVarChar()
|
||||
res.ServerName = r.BVarChar()
|
||||
res.ProcName = r.BVarChar()
|
||||
res.LineNo = r.int32()
|
||||
return
|
||||
}
|
||||
|
||||
// http://msdn.microsoft.com/en-us/library/dd304156.aspx
|
||||
func parseInfo(r *tdsBuffer) (res Error) {
|
||||
length := r.uint16()
|
||||
_ = length // ignore length
|
||||
res.Number = r.int32()
|
||||
res.State = r.byte()
|
||||
res.Class = r.byte()
|
||||
res.Message = r.UsVarChar()
|
||||
res.ServerName = r.BVarChar()
|
||||
res.ProcName = r.BVarChar()
|
||||
res.LineNo = r.int32()
|
||||
return
|
||||
}
|
||||
|
||||
// https://msdn.microsoft.com/en-us/library/dd303881.aspx
|
||||
func parseReturnValue(r *tdsBuffer) (nv namedValue) {
|
||||
/*
|
||||
ParamOrdinal
|
||||
ParamName
|
||||
Status
|
||||
UserType
|
||||
Flags
|
||||
TypeInfo
|
||||
CryptoMetadata
|
||||
Value
|
||||
*/
|
||||
r.uint16()
|
||||
nv.Name = r.BVarChar()
|
||||
r.byte()
|
||||
r.uint32() // UserType (uint16 prior to 7.2)
|
||||
r.uint16()
|
||||
ti := readTypeInfo(r)
|
||||
nv.Value = ti.Reader(&ti, r)
|
||||
return
|
||||
}
|
||||
|
||||
func processSingleResponse(sess *tdsSession, ch chan tokenStruct, outs map[string]interface{}) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
if sess.logFlags&logErrors != 0 {
|
||||
sess.log.Printf("ERROR: Intercepted panic %v", err)
|
||||
}
|
||||
ch <- err
|
||||
}
|
||||
close(ch)
|
||||
}()
|
||||
|
||||
packet_type, err := sess.buf.BeginRead()
|
||||
if err != nil {
|
||||
if sess.logFlags&logErrors != 0 {
|
||||
sess.log.Printf("ERROR: BeginRead failed %v", err)
|
||||
}
|
||||
ch <- err
|
||||
return
|
||||
}
|
||||
if packet_type != packReply {
|
||||
badStreamPanic(fmt.Errorf("unexpected packet type in reply: got %v, expected %v", packet_type, packReply))
|
||||
}
|
||||
var columns []columnStruct
|
||||
errs := make([]Error, 0, 5)
|
||||
for {
|
||||
token := token(sess.buf.byte())
|
||||
if sess.logFlags&logDebug != 0 {
|
||||
sess.log.Printf("got token %v", token)
|
||||
}
|
||||
switch token {
|
||||
case tokenSSPI:
|
||||
ch <- parseSSPIMsg(sess.buf)
|
||||
return
|
||||
case tokenReturnStatus:
|
||||
returnStatus := parseReturnStatus(sess.buf)
|
||||
ch <- returnStatus
|
||||
case tokenLoginAck:
|
||||
loginAck := parseLoginAck(sess.buf)
|
||||
ch <- loginAck
|
||||
case tokenOrder:
|
||||
order := parseOrder(sess.buf)
|
||||
ch <- order
|
||||
case tokenDoneInProc:
|
||||
done := parseDoneInProc(sess.buf)
|
||||
if sess.logFlags&logRows != 0 && done.Status&doneCount != 0 {
|
||||
sess.log.Printf("(%d row(s) affected)\n", done.RowCount)
|
||||
}
|
||||
ch <- done
|
||||
case tokenDone, tokenDoneProc:
|
||||
done := parseDone(sess.buf)
|
||||
done.errors = errs
|
||||
if sess.logFlags&logDebug != 0 {
|
||||
sess.log.Printf("got DONE or DONEPROC status=%d", done.Status)
|
||||
}
|
||||
if done.Status&doneSrvError != 0 {
|
||||
ch <- errors.New("SQL Server had internal error")
|
||||
return
|
||||
}
|
||||
if sess.logFlags&logRows != 0 && done.Status&doneCount != 0 {
|
||||
sess.log.Printf("(%d row(s) affected)\n", done.RowCount)
|
||||
}
|
||||
ch <- done
|
||||
if done.Status&doneMore == 0 {
|
||||
return
|
||||
}
|
||||
case tokenColMetadata:
|
||||
columns = parseColMetadata72(sess.buf)
|
||||
ch <- columns
|
||||
case tokenRow:
|
||||
row := make([]interface{}, len(columns))
|
||||
parseRow(sess.buf, columns, row)
|
||||
ch <- row
|
||||
case tokenNbcRow:
|
||||
row := make([]interface{}, len(columns))
|
||||
parseNbcRow(sess.buf, columns, row)
|
||||
ch <- row
|
||||
case tokenEnvChange:
|
||||
processEnvChg(sess)
|
||||
case tokenError:
|
||||
err := parseError72(sess.buf)
|
||||
if sess.logFlags&logDebug != 0 {
|
||||
sess.log.Printf("got ERROR %d %s", err.Number, err.Message)
|
||||
}
|
||||
errs = append(errs, err)
|
||||
if sess.logFlags&logErrors != 0 {
|
||||
sess.log.Println(err.Message)
|
||||
}
|
||||
case tokenInfo:
|
||||
info := parseInfo(sess.buf)
|
||||
if sess.logFlags&logDebug != 0 {
|
||||
sess.log.Printf("got INFO %d %s", info.Number, info.Message)
|
||||
}
|
||||
if sess.logFlags&logMessages != 0 {
|
||||
sess.log.Println(info.Message)
|
||||
}
|
||||
case tokenReturnValue:
|
||||
nv := parseReturnValue(sess.buf)
|
||||
if len(nv.Name) > 0 {
|
||||
name := nv.Name[1:] // Remove the leading "@".
|
||||
if ov, has := outs[name]; has {
|
||||
err = scanIntoOut(name, nv.Value, ov)
|
||||
if err != nil {
|
||||
fmt.Println("scan error", err)
|
||||
ch <- err
|
||||
}
|
||||
}
|
||||
}
|
||||
default:
|
||||
badStreamPanic(fmt.Errorf("unknown token type returned: %v", token))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type parseRespIter byte
|
||||
|
||||
const (
|
||||
parseRespIterContinue parseRespIter = iota // Continue parsing current token.
|
||||
parseRespIterNext // Fetch the next token.
|
||||
parseRespIterDone // Done with parsing the response.
|
||||
)
|
||||
|
||||
type parseRespState byte
|
||||
|
||||
const (
|
||||
parseRespStateNormal parseRespState = iota // Normal response state.
|
||||
parseRespStateCancel // Query is canceled, wait for server to confirm.
|
||||
parseRespStateClosing // Waiting for tokens to come through.
|
||||
)
|
||||
|
||||
type parseResp struct {
|
||||
sess *tdsSession
|
||||
ctxDone <-chan struct{}
|
||||
state parseRespState
|
||||
cancelError error
|
||||
}
|
||||
|
||||
func (ts *parseResp) sendAttention(ch chan tokenStruct) parseRespIter {
|
||||
if err := sendAttention(ts.sess.buf); err != nil {
|
||||
ts.dlogf("failed to send attention signal %v", err)
|
||||
ch <- err
|
||||
return parseRespIterDone
|
||||
}
|
||||
ts.state = parseRespStateCancel
|
||||
return parseRespIterContinue
|
||||
}
|
||||
|
||||
func (ts *parseResp) dlog(msg string) {
|
||||
if ts.sess.logFlags&logDebug != 0 {
|
||||
ts.sess.log.Println(msg)
|
||||
}
|
||||
}
|
||||
func (ts *parseResp) dlogf(f string, v ...interface{}) {
|
||||
if ts.sess.logFlags&logDebug != 0 {
|
||||
ts.sess.log.Printf(f, v...)
|
||||
}
|
||||
}
|
||||
|
||||
func (ts *parseResp) iter(ctx context.Context, ch chan tokenStruct, tokChan chan tokenStruct) parseRespIter {
|
||||
switch ts.state {
|
||||
default:
|
||||
panic("unknown state")
|
||||
case parseRespStateNormal:
|
||||
select {
|
||||
case tok, ok := <-tokChan:
|
||||
if !ok {
|
||||
ts.dlog("response finished")
|
||||
return parseRespIterDone
|
||||
}
|
||||
if err, ok := tok.(net.Error); ok && err.Timeout() {
|
||||
ts.cancelError = err
|
||||
ts.dlog("got timeout error, sending attention signal to server")
|
||||
return ts.sendAttention(ch)
|
||||
}
|
||||
// Pass the token along.
|
||||
ch <- tok
|
||||
return parseRespIterContinue
|
||||
|
||||
case <-ts.ctxDone:
|
||||
ts.ctxDone = nil
|
||||
ts.dlog("got cancel message, sending attention signal to server")
|
||||
return ts.sendAttention(ch)
|
||||
}
|
||||
case parseRespStateCancel: // Read all responses until a DONE or error is received.Auth
|
||||
select {
|
||||
case tok, ok := <-tokChan:
|
||||
if !ok {
|
||||
ts.dlog("response finished but waiting for attention ack")
|
||||
return parseRespIterNext
|
||||
}
|
||||
switch tok := tok.(type) {
|
||||
default:
|
||||
// Ignore all other tokens while waiting.
|
||||
// The TDS spec says other tokens may arrive after an attention
|
||||
// signal is sent. Ignore these tokens and continue looking for
|
||||
// a DONE with attention confirm mark.
|
||||
case doneStruct:
|
||||
if tok.Status&doneAttn != 0 {
|
||||
ts.dlog("got cancellation confirmation from server")
|
||||
if ts.cancelError != nil {
|
||||
ch <- ts.cancelError
|
||||
ts.cancelError = nil
|
||||
} else {
|
||||
ch <- ctx.Err()
|
||||
}
|
||||
return parseRespIterDone
|
||||
}
|
||||
|
||||
// If an error happens during cancel, pass it along and just stop.
|
||||
// We are uncertain to receive more tokens.
|
||||
case error:
|
||||
ch <- tok
|
||||
ts.state = parseRespStateClosing
|
||||
}
|
||||
return parseRespIterContinue
|
||||
case <-ts.ctxDone:
|
||||
ts.ctxDone = nil
|
||||
ts.state = parseRespStateClosing
|
||||
return parseRespIterContinue
|
||||
}
|
||||
case parseRespStateClosing: // Wait for current token chan to close.
|
||||
if _, ok := <-tokChan; !ok {
|
||||
ts.dlog("response finished")
|
||||
return parseRespIterDone
|
||||
}
|
||||
return parseRespIterContinue
|
||||
}
|
||||
}
|
||||
|
||||
func processResponse(ctx context.Context, sess *tdsSession, ch chan tokenStruct, outs map[string]interface{}) {
|
||||
ts := &parseResp{
|
||||
sess: sess,
|
||||
ctxDone: ctx.Done(),
|
||||
}
|
||||
defer func() {
|
||||
// Ensure any remaining error is piped through
|
||||
// or the query may look like it executed when it actually failed.
|
||||
if ts.cancelError != nil {
|
||||
ch <- ts.cancelError
|
||||
ts.cancelError = nil
|
||||
}
|
||||
close(ch)
|
||||
}()
|
||||
|
||||
// Loop over multiple responses.
|
||||
for {
|
||||
ts.dlog("initiating response reading")
|
||||
|
||||
tokChan := make(chan tokenStruct)
|
||||
go processSingleResponse(sess, tokChan, outs)
|
||||
|
||||
// Loop over multiple tokens in response.
|
||||
tokensLoop:
|
||||
for {
|
||||
switch ts.iter(ctx, ch, tokChan) {
|
||||
case parseRespIterContinue:
|
||||
// Nothing, continue to next token.
|
||||
case parseRespIterNext:
|
||||
break tokensLoop
|
||||
case parseRespIterDone:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,53 @@
|
|||
// Code generated by "stringer -type token"; DO NOT EDIT
|
||||
|
||||
package mssql
|
||||
|
||||
import "fmt"
|
||||
|
||||
const (
|
||||
_token_name_0 = "tokenReturnStatus"
|
||||
_token_name_1 = "tokenColMetadata"
|
||||
_token_name_2 = "tokenOrdertokenErrortokenInfo"
|
||||
_token_name_3 = "tokenLoginAck"
|
||||
_token_name_4 = "tokenRowtokenNbcRow"
|
||||
_token_name_5 = "tokenEnvChange"
|
||||
_token_name_6 = "tokenSSPI"
|
||||
_token_name_7 = "tokenDonetokenDoneProctokenDoneInProc"
|
||||
)
|
||||
|
||||
var (
|
||||
_token_index_0 = [...]uint8{0, 17}
|
||||
_token_index_1 = [...]uint8{0, 16}
|
||||
_token_index_2 = [...]uint8{0, 10, 20, 29}
|
||||
_token_index_3 = [...]uint8{0, 13}
|
||||
_token_index_4 = [...]uint8{0, 8, 19}
|
||||
_token_index_5 = [...]uint8{0, 14}
|
||||
_token_index_6 = [...]uint8{0, 9}
|
||||
_token_index_7 = [...]uint8{0, 9, 22, 37}
|
||||
)
|
||||
|
||||
func (i token) String() string {
|
||||
switch {
|
||||
case i == 121:
|
||||
return _token_name_0
|
||||
case i == 129:
|
||||
return _token_name_1
|
||||
case 169 <= i && i <= 171:
|
||||
i -= 169
|
||||
return _token_name_2[_token_index_2[i]:_token_index_2[i+1]]
|
||||
case i == 173:
|
||||
return _token_name_3
|
||||
case 209 <= i && i <= 210:
|
||||
i -= 209
|
||||
return _token_name_4[_token_index_4[i]:_token_index_4[i+1]]
|
||||
case i == 227:
|
||||
return _token_name_5
|
||||
case i == 237:
|
||||
return _token_name_6
|
||||
case 253 <= i && i <= 255:
|
||||
i -= 253
|
||||
return _token_name_7[_token_index_7[i]:_token_index_7[i+1]]
|
||||
default:
|
||||
return fmt.Sprintf("token(%d)", i)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,110 @@
|
|||
package mssql
|
||||
|
||||
// Transaction Manager requests
|
||||
// http://msdn.microsoft.com/en-us/library/dd339887.aspx
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
)
|
||||
|
||||
const (
|
||||
tmGetDtcAddr = 0
|
||||
tmPropagateXact = 1
|
||||
tmBeginXact = 5
|
||||
tmPromoteXact = 6
|
||||
tmCommitXact = 7
|
||||
tmRollbackXact = 8
|
||||
tmSaveXact = 9
|
||||
)
|
||||
|
||||
type isoLevel uint8
|
||||
|
||||
const (
|
||||
isolationUseCurrent isoLevel = 0
|
||||
isolationReadUncommited = 1
|
||||
isolationReadCommited = 2
|
||||
isolationRepeatableRead = 3
|
||||
isolationSerializable = 4
|
||||
isolationSnapshot = 5
|
||||
)
|
||||
|
||||
func sendBeginXact(buf *tdsBuffer, headers []headerStruct, isolation isoLevel, name string, resetSession bool) (err error) {
|
||||
buf.BeginPacket(packTransMgrReq, resetSession)
|
||||
writeAllHeaders(buf, headers)
|
||||
var rqtype uint16 = tmBeginXact
|
||||
err = binary.Write(buf, binary.LittleEndian, &rqtype)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = binary.Write(buf, binary.LittleEndian, &isolation)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = writeBVarChar(buf, name)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return buf.FinishPacket()
|
||||
}
|
||||
|
||||
const (
|
||||
fBeginXact = 1
|
||||
)
|
||||
|
||||
func sendCommitXact(buf *tdsBuffer, headers []headerStruct, name string, flags uint8, isolation uint8, newname string, resetSession bool) error {
|
||||
buf.BeginPacket(packTransMgrReq, resetSession)
|
||||
writeAllHeaders(buf, headers)
|
||||
var rqtype uint16 = tmCommitXact
|
||||
err := binary.Write(buf, binary.LittleEndian, &rqtype)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = writeBVarChar(buf, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = binary.Write(buf, binary.LittleEndian, &flags)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if flags&fBeginXact != 0 {
|
||||
err = binary.Write(buf, binary.LittleEndian, &isolation)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = writeBVarChar(buf, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return buf.FinishPacket()
|
||||
}
|
||||
|
||||
func sendRollbackXact(buf *tdsBuffer, headers []headerStruct, name string, flags uint8, isolation uint8, newname string, resetSession bool) error {
|
||||
buf.BeginPacket(packTransMgrReq, resetSession)
|
||||
writeAllHeaders(buf, headers)
|
||||
var rqtype uint16 = tmRollbackXact
|
||||
err := binary.Write(buf, binary.LittleEndian, &rqtype)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = writeBVarChar(buf, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = binary.Write(buf, binary.LittleEndian, &flags)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if flags&fBeginXact != 0 {
|
||||
err = binary.Write(buf, binary.LittleEndian, &isolation)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = writeBVarChar(buf, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return buf.FinishPacket()
|
||||
}
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,74 @@
|
|||
package mssql
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type UniqueIdentifier [16]byte
|
||||
|
||||
func (u *UniqueIdentifier) Scan(v interface{}) error {
|
||||
reverse := func(b []byte) {
|
||||
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
|
||||
b[i], b[j] = b[j], b[i]
|
||||
}
|
||||
}
|
||||
|
||||
switch vt := v.(type) {
|
||||
case []byte:
|
||||
if len(vt) != 16 {
|
||||
return errors.New("mssql: invalid UniqueIdentifier length")
|
||||
}
|
||||
|
||||
var raw UniqueIdentifier
|
||||
|
||||
copy(raw[:], vt)
|
||||
|
||||
reverse(raw[0:4])
|
||||
reverse(raw[4:6])
|
||||
reverse(raw[6:8])
|
||||
*u = raw
|
||||
|
||||
return nil
|
||||
case string:
|
||||
if len(vt) != 36 {
|
||||
return errors.New("mssql: invalid UniqueIdentifier string length")
|
||||
}
|
||||
|
||||
b := []byte(vt)
|
||||
for i, c := range b {
|
||||
switch c {
|
||||
case '-':
|
||||
b = append(b[:i], b[i+1:]...)
|
||||
}
|
||||
}
|
||||
|
||||
_, err := hex.Decode(u[:], []byte(b))
|
||||
return err
|
||||
default:
|
||||
return fmt.Errorf("mssql: cannot convert %T to UniqueIdentifier", v)
|
||||
}
|
||||
}
|
||||
|
||||
func (u UniqueIdentifier) Value() (driver.Value, error) {
|
||||
reverse := func(b []byte) {
|
||||
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
|
||||
b[i], b[j] = b[j], b[i]
|
||||
}
|
||||
}
|
||||
|
||||
raw := make([]byte, len(u))
|
||||
copy(raw, u[:])
|
||||
|
||||
reverse(raw[0:4])
|
||||
reverse(raw[4:6])
|
||||
reverse(raw[6:8])
|
||||
|
||||
return raw, nil
|
||||
}
|
||||
|
||||
func (u UniqueIdentifier) String() string {
|
||||
return fmt.Sprintf("%X-%X-%X-%X-%X", u[0:4], u[4:6], u[6:8], u[8:10], u[10:])
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2012-2018 Grigory Dryapak
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
|
@ -0,0 +1,188 @@
|
|||
# Imaging
|
||||
|
||||
[![GoDoc](https://godoc.org/github.com/disintegration/imaging?status.svg)](https://godoc.org/github.com/disintegration/imaging)
|
||||
[![Build Status](https://travis-ci.org/disintegration/imaging.svg?branch=master)](https://travis-ci.org/disintegration/imaging)
|
||||
[![Coverage Status](https://coveralls.io/repos/github/disintegration/imaging/badge.svg?branch=master&service=github)](https://coveralls.io/github/disintegration/imaging?branch=master)
|
||||
[![Go Report Card](https://goreportcard.com/badge/github.com/disintegration/imaging)](https://goreportcard.com/report/github.com/disintegration/imaging)
|
||||
|
||||
Package imaging provides basic image processing functions (resize, rotate, crop, brightness/contrast adjustments, etc.).
|
||||
|
||||
All the image processing functions provided by the package accept any image type that implements `image.Image` interface
|
||||
as an input, and return a new image of `*image.NRGBA` type (32bit RGBA colors, not premultiplied by alpha).
|
||||
|
||||
## Installation
|
||||
|
||||
go get -u github.com/disintegration/imaging
|
||||
|
||||
## Documentation
|
||||
|
||||
http://godoc.org/github.com/disintegration/imaging
|
||||
|
||||
## Usage examples
|
||||
|
||||
A few usage examples can be found below. See the documentation for the full list of supported functions.
|
||||
|
||||
### Image resizing
|
||||
|
||||
```go
|
||||
// Resize srcImage to size = 128x128px using the Lanczos filter.
|
||||
dstImage128 := imaging.Resize(srcImage, 128, 128, imaging.Lanczos)
|
||||
|
||||
// Resize srcImage to width = 800px preserving the aspect ratio.
|
||||
dstImage800 := imaging.Resize(srcImage, 800, 0, imaging.Lanczos)
|
||||
|
||||
// Scale down srcImage to fit the 800x600px bounding box.
|
||||
dstImageFit := imaging.Fit(srcImage, 800, 600, imaging.Lanczos)
|
||||
|
||||
// Resize and crop the srcImage to fill the 100x100px area.
|
||||
dstImageFill := imaging.Fill(srcImage, 100, 100, imaging.Center, imaging.Lanczos)
|
||||
```
|
||||
|
||||
Imaging supports image resizing using various resampling filters. The most notable ones:
|
||||
- `NearestNeighbor` - Fastest resampling filter, no antialiasing.
|
||||
- `Box` - Simple and fast averaging filter appropriate for downscaling. When upscaling it's similar to NearestNeighbor.
|
||||
- `Linear` - Bilinear filter, smooth and reasonably fast.
|
||||
- `MitchellNetravali` - А smooth bicubic filter.
|
||||
- `CatmullRom` - A sharp bicubic filter.
|
||||
- `Gaussian` - Blurring filter that uses gaussian function, useful for noise removal.
|
||||
- `Lanczos` - High-quality resampling filter for photographic images yielding sharp results, slower than cubic filters.
|
||||
|
||||
The full list of supported filters: NearestNeighbor, Box, Linear, Hermite, MitchellNetravali, CatmullRom, BSpline, Gaussian, Lanczos, Hann, Hamming, Blackman, Bartlett, Welch, Cosine. Custom filters can be created using ResampleFilter struct.
|
||||
|
||||
**Resampling filters comparison**
|
||||
|
||||
Original image:
|
||||
|
||||
![srcImage](testdata/branches.png)
|
||||
|
||||
The same image resized from 600x400px to 150x100px using different resampling filters.
|
||||
From faster (lower quality) to slower (higher quality):
|
||||
|
||||
Filter | Resize result
|
||||
--------------------------|---------------------------------------------
|
||||
`imaging.NearestNeighbor` | ![dstImage](testdata/out_resize_nearest.png)
|
||||
`imaging.Linear` | ![dstImage](testdata/out_resize_linear.png)
|
||||
`imaging.CatmullRom` | ![dstImage](testdata/out_resize_catrom.png)
|
||||
`imaging.Lanczos` | ![dstImage](testdata/out_resize_lanczos.png)
|
||||
|
||||
|
||||
### Gaussian Blur
|
||||
|
||||
```go
|
||||
dstImage := imaging.Blur(srcImage, 0.5)
|
||||
```
|
||||
|
||||
Sigma parameter allows to control the strength of the blurring effect.
|
||||
|
||||
Original image | Sigma = 0.5 | Sigma = 1.5
|
||||
-----------------------------------|----------------------------------------|---------------------------------------
|
||||
![srcImage](testdata/flowers_small.png) | ![dstImage](testdata/out_blur_0.5.png) | ![dstImage](testdata/out_blur_1.5.png)
|
||||
|
||||
### Sharpening
|
||||
|
||||
```go
|
||||
dstImage := imaging.Sharpen(srcImage, 0.5)
|
||||
```
|
||||
|
||||
`Sharpen` uses gaussian function internally. Sigma parameter allows to control the strength of the sharpening effect.
|
||||
|
||||
Original image | Sigma = 0.5 | Sigma = 1.5
|
||||
-----------------------------------|-------------------------------------------|------------------------------------------
|
||||
![srcImage](testdata/flowers_small.png) | ![dstImage](testdata/out_sharpen_0.5.png) | ![dstImage](testdata/out_sharpen_1.5.png)
|
||||
|
||||
### Gamma correction
|
||||
|
||||
```go
|
||||
dstImage := imaging.AdjustGamma(srcImage, 0.75)
|
||||
```
|
||||
|
||||
Original image | Gamma = 0.75 | Gamma = 1.25
|
||||
-----------------------------------|------------------------------------------|-----------------------------------------
|
||||
![srcImage](testdata/flowers_small.png) | ![dstImage](testdata/out_gamma_0.75.png) | ![dstImage](testdata/out_gamma_1.25.png)
|
||||
|
||||
### Contrast adjustment
|
||||
|
||||
```go
|
||||
dstImage := imaging.AdjustContrast(srcImage, 20)
|
||||
```
|
||||
|
||||
Original image | Contrast = 15 | Contrast = -15
|
||||
-----------------------------------|--------------------------------------------|-------------------------------------------
|
||||
![srcImage](testdata/flowers_small.png) | ![dstImage](testdata/out_contrast_p15.png) | ![dstImage](testdata/out_contrast_m15.png)
|
||||
|
||||
### Brightness adjustment
|
||||
|
||||
```go
|
||||
dstImage := imaging.AdjustBrightness(srcImage, 20)
|
||||
```
|
||||
|
||||
Original image | Brightness = 10 | Brightness = -10
|
||||
-----------------------------------|----------------------------------------------|---------------------------------------------
|
||||
![srcImage](testdata/flowers_small.png) | ![dstImage](testdata/out_brightness_p10.png) | ![dstImage](testdata/out_brightness_m10.png)
|
||||
|
||||
## Example code
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"image"
|
||||
"image/color"
|
||||
"log"
|
||||
|
||||
"github.com/disintegration/imaging"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// Open a test image.
|
||||
src, err := imaging.Open("testdata/flowers.png")
|
||||
if err != nil {
|
||||
log.Fatalf("failed to open image: %v", err)
|
||||
}
|
||||
|
||||
// Crop the original image to 300x300px size using the center anchor.
|
||||
src = imaging.CropAnchor(src, 300, 300, imaging.Center)
|
||||
|
||||
// Resize the cropped image to width = 200px preserving the aspect ratio.
|
||||
src = imaging.Resize(src, 200, 0, imaging.Lanczos)
|
||||
|
||||
// Create a blurred version of the image.
|
||||
img1 := imaging.Blur(src, 5)
|
||||
|
||||
// Create a grayscale version of the image with higher contrast and sharpness.
|
||||
img2 := imaging.Grayscale(src)
|
||||
img2 = imaging.AdjustContrast(img2, 20)
|
||||
img2 = imaging.Sharpen(img2, 2)
|
||||
|
||||
// Create an inverted version of the image.
|
||||
img3 := imaging.Invert(src)
|
||||
|
||||
// Create an embossed version of the image using a convolution filter.
|
||||
img4 := imaging.Convolve3x3(
|
||||
src,
|
||||
[9]float64{
|
||||
-1, -1, 0,
|
||||
-1, 1, 1,
|
||||
0, 1, 1,
|
||||
},
|
||||
nil,
|
||||
)
|
||||
|
||||
// Create a new image and paste the four produced images into it.
|
||||
dst := imaging.New(400, 400, color.NRGBA{0, 0, 0, 0})
|
||||
dst = imaging.Paste(dst, img1, image.Pt(0, 0))
|
||||
dst = imaging.Paste(dst, img2, image.Pt(0, 200))
|
||||
dst = imaging.Paste(dst, img3, image.Pt(200, 0))
|
||||
dst = imaging.Paste(dst, img4, image.Pt(200, 200))
|
||||
|
||||
// Save the resulting image as JPEG.
|
||||
err = imaging.Save(dst, "testdata/out_example.jpg")
|
||||
if err != nil {
|
||||
log.Fatalf("failed to save image: %v", err)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
![dstImage](testdata/out_example.jpg)
|
|
@ -0,0 +1,222 @@
|
|||
package imaging
|
||||
|
||||
import (
|
||||
"image"
|
||||
"image/color"
|
||||
"math"
|
||||
)
|
||||
|
||||
// Grayscale produces a grayscale version of the image.
|
||||
func Grayscale(img image.Image) *image.NRGBA {
|
||||
src := newScanner(img)
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
|
||||
parallel(0, src.h, func(ys <-chan int) {
|
||||
for y := range ys {
|
||||
i := y * dst.Stride
|
||||
src.scan(0, y, src.w, y+1, dst.Pix[i:i+src.w*4])
|
||||
for x := 0; x < src.w; x++ {
|
||||
r := dst.Pix[i+0]
|
||||
g := dst.Pix[i+1]
|
||||
b := dst.Pix[i+2]
|
||||
f := 0.299*float64(r) + 0.587*float64(g) + 0.114*float64(b)
|
||||
y := uint8(f + 0.5)
|
||||
dst.Pix[i+0] = y
|
||||
dst.Pix[i+1] = y
|
||||
dst.Pix[i+2] = y
|
||||
i += 4
|
||||
}
|
||||
}
|
||||
})
|
||||
return dst
|
||||
}
|
||||
|
||||
// Invert produces an inverted (negated) version of the image.
|
||||
func Invert(img image.Image) *image.NRGBA {
|
||||
src := newScanner(img)
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
|
||||
parallel(0, src.h, func(ys <-chan int) {
|
||||
for y := range ys {
|
||||
i := y * dst.Stride
|
||||
src.scan(0, y, src.w, y+1, dst.Pix[i:i+src.w*4])
|
||||
for x := 0; x < src.w; x++ {
|
||||
dst.Pix[i+0] = 255 - dst.Pix[i+0]
|
||||
dst.Pix[i+1] = 255 - dst.Pix[i+1]
|
||||
dst.Pix[i+2] = 255 - dst.Pix[i+2]
|
||||
i += 4
|
||||
}
|
||||
}
|
||||
})
|
||||
return dst
|
||||
}
|
||||
|
||||
// AdjustContrast changes the contrast of the image using the percentage parameter and returns the adjusted image.
|
||||
// The percentage must be in range (-100, 100). The percentage = 0 gives the original image.
|
||||
// The percentage = -100 gives solid gray image.
|
||||
//
|
||||
// Examples:
|
||||
//
|
||||
// dstImage = imaging.AdjustContrast(srcImage, -10) // decrease image contrast by 10%
|
||||
// dstImage = imaging.AdjustContrast(srcImage, 20) // increase image contrast by 20%
|
||||
//
|
||||
func AdjustContrast(img image.Image, percentage float64) *image.NRGBA {
|
||||
percentage = math.Min(math.Max(percentage, -100.0), 100.0)
|
||||
lut := make([]uint8, 256)
|
||||
|
||||
v := (100.0 + percentage) / 100.0
|
||||
for i := 0; i < 256; i++ {
|
||||
if 0 <= v && v <= 1 {
|
||||
lut[i] = clamp((0.5 + (float64(i)/255.0-0.5)*v) * 255.0)
|
||||
} else if 1 < v && v < 2 {
|
||||
lut[i] = clamp((0.5 + (float64(i)/255.0-0.5)*(1/(2.0-v))) * 255.0)
|
||||
} else {
|
||||
lut[i] = uint8(float64(i)/255.0+0.5) * 255
|
||||
}
|
||||
}
|
||||
|
||||
return adjustLUT(img, lut)
|
||||
}
|
||||
|
||||
// AdjustBrightness changes the brightness of the image using the percentage parameter and returns the adjusted image.
|
||||
// The percentage must be in range (-100, 100). The percentage = 0 gives the original image.
|
||||
// The percentage = -100 gives solid black image. The percentage = 100 gives solid white image.
|
||||
//
|
||||
// Examples:
|
||||
//
|
||||
// dstImage = imaging.AdjustBrightness(srcImage, -15) // decrease image brightness by 15%
|
||||
// dstImage = imaging.AdjustBrightness(srcImage, 10) // increase image brightness by 10%
|
||||
//
|
||||
func AdjustBrightness(img image.Image, percentage float64) *image.NRGBA {
|
||||
percentage = math.Min(math.Max(percentage, -100.0), 100.0)
|
||||
lut := make([]uint8, 256)
|
||||
|
||||
shift := 255.0 * percentage / 100.0
|
||||
for i := 0; i < 256; i++ {
|
||||
lut[i] = clamp(float64(i) + shift)
|
||||
}
|
||||
|
||||
return adjustLUT(img, lut)
|
||||
}
|
||||
|
||||
// AdjustGamma performs a gamma correction on the image and returns the adjusted image.
|
||||
// Gamma parameter must be positive. Gamma = 1.0 gives the original image.
|
||||
// Gamma less than 1.0 darkens the image and gamma greater than 1.0 lightens it.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// dstImage = imaging.AdjustGamma(srcImage, 0.7)
|
||||
//
|
||||
func AdjustGamma(img image.Image, gamma float64) *image.NRGBA {
|
||||
e := 1.0 / math.Max(gamma, 0.0001)
|
||||
lut := make([]uint8, 256)
|
||||
|
||||
for i := 0; i < 256; i++ {
|
||||
lut[i] = clamp(math.Pow(float64(i)/255.0, e) * 255.0)
|
||||
}
|
||||
|
||||
return adjustLUT(img, lut)
|
||||
}
|
||||
|
||||
// AdjustSigmoid changes the contrast of the image using a sigmoidal function and returns the adjusted image.
|
||||
// It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail.
|
||||
// The midpoint parameter is the midpoint of contrast that must be between 0 and 1, typically 0.5.
|
||||
// The factor parameter indicates how much to increase or decrease the contrast, typically in range (-10, 10).
|
||||
// If the factor parameter is positive the image contrast is increased otherwise the contrast is decreased.
|
||||
//
|
||||
// Examples:
|
||||
//
|
||||
// dstImage = imaging.AdjustSigmoid(srcImage, 0.5, 3.0) // increase the contrast
|
||||
// dstImage = imaging.AdjustSigmoid(srcImage, 0.5, -3.0) // decrease the contrast
|
||||
//
|
||||
func AdjustSigmoid(img image.Image, midpoint, factor float64) *image.NRGBA {
|
||||
if factor == 0 {
|
||||
return Clone(img)
|
||||
}
|
||||
|
||||
lut := make([]uint8, 256)
|
||||
a := math.Min(math.Max(midpoint, 0.0), 1.0)
|
||||
b := math.Abs(factor)
|
||||
sig0 := sigmoid(a, b, 0)
|
||||
sig1 := sigmoid(a, b, 1)
|
||||
e := 1.0e-6
|
||||
|
||||
if factor > 0 {
|
||||
for i := 0; i < 256; i++ {
|
||||
x := float64(i) / 255.0
|
||||
sigX := sigmoid(a, b, x)
|
||||
f := (sigX - sig0) / (sig1 - sig0)
|
||||
lut[i] = clamp(f * 255.0)
|
||||
}
|
||||
} else {
|
||||
for i := 0; i < 256; i++ {
|
||||
x := float64(i) / 255.0
|
||||
arg := math.Min(math.Max((sig1-sig0)*x+sig0, e), 1.0-e)
|
||||
f := a - math.Log(1.0/arg-1.0)/b
|
||||
lut[i] = clamp(f * 255.0)
|
||||
}
|
||||
}
|
||||
|
||||
return adjustLUT(img, lut)
|
||||
}
|
||||
|
||||
func sigmoid(a, b, x float64) float64 {
|
||||
return 1 / (1 + math.Exp(b*(a-x)))
|
||||
}
|
||||
|
||||
// adjustLUT applies the given lookup table to the colors of the image.
|
||||
func adjustLUT(img image.Image, lut []uint8) *image.NRGBA {
|
||||
src := newScanner(img)
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
|
||||
parallel(0, src.h, func(ys <-chan int) {
|
||||
for y := range ys {
|
||||
i := y * dst.Stride
|
||||
src.scan(0, y, src.w, y+1, dst.Pix[i:i+src.w*4])
|
||||
for x := 0; x < src.w; x++ {
|
||||
dst.Pix[i+0] = lut[dst.Pix[i+0]]
|
||||
dst.Pix[i+1] = lut[dst.Pix[i+1]]
|
||||
dst.Pix[i+2] = lut[dst.Pix[i+2]]
|
||||
i += 4
|
||||
}
|
||||
}
|
||||
})
|
||||
return dst
|
||||
}
|
||||
|
||||
// AdjustFunc applies the fn function to each pixel of the img image and returns the adjusted image.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// dstImage = imaging.AdjustFunc(
|
||||
// srcImage,
|
||||
// func(c color.NRGBA) color.NRGBA {
|
||||
// // shift the red channel by 16
|
||||
// r := int(c.R) + 16
|
||||
// if r > 255 {
|
||||
// r = 255
|
||||
// }
|
||||
// return color.NRGBA{uint8(r), c.G, c.B, c.A}
|
||||
// }
|
||||
// )
|
||||
//
|
||||
func AdjustFunc(img image.Image, fn func(c color.NRGBA) color.NRGBA) *image.NRGBA {
|
||||
src := newScanner(img)
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
|
||||
parallel(0, src.h, func(ys <-chan int) {
|
||||
for y := range ys {
|
||||
i := y * dst.Stride
|
||||
src.scan(0, y, src.w, y+1, dst.Pix[i:i+src.w*4])
|
||||
for x := 0; x < src.w; x++ {
|
||||
r := dst.Pix[i+0]
|
||||
g := dst.Pix[i+1]
|
||||
b := dst.Pix[i+2]
|
||||
a := dst.Pix[i+3]
|
||||
c := fn(color.NRGBA{r, g, b, a})
|
||||
dst.Pix[i+0] = c.R
|
||||
dst.Pix[i+1] = c.G
|
||||
dst.Pix[i+2] = c.B
|
||||
dst.Pix[i+3] = c.A
|
||||
i += 4
|
||||
}
|
||||
}
|
||||
})
|
||||
return dst
|
||||
}
|
|
@ -0,0 +1,146 @@
|
|||
package imaging
|
||||
|
||||
import (
|
||||
"image"
|
||||
)
|
||||
|
||||
// ConvolveOptions are convolution parameters.
|
||||
type ConvolveOptions struct {
|
||||
// If Normalize is true the kernel is normalized before convolution.
|
||||
Normalize bool
|
||||
|
||||
// If Abs is true the absolute value of each color channel is taken after convolution.
|
||||
Abs bool
|
||||
|
||||
// Bias is added to each color channel value after convolution.
|
||||
Bias int
|
||||
}
|
||||
|
||||
// Convolve3x3 convolves the image with the specified 3x3 convolution kernel.
|
||||
// Default parameters are used if a nil *ConvolveOptions is passed.
|
||||
func Convolve3x3(img image.Image, kernel [9]float64, options *ConvolveOptions) *image.NRGBA {
|
||||
return convolve(img, kernel[:], options)
|
||||
}
|
||||
|
||||
// Convolve5x5 convolves the image with the specified 5x5 convolution kernel.
|
||||
// Default parameters are used if a nil *ConvolveOptions is passed.
|
||||
func Convolve5x5(img image.Image, kernel [25]float64, options *ConvolveOptions) *image.NRGBA {
|
||||
return convolve(img, kernel[:], options)
|
||||
}
|
||||
|
||||
func convolve(img image.Image, kernel []float64, options *ConvolveOptions) *image.NRGBA {
|
||||
src := toNRGBA(img)
|
||||
w := src.Bounds().Max.X
|
||||
h := src.Bounds().Max.Y
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, w, h))
|
||||
|
||||
if w < 1 || h < 1 {
|
||||
return dst
|
||||
}
|
||||
|
||||
if options == nil {
|
||||
options = &ConvolveOptions{}
|
||||
}
|
||||
|
||||
if options.Normalize {
|
||||
normalizeKernel(kernel)
|
||||
}
|
||||
|
||||
type coef struct {
|
||||
x, y int
|
||||
k float64
|
||||
}
|
||||
var coefs []coef
|
||||
var m int
|
||||
|
||||
switch len(kernel) {
|
||||
case 9:
|
||||
m = 1
|
||||
case 25:
|
||||
m = 2
|
||||
}
|
||||
|
||||
i := 0
|
||||
for y := -m; y <= m; y++ {
|
||||
for x := -m; x <= m; x++ {
|
||||
if kernel[i] != 0 {
|
||||
coefs = append(coefs, coef{x: x, y: y, k: kernel[i]})
|
||||
}
|
||||
i++
|
||||
}
|
||||
}
|
||||
|
||||
parallel(0, h, func(ys <-chan int) {
|
||||
for y := range ys {
|
||||
for x := 0; x < w; x++ {
|
||||
var r, g, b float64
|
||||
for _, c := range coefs {
|
||||
ix := x + c.x
|
||||
if ix < 0 {
|
||||
ix = 0
|
||||
} else if ix >= w {
|
||||
ix = w - 1
|
||||
}
|
||||
|
||||
iy := y + c.y
|
||||
if iy < 0 {
|
||||
iy = 0
|
||||
} else if iy >= h {
|
||||
iy = h - 1
|
||||
}
|
||||
|
||||
off := iy*src.Stride + ix*4
|
||||
r += float64(src.Pix[off+0]) * c.k
|
||||
g += float64(src.Pix[off+1]) * c.k
|
||||
b += float64(src.Pix[off+2]) * c.k
|
||||
}
|
||||
|
||||
if options.Abs {
|
||||
if r < 0 {
|
||||
r = -r
|
||||
}
|
||||
if g < 0 {
|
||||
g = -g
|
||||
}
|
||||
if b < 0 {
|
||||
b = -b
|
||||
}
|
||||
}
|
||||
|
||||
if options.Bias != 0 {
|
||||
r += float64(options.Bias)
|
||||
g += float64(options.Bias)
|
||||
b += float64(options.Bias)
|
||||
}
|
||||
|
||||
srcOff := y*src.Stride + x*4
|
||||
dstOff := y*dst.Stride + x*4
|
||||
dst.Pix[dstOff+0] = clamp(r)
|
||||
dst.Pix[dstOff+1] = clamp(g)
|
||||
dst.Pix[dstOff+2] = clamp(b)
|
||||
dst.Pix[dstOff+3] = src.Pix[srcOff+3]
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return dst
|
||||
}
|
||||
|
||||
func normalizeKernel(kernel []float64) {
|
||||
var sum, sumpos float64
|
||||
for i := range kernel {
|
||||
sum += kernel[i]
|
||||
if kernel[i] > 0 {
|
||||
sumpos += kernel[i]
|
||||
}
|
||||
}
|
||||
if sum != 0 {
|
||||
for i := range kernel {
|
||||
kernel[i] /= sum
|
||||
}
|
||||
} else if sumpos != 0 {
|
||||
for i := range kernel {
|
||||
kernel[i] /= sumpos
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
/*
|
||||
Package imaging provides basic image processing functions (resize, rotate, crop, brightness/contrast adjustments, etc.).
|
||||
|
||||
All the image processing functions provided by the package accept any image type that implements image.Image interface
|
||||
as an input, and return a new image of *image.NRGBA type (32bit RGBA colors, not premultiplied by alpha).
|
||||
*/
|
||||
package imaging
|
|
@ -0,0 +1,173 @@
|
|||
package imaging
|
||||
|
||||
import (
|
||||
"image"
|
||||
"math"
|
||||
)
|
||||
|
||||
func gaussianBlurKernel(x, sigma float64) float64 {
|
||||
return math.Exp(-(x*x)/(2*sigma*sigma)) / (sigma * math.Sqrt(2*math.Pi))
|
||||
}
|
||||
|
||||
// Blur produces a blurred version of the image using a Gaussian function.
|
||||
// Sigma parameter must be positive and indicates how much the image will be blurred.
|
||||
//
|
||||
// Usage example:
|
||||
//
|
||||
// dstImage := imaging.Blur(srcImage, 3.5)
|
||||
//
|
||||
func Blur(img image.Image, sigma float64) *image.NRGBA {
|
||||
if sigma <= 0 {
|
||||
return Clone(img)
|
||||
}
|
||||
|
||||
radius := int(math.Ceil(sigma * 3.0))
|
||||
kernel := make([]float64, radius+1)
|
||||
|
||||
for i := 0; i <= radius; i++ {
|
||||
kernel[i] = gaussianBlurKernel(float64(i), sigma)
|
||||
}
|
||||
|
||||
return blurVertical(blurHorizontal(img, kernel), kernel)
|
||||
}
|
||||
|
||||
func blurHorizontal(img image.Image, kernel []float64) *image.NRGBA {
|
||||
src := newScanner(img)
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
|
||||
radius := len(kernel) - 1
|
||||
|
||||
parallel(0, src.h, func(ys <-chan int) {
|
||||
scanLine := make([]uint8, src.w*4)
|
||||
scanLineF := make([]float64, len(scanLine))
|
||||
for y := range ys {
|
||||
src.scan(0, y, src.w, y+1, scanLine)
|
||||
for i, v := range scanLine {
|
||||
scanLineF[i] = float64(v)
|
||||
}
|
||||
for x, idx := 0, 0; x < src.w; x, idx = x+1, idx+4 {
|
||||
min := x - radius
|
||||
if min < 0 {
|
||||
min = 0
|
||||
}
|
||||
max := x + radius
|
||||
if max > src.w-1 {
|
||||
max = src.w - 1
|
||||
}
|
||||
|
||||
var r, g, b, a, wsum float64
|
||||
for ix := min; ix <= max; ix++ {
|
||||
i := ix * 4
|
||||
weight := kernel[absint(x-ix)]
|
||||
wsum += weight
|
||||
wa := scanLineF[i+3] * weight
|
||||
r += scanLineF[i+0] * wa
|
||||
g += scanLineF[i+1] * wa
|
||||
b += scanLineF[i+2] * wa
|
||||
a += wa
|
||||
}
|
||||
if a != 0 {
|
||||
r /= a
|
||||
g /= a
|
||||
b /= a
|
||||
}
|
||||
|
||||
scanLine[idx+0] = clamp(r)
|
||||
scanLine[idx+1] = clamp(g)
|
||||
scanLine[idx+2] = clamp(b)
|
||||
scanLine[idx+3] = clamp(a / wsum)
|
||||
}
|
||||
copy(dst.Pix[y*dst.Stride:], scanLine)
|
||||
}
|
||||
})
|
||||
|
||||
return dst
|
||||
}
|
||||
|
||||
func blurVertical(img image.Image, kernel []float64) *image.NRGBA {
|
||||
src := newScanner(img)
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
|
||||
radius := len(kernel) - 1
|
||||
|
||||
parallel(0, src.w, func(xs <-chan int) {
|
||||
scanLine := make([]uint8, src.h*4)
|
||||
scanLineF := make([]float64, len(scanLine))
|
||||
for x := range xs {
|
||||
src.scan(x, 0, x+1, src.h, scanLine)
|
||||
for i, v := range scanLine {
|
||||
scanLineF[i] = float64(v)
|
||||
}
|
||||
for y := 0; y < src.h; y++ {
|
||||
min := y - radius
|
||||
if min < 0 {
|
||||
min = 0
|
||||
}
|
||||
max := y + radius
|
||||
if max > src.h-1 {
|
||||
max = src.h - 1
|
||||
}
|
||||
|
||||
var r, g, b, a, wsum float64
|
||||
for iy := min; iy <= max; iy++ {
|
||||
i := iy * 4
|
||||
weight := kernel[absint(y-iy)]
|
||||
wsum += weight
|
||||
wa := scanLineF[i+3] * weight
|
||||
r += scanLineF[i+0] * wa
|
||||
g += scanLineF[i+1] * wa
|
||||
b += scanLineF[i+2] * wa
|
||||
a += wa
|
||||
}
|
||||
if a != 0 {
|
||||
r /= a
|
||||
g /= a
|
||||
b /= a
|
||||
}
|
||||
|
||||
j := y*dst.Stride + x*4
|
||||
dst.Pix[j+0] = clamp(r)
|
||||
dst.Pix[j+1] = clamp(g)
|
||||
dst.Pix[j+2] = clamp(b)
|
||||
dst.Pix[j+3] = clamp(a / wsum)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return dst
|
||||
}
|
||||
|
||||
// Sharpen produces a sharpened version of the image.
|
||||
// Sigma parameter must be positive and indicates how much the image will be sharpened.
|
||||
//
|
||||
// Usage example:
|
||||
//
|
||||
// dstImage := imaging.Sharpen(srcImage, 3.5)
|
||||
//
|
||||
func Sharpen(img image.Image, sigma float64) *image.NRGBA {
|
||||
if sigma <= 0 {
|
||||
return Clone(img)
|
||||
}
|
||||
|
||||
src := newScanner(img)
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
|
||||
blurred := Blur(img, sigma)
|
||||
|
||||
parallel(0, src.h, func(ys <-chan int) {
|
||||
scanLine := make([]uint8, src.w*4)
|
||||
for y := range ys {
|
||||
src.scan(0, y, src.w, y+1, scanLine)
|
||||
j := y * dst.Stride
|
||||
for i := 0; i < src.w*4; i++ {
|
||||
val := int(scanLine[i])<<1 - int(blurred.Pix[j])
|
||||
if val < 0 {
|
||||
val = 0
|
||||
} else if val > 0xff {
|
||||
val = 0xff
|
||||
}
|
||||
dst.Pix[j] = uint8(val)
|
||||
j++
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return dst
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
module github.com/disintegration/imaging
|
||||
|
||||
require golang.org/x/image v0.0.0-20180708004352-c73c2afc3b81
|
|
@ -0,0 +1,2 @@
|
|||
golang.org/x/image v0.0.0-20180708004352-c73c2afc3b81 h1:00VmoueYNlNz/aHIilyyQz/MHSqGoWJzpFv/HW8xpzI=
|
||||
golang.org/x/image v0.0.0-20180708004352-c73c2afc3b81/go.mod h1:ux5Hcp/YLpHSI86hEcLt0YII63i6oz57MZXIpbrjZUs=
|
|
@ -0,0 +1,51 @@
|
|||
package imaging
|
||||
|
||||
import (
|
||||
"image"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// Histogram returns a normalized histogram of an image.
|
||||
//
|
||||
// Resulting histogram is represented as an array of 256 floats, where
|
||||
// histogram[i] is a probability of a pixel being of a particular luminance i.
|
||||
func Histogram(img image.Image) [256]float64 {
|
||||
var mu sync.Mutex
|
||||
var histogram [256]float64
|
||||
var total float64
|
||||
|
||||
src := newScanner(img)
|
||||
if src.w == 0 || src.h == 0 {
|
||||
return histogram
|
||||
}
|
||||
|
||||
parallel(0, src.h, func(ys <-chan int) {
|
||||
var tmpHistogram [256]float64
|
||||
var tmpTotal float64
|
||||
scanLine := make([]uint8, src.w*4)
|
||||
for y := range ys {
|
||||
src.scan(0, y, src.w, y+1, scanLine)
|
||||
i := 0
|
||||
for x := 0; x < src.w; x++ {
|
||||
r := scanLine[i+0]
|
||||
g := scanLine[i+1]
|
||||
b := scanLine[i+2]
|
||||
y := 0.299*float32(r) + 0.587*float32(g) + 0.114*float32(b)
|
||||
tmpHistogram[int(y+0.5)]++
|
||||
tmpTotal++
|
||||
i += 4
|
||||
}
|
||||
}
|
||||
mu.Lock()
|
||||
for i := 0; i < 256; i++ {
|
||||
histogram[i] += tmpHistogram[i]
|
||||
}
|
||||
total += tmpTotal
|
||||
mu.Unlock()
|
||||
})
|
||||
|
||||
for i := 0; i < 256; i++ {
|
||||
histogram[i] = histogram[i] / total
|
||||
}
|
||||
return histogram
|
||||
}
|
|
@ -0,0 +1,463 @@
|
|||
package imaging
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"image"
|
||||
"image/draw"
|
||||
"image/gif"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/image/bmp"
|
||||
"golang.org/x/image/tiff"
|
||||
)
|
||||
|
||||
// Format is an image file format.
|
||||
type Format int
|
||||
|
||||
// Image file formats.
|
||||
const (
|
||||
JPEG Format = iota
|
||||
PNG
|
||||
GIF
|
||||
TIFF
|
||||
BMP
|
||||
)
|
||||
|
||||
func (f Format) String() string {
|
||||
switch f {
|
||||
case JPEG:
|
||||
return "JPEG"
|
||||
case PNG:
|
||||
return "PNG"
|
||||
case GIF:
|
||||
return "GIF"
|
||||
case TIFF:
|
||||
return "TIFF"
|
||||
case BMP:
|
||||
return "BMP"
|
||||
default:
|
||||
return "Unsupported"
|
||||
}
|
||||
}
|
||||
|
||||
var formatFromExt = map[string]Format{
|
||||
"jpg": JPEG,
|
||||
"jpeg": JPEG,
|
||||
"png": PNG,
|
||||
"tif": TIFF,
|
||||
"tiff": TIFF,
|
||||
"bmp": BMP,
|
||||
"gif": GIF,
|
||||
}
|
||||
|
||||
// FormatFromExtension parses image format from extension:
|
||||
// "jpg" (or "jpeg"), "png", "gif", "tif" (or "tiff") and "bmp" are supported.
|
||||
func FormatFromExtension(ext string) (Format, error) {
|
||||
if f, ok := formatFromExt[strings.ToLower(strings.TrimPrefix(ext, "."))]; ok {
|
||||
return f, nil
|
||||
}
|
||||
return -1, ErrUnsupportedFormat
|
||||
}
|
||||
|
||||
// FormatFromFilename parses image format from filename extension:
|
||||
// "jpg" (or "jpeg"), "png", "gif", "tif" (or "tiff") and "bmp" are supported.
|
||||
func FormatFromFilename(filename string) (Format, error) {
|
||||
ext := filepath.Ext(filename)
|
||||
return FormatFromExtension(ext)
|
||||
}
|
||||
|
||||
var (
|
||||
// ErrUnsupportedFormat means the given image format (or file extension) is unsupported.
|
||||
ErrUnsupportedFormat = errors.New("imaging: unsupported image format")
|
||||
)
|
||||
|
||||
type fileSystem interface {
|
||||
Create(string) (io.WriteCloser, error)
|
||||
Open(string) (io.ReadCloser, error)
|
||||
}
|
||||
|
||||
type localFS struct{}
|
||||
|
||||
func (localFS) Create(name string) (io.WriteCloser, error) { return os.Create(name) }
|
||||
func (localFS) Open(name string) (io.ReadCloser, error) { return os.Open(name) }
|
||||
|
||||
var fs fileSystem = localFS{}
|
||||
|
||||
type decodeConfig struct {
|
||||
autoOrientation bool
|
||||
}
|
||||
|
||||
var defaultDecodeConfig = decodeConfig{
|
||||
autoOrientation: false,
|
||||
}
|
||||
|
||||
// DecodeOption sets an optional parameter for the Decode and Open functions.
|
||||
type DecodeOption func(*decodeConfig)
|
||||
|
||||
// AutoOrientation returns a DecodeOption that sets the auto-orientation mode.
|
||||
// If auto-orientation is enabled, the image will be transformed after decoding
|
||||
// according to the EXIF orientation tag (if present). By default it's disabled.
|
||||
func AutoOrientation(enabled bool) DecodeOption {
|
||||
return func(c *decodeConfig) {
|
||||
c.autoOrientation = enabled
|
||||
}
|
||||
}
|
||||
|
||||
// Decode reads an image from r.
|
||||
func Decode(r io.Reader, opts ...DecodeOption) (image.Image, error) {
|
||||
cfg := defaultDecodeConfig
|
||||
for _, option := range opts {
|
||||
option(&cfg)
|
||||
}
|
||||
|
||||
if !cfg.autoOrientation {
|
||||
img, _, err := image.Decode(r)
|
||||
return img, err
|
||||
}
|
||||
|
||||
var orient orientation
|
||||
pr, pw := io.Pipe()
|
||||
r = io.TeeReader(r, pw)
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
orient = readOrientation(pr)
|
||||
io.Copy(ioutil.Discard, pr)
|
||||
}()
|
||||
|
||||
img, _, err := image.Decode(r)
|
||||
pw.Close()
|
||||
<-done
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return fixOrientation(img, orient), nil
|
||||
}
|
||||
|
||||
// Open loads an image from file.
|
||||
//
|
||||
// Examples:
|
||||
//
|
||||
// // Load an image from file.
|
||||
// img, err := imaging.Open("test.jpg")
|
||||
//
|
||||
// // Load an image and transform it depending on the EXIF orientation tag (if present).
|
||||
// img, err := imaging.Open("test.jpg", imaging.AutoOrientation(true))
|
||||
//
|
||||
func Open(filename string, opts ...DecodeOption) (image.Image, error) {
|
||||
file, err := fs.Open(filename)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer file.Close()
|
||||
return Decode(file, opts...)
|
||||
}
|
||||
|
||||
type encodeConfig struct {
|
||||
jpegQuality int
|
||||
gifNumColors int
|
||||
gifQuantizer draw.Quantizer
|
||||
gifDrawer draw.Drawer
|
||||
pngCompressionLevel png.CompressionLevel
|
||||
}
|
||||
|
||||
var defaultEncodeConfig = encodeConfig{
|
||||
jpegQuality: 95,
|
||||
gifNumColors: 256,
|
||||
gifQuantizer: nil,
|
||||
gifDrawer: nil,
|
||||
pngCompressionLevel: png.DefaultCompression,
|
||||
}
|
||||
|
||||
// EncodeOption sets an optional parameter for the Encode and Save functions.
|
||||
type EncodeOption func(*encodeConfig)
|
||||
|
||||
// JPEGQuality returns an EncodeOption that sets the output JPEG quality.
|
||||
// Quality ranges from 1 to 100 inclusive, higher is better. Default is 95.
|
||||
func JPEGQuality(quality int) EncodeOption {
|
||||
return func(c *encodeConfig) {
|
||||
c.jpegQuality = quality
|
||||
}
|
||||
}
|
||||
|
||||
// GIFNumColors returns an EncodeOption that sets the maximum number of colors
|
||||
// used in the GIF-encoded image. It ranges from 1 to 256. Default is 256.
|
||||
func GIFNumColors(numColors int) EncodeOption {
|
||||
return func(c *encodeConfig) {
|
||||
c.gifNumColors = numColors
|
||||
}
|
||||
}
|
||||
|
||||
// GIFQuantizer returns an EncodeOption that sets the quantizer that is used to produce
|
||||
// a palette of the GIF-encoded image.
|
||||
func GIFQuantizer(quantizer draw.Quantizer) EncodeOption {
|
||||
return func(c *encodeConfig) {
|
||||
c.gifQuantizer = quantizer
|
||||
}
|
||||
}
|
||||
|
||||
// GIFDrawer returns an EncodeOption that sets the drawer that is used to convert
|
||||
// the source image to the desired palette of the GIF-encoded image.
|
||||
func GIFDrawer(drawer draw.Drawer) EncodeOption {
|
||||
return func(c *encodeConfig) {
|
||||
c.gifDrawer = drawer
|
||||
}
|
||||
}
|
||||
|
||||
// PNGCompressionLevel returns an EncodeOption that sets the compression level
|
||||
// of the PNG-encoded image. Default is png.DefaultCompression.
|
||||
func PNGCompressionLevel(level png.CompressionLevel) EncodeOption {
|
||||
return func(c *encodeConfig) {
|
||||
c.pngCompressionLevel = level
|
||||
}
|
||||
}
|
||||
|
||||
// Encode writes the image img to w in the specified format (JPEG, PNG, GIF, TIFF or BMP).
|
||||
func Encode(w io.Writer, img image.Image, format Format, opts ...EncodeOption) error {
|
||||
cfg := defaultEncodeConfig
|
||||
for _, option := range opts {
|
||||
option(&cfg)
|
||||
}
|
||||
|
||||
var err error
|
||||
switch format {
|
||||
case JPEG:
|
||||
var rgba *image.RGBA
|
||||
if nrgba, ok := img.(*image.NRGBA); ok {
|
||||
if nrgba.Opaque() {
|
||||
rgba = &image.RGBA{
|
||||
Pix: nrgba.Pix,
|
||||
Stride: nrgba.Stride,
|
||||
Rect: nrgba.Rect,
|
||||
}
|
||||
}
|
||||
}
|
||||
if rgba != nil {
|
||||
err = jpeg.Encode(w, rgba, &jpeg.Options{Quality: cfg.jpegQuality})
|
||||
} else {
|
||||
err = jpeg.Encode(w, img, &jpeg.Options{Quality: cfg.jpegQuality})
|
||||
}
|
||||
|
||||
case PNG:
|
||||
enc := png.Encoder{CompressionLevel: cfg.pngCompressionLevel}
|
||||
err = enc.Encode(w, img)
|
||||
|
||||
case GIF:
|
||||
err = gif.Encode(w, img, &gif.Options{
|
||||
NumColors: cfg.gifNumColors,
|
||||
Quantizer: cfg.gifQuantizer,
|
||||
Drawer: cfg.gifDrawer,
|
||||
})
|
||||
|
||||
case TIFF:
|
||||
err = tiff.Encode(w, img, &tiff.Options{Compression: tiff.Deflate, Predictor: true})
|
||||
|
||||
case BMP:
|
||||
err = bmp.Encode(w, img)
|
||||
|
||||
default:
|
||||
err = ErrUnsupportedFormat
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Save saves the image to file with the specified filename.
|
||||
// The format is determined from the filename extension:
|
||||
// "jpg" (or "jpeg"), "png", "gif", "tif" (or "tiff") and "bmp" are supported.
|
||||
//
|
||||
// Examples:
|
||||
//
|
||||
// // Save the image as PNG.
|
||||
// err := imaging.Save(img, "out.png")
|
||||
//
|
||||
// // Save the image as JPEG with optional quality parameter set to 80.
|
||||
// err := imaging.Save(img, "out.jpg", imaging.JPEGQuality(80))
|
||||
//
|
||||
func Save(img image.Image, filename string, opts ...EncodeOption) (err error) {
|
||||
f, err := FormatFromFilename(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
file, err := fs.Create(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer func() {
|
||||
cerr := file.Close()
|
||||
if err == nil {
|
||||
err = cerr
|
||||
}
|
||||
}()
|
||||
|
||||
return Encode(file, img, f, opts...)
|
||||
}
|
||||
|
||||
// orientation is an EXIF flag that specifies the transformation
|
||||
// that should be applied to image to display it correctly.
|
||||
type orientation int
|
||||
|
||||
const (
|
||||
orientationUnspecified = 0
|
||||
orientationNormal = 1
|
||||
orientationFlipH = 2
|
||||
orientationRotate180 = 3
|
||||
orientationFlipV = 4
|
||||
orientationTranspose = 5
|
||||
orientationRotate270 = 6
|
||||
orientationTransverse = 7
|
||||
orientationRotate90 = 8
|
||||
)
|
||||
|
||||
// readOrientation tries to read the orientation EXIF flag from image data in r.
|
||||
// If the EXIF data block is not found or the orientation flag is not found
|
||||
// or any other error occures while reading the data, it returns the
|
||||
// orientationUnspecified (0) value.
|
||||
func readOrientation(r io.Reader) orientation {
|
||||
const (
|
||||
markerSOI = 0xffd8
|
||||
markerAPP1 = 0xffe1
|
||||
exifHeader = 0x45786966
|
||||
byteOrderBE = 0x4d4d
|
||||
byteOrderLE = 0x4949
|
||||
orientationTag = 0x0112
|
||||
)
|
||||
|
||||
// Check if JPEG SOI marker is present.
|
||||
var soi uint16
|
||||
if err := binary.Read(r, binary.BigEndian, &soi); err != nil {
|
||||
return orientationUnspecified
|
||||
}
|
||||
if soi != markerSOI {
|
||||
return orientationUnspecified // Missing JPEG SOI marker.
|
||||
}
|
||||
|
||||
// Find JPEG APP1 marker.
|
||||
for {
|
||||
var marker, size uint16
|
||||
if err := binary.Read(r, binary.BigEndian, &marker); err != nil {
|
||||
return orientationUnspecified
|
||||
}
|
||||
if err := binary.Read(r, binary.BigEndian, &size); err != nil {
|
||||
return orientationUnspecified
|
||||
}
|
||||
if marker>>8 != 0xff {
|
||||
return orientationUnspecified // Invalid JPEG marker.
|
||||
}
|
||||
if marker == markerAPP1 {
|
||||
break
|
||||
}
|
||||
if size < 2 {
|
||||
return orientationUnspecified // Invalid block size.
|
||||
}
|
||||
if _, err := io.CopyN(ioutil.Discard, r, int64(size-2)); err != nil {
|
||||
return orientationUnspecified
|
||||
}
|
||||
}
|
||||
|
||||
// Check if EXIF header is present.
|
||||
var header uint32
|
||||
if err := binary.Read(r, binary.BigEndian, &header); err != nil {
|
||||
return orientationUnspecified
|
||||
}
|
||||
if header != exifHeader {
|
||||
return orientationUnspecified
|
||||
}
|
||||
if _, err := io.CopyN(ioutil.Discard, r, 2); err != nil {
|
||||
return orientationUnspecified
|
||||
}
|
||||
|
||||
// Read byte order information.
|
||||
var (
|
||||
byteOrderTag uint16
|
||||
byteOrder binary.ByteOrder
|
||||
)
|
||||
if err := binary.Read(r, binary.BigEndian, &byteOrderTag); err != nil {
|
||||
return orientationUnspecified
|
||||
}
|
||||
switch byteOrderTag {
|
||||
case byteOrderBE:
|
||||
byteOrder = binary.BigEndian
|
||||
case byteOrderLE:
|
||||
byteOrder = binary.LittleEndian
|
||||
default:
|
||||
return orientationUnspecified // Invalid byte order flag.
|
||||
}
|
||||
if _, err := io.CopyN(ioutil.Discard, r, 2); err != nil {
|
||||
return orientationUnspecified
|
||||
}
|
||||
|
||||
// Skip the EXIF offset.
|
||||
var offset uint32
|
||||
if err := binary.Read(r, byteOrder, &offset); err != nil {
|
||||
return orientationUnspecified
|
||||
}
|
||||
if offset < 8 {
|
||||
return orientationUnspecified // Invalid offset value.
|
||||
}
|
||||
if _, err := io.CopyN(ioutil.Discard, r, int64(offset-8)); err != nil {
|
||||
return orientationUnspecified
|
||||
}
|
||||
|
||||
// Read the number of tags.
|
||||
var numTags uint16
|
||||
if err := binary.Read(r, byteOrder, &numTags); err != nil {
|
||||
return orientationUnspecified
|
||||
}
|
||||
|
||||
// Find the orientation tag.
|
||||
for i := 0; i < int(numTags); i++ {
|
||||
var tag uint16
|
||||
if err := binary.Read(r, byteOrder, &tag); err != nil {
|
||||
return orientationUnspecified
|
||||
}
|
||||
if tag != orientationTag {
|
||||
if _, err := io.CopyN(ioutil.Discard, r, 10); err != nil {
|
||||
return orientationUnspecified
|
||||
}
|
||||
continue
|
||||
}
|
||||
if _, err := io.CopyN(ioutil.Discard, r, 6); err != nil {
|
||||
return orientationUnspecified
|
||||
}
|
||||
var val uint16
|
||||
if err := binary.Read(r, byteOrder, &val); err != nil {
|
||||
return orientationUnspecified
|
||||
}
|
||||
if val < 1 || val > 8 {
|
||||
return orientationUnspecified // Invalid tag value.
|
||||
}
|
||||
return orientation(val)
|
||||
}
|
||||
return orientationUnspecified // Missing orientation tag.
|
||||
}
|
||||
|
||||
// fixOrientation applies a transform to img corresponding to the given orientation flag.
|
||||
func fixOrientation(img image.Image, o orientation) image.Image {
|
||||
switch o {
|
||||
case orientationNormal:
|
||||
case orientationFlipH:
|
||||
img = FlipH(img)
|
||||
case orientationFlipV:
|
||||
img = FlipV(img)
|
||||
case orientationRotate90:
|
||||
img = Rotate90(img)
|
||||
case orientationRotate180:
|
||||
img = Rotate180(img)
|
||||
case orientationRotate270:
|
||||
img = Rotate270(img)
|
||||
case orientationTranspose:
|
||||
img = Transpose(img)
|
||||
case orientationTransverse:
|
||||
img = Transverse(img)
|
||||
}
|
||||
return img
|
||||
}
|
|
@ -0,0 +1,576 @@
|
|||
package imaging
|
||||
|
||||
import (
|
||||
"image"
|
||||
"math"
|
||||
)
|
||||
|
||||
type indexWeight struct {
|
||||
index int
|
||||
weight float64
|
||||
}
|
||||
|
||||
func precomputeWeights(dstSize, srcSize int, filter ResampleFilter) [][]indexWeight {
|
||||
du := float64(srcSize) / float64(dstSize)
|
||||
scale := du
|
||||
if scale < 1.0 {
|
||||
scale = 1.0
|
||||
}
|
||||
ru := math.Ceil(scale * filter.Support)
|
||||
|
||||
out := make([][]indexWeight, dstSize)
|
||||
tmp := make([]indexWeight, 0, dstSize*int(ru+2)*2)
|
||||
|
||||
for v := 0; v < dstSize; v++ {
|
||||
fu := (float64(v)+0.5)*du - 0.5
|
||||
|
||||
begin := int(math.Ceil(fu - ru))
|
||||
if begin < 0 {
|
||||
begin = 0
|
||||
}
|
||||
end := int(math.Floor(fu + ru))
|
||||
if end > srcSize-1 {
|
||||
end = srcSize - 1
|
||||
}
|
||||
|
||||
var sum float64
|
||||
for u := begin; u <= end; u++ {
|
||||
w := filter.Kernel((float64(u) - fu) / scale)
|
||||
if w != 0 {
|
||||
sum += w
|
||||
tmp = append(tmp, indexWeight{index: u, weight: w})
|
||||
}
|
||||
}
|
||||
if sum != 0 {
|
||||
for i := range tmp {
|
||||
tmp[i].weight /= sum
|
||||
}
|
||||
}
|
||||
|
||||
out[v] = tmp
|
||||
tmp = tmp[len(tmp):]
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
// Resize resizes the image to the specified width and height using the specified resampling
|
||||
// filter and returns the transformed image. If one of width or height is 0, the image aspect
|
||||
// ratio is preserved.
|
||||
//
|
||||
// Supported resample filters: NearestNeighbor, Box, Linear, Hermite, MitchellNetravali,
|
||||
// CatmullRom, BSpline, Gaussian, Lanczos, Hann, Hamming, Blackman, Bartlett, Welch, Cosine.
|
||||
//
|
||||
// Usage example:
|
||||
//
|
||||
// dstImage := imaging.Resize(srcImage, 800, 600, imaging.Lanczos)
|
||||
//
|
||||
func Resize(img image.Image, width, height int, filter ResampleFilter) *image.NRGBA {
|
||||
dstW, dstH := width, height
|
||||
if dstW < 0 || dstH < 0 {
|
||||
return &image.NRGBA{}
|
||||
}
|
||||
if dstW == 0 && dstH == 0 {
|
||||
return &image.NRGBA{}
|
||||
}
|
||||
|
||||
srcW := img.Bounds().Dx()
|
||||
srcH := img.Bounds().Dy()
|
||||
if srcW <= 0 || srcH <= 0 {
|
||||
return &image.NRGBA{}
|
||||
}
|
||||
|
||||
// If new width or height is 0 then preserve aspect ratio, minimum 1px.
|
||||
if dstW == 0 {
|
||||
tmpW := float64(dstH) * float64(srcW) / float64(srcH)
|
||||
dstW = int(math.Max(1.0, math.Floor(tmpW+0.5)))
|
||||
}
|
||||
if dstH == 0 {
|
||||
tmpH := float64(dstW) * float64(srcH) / float64(srcW)
|
||||
dstH = int(math.Max(1.0, math.Floor(tmpH+0.5)))
|
||||
}
|
||||
|
||||
if filter.Support <= 0 {
|
||||
// Nearest-neighbor special case.
|
||||
return resizeNearest(img, dstW, dstH)
|
||||
}
|
||||
|
||||
if srcW != dstW && srcH != dstH {
|
||||
return resizeVertical(resizeHorizontal(img, dstW, filter), dstH, filter)
|
||||
}
|
||||
if srcW != dstW {
|
||||
return resizeHorizontal(img, dstW, filter)
|
||||
}
|
||||
if srcH != dstH {
|
||||
return resizeVertical(img, dstH, filter)
|
||||
}
|
||||
return Clone(img)
|
||||
}
|
||||
|
||||
func resizeHorizontal(img image.Image, width int, filter ResampleFilter) *image.NRGBA {
|
||||
src := newScanner(img)
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, width, src.h))
|
||||
weights := precomputeWeights(width, src.w, filter)
|
||||
parallel(0, src.h, func(ys <-chan int) {
|
||||
scanLine := make([]uint8, src.w*4)
|
||||
for y := range ys {
|
||||
src.scan(0, y, src.w, y+1, scanLine)
|
||||
j0 := y * dst.Stride
|
||||
for x := range weights {
|
||||
var r, g, b, a float64
|
||||
for _, w := range weights[x] {
|
||||
i := w.index * 4
|
||||
s := scanLine[i : i+4 : i+4]
|
||||
aw := float64(s[3]) * w.weight
|
||||
r += float64(s[0]) * aw
|
||||
g += float64(s[1]) * aw
|
||||
b += float64(s[2]) * aw
|
||||
a += aw
|
||||
}
|
||||
if a != 0 {
|
||||
aInv := 1 / a
|
||||
j := j0 + x*4
|
||||
d := dst.Pix[j : j+4 : j+4]
|
||||
d[0] = clamp(r * aInv)
|
||||
d[1] = clamp(g * aInv)
|
||||
d[2] = clamp(b * aInv)
|
||||
d[3] = clamp(a)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
return dst
|
||||
}
|
||||
|
||||
func resizeVertical(img image.Image, height int, filter ResampleFilter) *image.NRGBA {
|
||||
src := newScanner(img)
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, src.w, height))
|
||||
weights := precomputeWeights(height, src.h, filter)
|
||||
parallel(0, src.w, func(xs <-chan int) {
|
||||
scanLine := make([]uint8, src.h*4)
|
||||
for x := range xs {
|
||||
src.scan(x, 0, x+1, src.h, scanLine)
|
||||
for y := range weights {
|
||||
var r, g, b, a float64
|
||||
for _, w := range weights[y] {
|
||||
i := w.index * 4
|
||||
s := scanLine[i : i+4 : i+4]
|
||||
aw := float64(s[3]) * w.weight
|
||||
r += float64(s[0]) * aw
|
||||
g += float64(s[1]) * aw
|
||||
b += float64(s[2]) * aw
|
||||
a += aw
|
||||
}
|
||||
if a != 0 {
|
||||
aInv := 1 / a
|
||||
j := y*dst.Stride + x*4
|
||||
d := dst.Pix[j : j+4 : j+4]
|
||||
d[0] = clamp(r * aInv)
|
||||
d[1] = clamp(g * aInv)
|
||||
d[2] = clamp(b * aInv)
|
||||
d[3] = clamp(a)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
return dst
|
||||
}
|
||||
|
||||
// resizeNearest is a fast nearest-neighbor resize, no filtering.
|
||||
func resizeNearest(img image.Image, width, height int) *image.NRGBA {
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, width, height))
|
||||
dx := float64(img.Bounds().Dx()) / float64(width)
|
||||
dy := float64(img.Bounds().Dy()) / float64(height)
|
||||
|
||||
if dx > 1 && dy > 1 {
|
||||
src := newScanner(img)
|
||||
parallel(0, height, func(ys <-chan int) {
|
||||
for y := range ys {
|
||||
srcY := int((float64(y) + 0.5) * dy)
|
||||
dstOff := y * dst.Stride
|
||||
for x := 0; x < width; x++ {
|
||||
srcX := int((float64(x) + 0.5) * dx)
|
||||
src.scan(srcX, srcY, srcX+1, srcY+1, dst.Pix[dstOff:dstOff+4])
|
||||
dstOff += 4
|
||||
}
|
||||
}
|
||||
})
|
||||
} else {
|
||||
src := toNRGBA(img)
|
||||
parallel(0, height, func(ys <-chan int) {
|
||||
for y := range ys {
|
||||
srcY := int((float64(y) + 0.5) * dy)
|
||||
srcOff0 := srcY * src.Stride
|
||||
dstOff := y * dst.Stride
|
||||
for x := 0; x < width; x++ {
|
||||
srcX := int((float64(x) + 0.5) * dx)
|
||||
srcOff := srcOff0 + srcX*4
|
||||
copy(dst.Pix[dstOff:dstOff+4], src.Pix[srcOff:srcOff+4])
|
||||
dstOff += 4
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return dst
|
||||
}
|
||||
|
||||
// Fit scales down the image using the specified resample filter to fit the specified
|
||||
// maximum width and height and returns the transformed image.
|
||||
//
|
||||
// Supported resample filters: NearestNeighbor, Box, Linear, Hermite, MitchellNetravali,
|
||||
// CatmullRom, BSpline, Gaussian, Lanczos, Hann, Hamming, Blackman, Bartlett, Welch, Cosine.
|
||||
//
|
||||
// Usage example:
|
||||
//
|
||||
// dstImage := imaging.Fit(srcImage, 800, 600, imaging.Lanczos)
|
||||
//
|
||||
func Fit(img image.Image, width, height int, filter ResampleFilter) *image.NRGBA {
|
||||
maxW, maxH := width, height
|
||||
|
||||
if maxW <= 0 || maxH <= 0 {
|
||||
return &image.NRGBA{}
|
||||
}
|
||||
|
||||
srcBounds := img.Bounds()
|
||||
srcW := srcBounds.Dx()
|
||||
srcH := srcBounds.Dy()
|
||||
|
||||
if srcW <= 0 || srcH <= 0 {
|
||||
return &image.NRGBA{}
|
||||
}
|
||||
|
||||
if srcW <= maxW && srcH <= maxH {
|
||||
return Clone(img)
|
||||
}
|
||||
|
||||
srcAspectRatio := float64(srcW) / float64(srcH)
|
||||
maxAspectRatio := float64(maxW) / float64(maxH)
|
||||
|
||||
var newW, newH int
|
||||
if srcAspectRatio > maxAspectRatio {
|
||||
newW = maxW
|
||||
newH = int(float64(newW) / srcAspectRatio)
|
||||
} else {
|
||||
newH = maxH
|
||||
newW = int(float64(newH) * srcAspectRatio)
|
||||
}
|
||||
|
||||
return Resize(img, newW, newH, filter)
|
||||
}
|
||||
|
||||
// Fill scales the image to the smallest possible size that will cover the specified dimensions,
|
||||
// crops the resized image to the specified dimensions using the given anchor point and returns
|
||||
// the transformed image.
|
||||
//
|
||||
// Supported resample filters: NearestNeighbor, Box, Linear, Hermite, MitchellNetravali,
|
||||
// CatmullRom, BSpline, Gaussian, Lanczos, Hann, Hamming, Blackman, Bartlett, Welch, Cosine.
|
||||
//
|
||||
// Usage example:
|
||||
//
|
||||
// dstImage := imaging.Fill(srcImage, 800, 600, imaging.Center, imaging.Lanczos)
|
||||
//
|
||||
func Fill(img image.Image, width, height int, anchor Anchor, filter ResampleFilter) *image.NRGBA {
|
||||
minW, minH := width, height
|
||||
|
||||
if minW <= 0 || minH <= 0 {
|
||||
return &image.NRGBA{}
|
||||
}
|
||||
|
||||
srcBounds := img.Bounds()
|
||||
srcW := srcBounds.Dx()
|
||||
srcH := srcBounds.Dy()
|
||||
|
||||
if srcW <= 0 || srcH <= 0 {
|
||||
return &image.NRGBA{}
|
||||
}
|
||||
|
||||
if srcW == minW && srcH == minH {
|
||||
return Clone(img)
|
||||
}
|
||||
|
||||
srcAspectRatio := float64(srcW) / float64(srcH)
|
||||
minAspectRatio := float64(minW) / float64(minH)
|
||||
|
||||
var tmp *image.NRGBA
|
||||
if srcAspectRatio < minAspectRatio {
|
||||
tmp = Resize(img, minW, 0, filter)
|
||||
} else {
|
||||
tmp = Resize(img, 0, minH, filter)
|
||||
}
|
||||
|
||||
return CropAnchor(tmp, minW, minH, anchor)
|
||||
}
|
||||
|
||||
// Thumbnail scales the image up or down using the specified resample filter, crops it
|
||||
// to the specified width and hight and returns the transformed image.
|
||||
//
|
||||
// Supported resample filters: NearestNeighbor, Box, Linear, Hermite, MitchellNetravali,
|
||||
// CatmullRom, BSpline, Gaussian, Lanczos, Hann, Hamming, Blackman, Bartlett, Welch, Cosine.
|
||||
//
|
||||
// Usage example:
|
||||
//
|
||||
// dstImage := imaging.Thumbnail(srcImage, 100, 100, imaging.Lanczos)
|
||||
//
|
||||
func Thumbnail(img image.Image, width, height int, filter ResampleFilter) *image.NRGBA {
|
||||
return Fill(img, width, height, Center, filter)
|
||||
}
|
||||
|
||||
// ResampleFilter is a resampling filter struct. It can be used to define custom filters.
|
||||
//
|
||||
// Supported resample filters: NearestNeighbor, Box, Linear, Hermite, MitchellNetravali,
|
||||
// CatmullRom, BSpline, Gaussian, Lanczos, Hann, Hamming, Blackman, Bartlett, Welch, Cosine.
|
||||
//
|
||||
// General filter recommendations:
|
||||
//
|
||||
// - Lanczos
|
||||
// High-quality resampling filter for photographic images yielding sharp results.
|
||||
// It's slower than cubic filters (see below).
|
||||
//
|
||||
// - CatmullRom
|
||||
// A sharp cubic filter. It's a good filter for both upscaling and downscaling if sharp results are needed.
|
||||
//
|
||||
// - MitchellNetravali
|
||||
// A high quality cubic filter that produces smoother results with less ringing artifacts than CatmullRom.
|
||||
//
|
||||
// - BSpline
|
||||
// A good filter if a very smooth output is needed.
|
||||
//
|
||||
// - Linear
|
||||
// Bilinear interpolation filter, produces reasonably good, smooth output.
|
||||
// It's faster than cubic filters.
|
||||
//
|
||||
// - Box
|
||||
// Simple and fast averaging filter appropriate for downscaling.
|
||||
// When upscaling it's similar to NearestNeighbor.
|
||||
//
|
||||
// - NearestNeighbor
|
||||
// Fastest resampling filter, no antialiasing.
|
||||
//
|
||||
type ResampleFilter struct {
|
||||
Support float64
|
||||
Kernel func(float64) float64
|
||||
}
|
||||
|
||||
// NearestNeighbor is a nearest-neighbor filter (no anti-aliasing).
|
||||
var NearestNeighbor ResampleFilter
|
||||
|
||||
// Box filter (averaging pixels).
|
||||
var Box ResampleFilter
|
||||
|
||||
// Linear filter.
|
||||
var Linear ResampleFilter
|
||||
|
||||
// Hermite cubic spline filter (BC-spline; B=0; C=0).
|
||||
var Hermite ResampleFilter
|
||||
|
||||
// MitchellNetravali is Mitchell-Netravali cubic filter (BC-spline; B=1/3; C=1/3).
|
||||
var MitchellNetravali ResampleFilter
|
||||
|
||||
// CatmullRom is a Catmull-Rom - sharp cubic filter (BC-spline; B=0; C=0.5).
|
||||
var CatmullRom ResampleFilter
|
||||
|
||||
// BSpline is a smooth cubic filter (BC-spline; B=1; C=0).
|
||||
var BSpline ResampleFilter
|
||||
|
||||
// Gaussian is a Gaussian blurring Filter.
|
||||
var Gaussian ResampleFilter
|
||||
|
||||
// Bartlett is a Bartlett-windowed sinc filter (3 lobes).
|
||||
var Bartlett ResampleFilter
|
||||
|
||||
// Lanczos filter (3 lobes).
|
||||
var Lanczos ResampleFilter
|
||||
|
||||
// Hann is a Hann-windowed sinc filter (3 lobes).
|
||||
var Hann ResampleFilter
|
||||
|
||||
// Hamming is a Hamming-windowed sinc filter (3 lobes).
|
||||
var Hamming ResampleFilter
|
||||
|
||||
// Blackman is a Blackman-windowed sinc filter (3 lobes).
|
||||
var Blackman ResampleFilter
|
||||
|
||||
// Welch is a Welch-windowed sinc filter (parabolic window, 3 lobes).
|
||||
var Welch ResampleFilter
|
||||
|
||||
// Cosine is a Cosine-windowed sinc filter (3 lobes).
|
||||
var Cosine ResampleFilter
|
||||
|
||||
func bcspline(x, b, c float64) float64 {
|
||||
var y float64
|
||||
x = math.Abs(x)
|
||||
if x < 1.0 {
|
||||
y = ((12-9*b-6*c)*x*x*x + (-18+12*b+6*c)*x*x + (6 - 2*b)) / 6
|
||||
} else if x < 2.0 {
|
||||
y = ((-b-6*c)*x*x*x + (6*b+30*c)*x*x + (-12*b-48*c)*x + (8*b + 24*c)) / 6
|
||||
}
|
||||
return y
|
||||
}
|
||||
|
||||
func sinc(x float64) float64 {
|
||||
if x == 0 {
|
||||
return 1
|
||||
}
|
||||
return math.Sin(math.Pi*x) / (math.Pi * x)
|
||||
}
|
||||
|
||||
func init() {
|
||||
NearestNeighbor = ResampleFilter{
|
||||
Support: 0.0, // special case - not applying the filter
|
||||
}
|
||||
|
||||
Box = ResampleFilter{
|
||||
Support: 0.5,
|
||||
Kernel: func(x float64) float64 {
|
||||
x = math.Abs(x)
|
||||
if x <= 0.5 {
|
||||
return 1.0
|
||||
}
|
||||
return 0
|
||||
},
|
||||
}
|
||||
|
||||
Linear = ResampleFilter{
|
||||
Support: 1.0,
|
||||
Kernel: func(x float64) float64 {
|
||||
x = math.Abs(x)
|
||||
if x < 1.0 {
|
||||
return 1.0 - x
|
||||
}
|
||||
return 0
|
||||
},
|
||||
}
|
||||
|
||||
Hermite = ResampleFilter{
|
||||
Support: 1.0,
|
||||
Kernel: func(x float64) float64 {
|
||||
x = math.Abs(x)
|
||||
if x < 1.0 {
|
||||
return bcspline(x, 0.0, 0.0)
|
||||
}
|
||||
return 0
|
||||
},
|
||||
}
|
||||
|
||||
MitchellNetravali = ResampleFilter{
|
||||
Support: 2.0,
|
||||
Kernel: func(x float64) float64 {
|
||||
x = math.Abs(x)
|
||||
if x < 2.0 {
|
||||
return bcspline(x, 1.0/3.0, 1.0/3.0)
|
||||
}
|
||||
return 0
|
||||
},
|
||||
}
|
||||
|
||||
CatmullRom = ResampleFilter{
|
||||
Support: 2.0,
|
||||
Kernel: func(x float64) float64 {
|
||||
x = math.Abs(x)
|
||||
if x < 2.0 {
|
||||
return bcspline(x, 0.0, 0.5)
|
||||
}
|
||||
return 0
|
||||
},
|
||||
}
|
||||
|
||||
BSpline = ResampleFilter{
|
||||
Support: 2.0,
|
||||
Kernel: func(x float64) float64 {
|
||||
x = math.Abs(x)
|
||||
if x < 2.0 {
|
||||
return bcspline(x, 1.0, 0.0)
|
||||
}
|
||||
return 0
|
||||
},
|
||||
}
|
||||
|
||||
Gaussian = ResampleFilter{
|
||||
Support: 2.0,
|
||||
Kernel: func(x float64) float64 {
|
||||
x = math.Abs(x)
|
||||
if x < 2.0 {
|
||||
return math.Exp(-2 * x * x)
|
||||
}
|
||||
return 0
|
||||
},
|
||||
}
|
||||
|
||||
Bartlett = ResampleFilter{
|
||||
Support: 3.0,
|
||||
Kernel: func(x float64) float64 {
|
||||
x = math.Abs(x)
|
||||
if x < 3.0 {
|
||||
return sinc(x) * (3.0 - x) / 3.0
|
||||
}
|
||||
return 0
|
||||
},
|
||||
}
|
||||
|
||||
Lanczos = ResampleFilter{
|
||||
Support: 3.0,
|
||||
Kernel: func(x float64) float64 {
|
||||
x = math.Abs(x)
|
||||
if x < 3.0 {
|
||||
return sinc(x) * sinc(x/3.0)
|
||||
}
|
||||
return 0
|
||||
},
|
||||
}
|
||||
|
||||
Hann = ResampleFilter{
|
||||
Support: 3.0,
|
||||
Kernel: func(x float64) float64 {
|
||||
x = math.Abs(x)
|
||||
if x < 3.0 {
|
||||
return sinc(x) * (0.5 + 0.5*math.Cos(math.Pi*x/3.0))
|
||||
}
|
||||
return 0
|
||||
},
|
||||
}
|
||||
|
||||
Hamming = ResampleFilter{
|
||||
Support: 3.0,
|
||||
Kernel: func(x float64) float64 {
|
||||
x = math.Abs(x)
|
||||
if x < 3.0 {
|
||||
return sinc(x) * (0.54 + 0.46*math.Cos(math.Pi*x/3.0))
|
||||
}
|
||||
return 0
|
||||
},
|
||||
}
|
||||
|
||||
Blackman = ResampleFilter{
|
||||
Support: 3.0,
|
||||
Kernel: func(x float64) float64 {
|
||||
x = math.Abs(x)
|
||||
if x < 3.0 {
|
||||
return sinc(x) * (0.42 - 0.5*math.Cos(math.Pi*x/3.0+math.Pi) + 0.08*math.Cos(2.0*math.Pi*x/3.0))
|
||||
}
|
||||
return 0
|
||||
},
|
||||
}
|
||||
|
||||
Welch = ResampleFilter{
|
||||
Support: 3.0,
|
||||
Kernel: func(x float64) float64 {
|
||||
x = math.Abs(x)
|
||||
if x < 3.0 {
|
||||
return sinc(x) * (1.0 - (x * x / 9.0))
|
||||
}
|
||||
return 0
|
||||
},
|
||||
}
|
||||
|
||||
Cosine = ResampleFilter{
|
||||
Support: 3.0,
|
||||
Kernel: func(x float64) float64 {
|
||||
x = math.Abs(x)
|
||||
if x < 3.0 {
|
||||
return sinc(x) * math.Cos((math.Pi/2.0)*(x/3.0))
|
||||
}
|
||||
return 0
|
||||
},
|
||||
}
|
||||
}
|
|
@ -0,0 +1,285 @@
|
|||
package imaging
|
||||
|
||||
import (
|
||||
"image"
|
||||
"image/color"
|
||||
)
|
||||
|
||||
type scanner struct {
|
||||
image image.Image
|
||||
w, h int
|
||||
palette []color.NRGBA
|
||||
}
|
||||
|
||||
func newScanner(img image.Image) *scanner {
|
||||
s := &scanner{
|
||||
image: img,
|
||||
w: img.Bounds().Dx(),
|
||||
h: img.Bounds().Dy(),
|
||||
}
|
||||
if img, ok := img.(*image.Paletted); ok {
|
||||
s.palette = make([]color.NRGBA, len(img.Palette))
|
||||
for i := 0; i < len(img.Palette); i++ {
|
||||
s.palette[i] = color.NRGBAModel.Convert(img.Palette[i]).(color.NRGBA)
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// scan scans the given rectangular region of the image into dst.
|
||||
func (s *scanner) scan(x1, y1, x2, y2 int, dst []uint8) {
|
||||
switch img := s.image.(type) {
|
||||
case *image.NRGBA:
|
||||
size := (x2 - x1) * 4
|
||||
j := 0
|
||||
i := y1*img.Stride + x1*4
|
||||
if size == 4 {
|
||||
for y := y1; y < y2; y++ {
|
||||
d := dst[j : j+4 : j+4]
|
||||
s := img.Pix[i : i+4 : i+4]
|
||||
d[0] = s[0]
|
||||
d[1] = s[1]
|
||||
d[2] = s[2]
|
||||
d[3] = s[3]
|
||||
j += size
|
||||
i += img.Stride
|
||||
}
|
||||
} else {
|
||||
for y := y1; y < y2; y++ {
|
||||
copy(dst[j:j+size], img.Pix[i:i+size])
|
||||
j += size
|
||||
i += img.Stride
|
||||
}
|
||||
}
|
||||
|
||||
case *image.NRGBA64:
|
||||
j := 0
|
||||
for y := y1; y < y2; y++ {
|
||||
i := y*img.Stride + x1*8
|
||||
for x := x1; x < x2; x++ {
|
||||
s := img.Pix[i : i+8 : i+8]
|
||||
d := dst[j : j+4 : j+4]
|
||||
d[0] = s[0]
|
||||
d[1] = s[2]
|
||||
d[2] = s[4]
|
||||
d[3] = s[6]
|
||||
j += 4
|
||||
i += 8
|
||||
}
|
||||
}
|
||||
|
||||
case *image.RGBA:
|
||||
j := 0
|
||||
for y := y1; y < y2; y++ {
|
||||
i := y*img.Stride + x1*4
|
||||
for x := x1; x < x2; x++ {
|
||||
d := dst[j : j+4 : j+4]
|
||||
a := img.Pix[i+3]
|
||||
switch a {
|
||||
case 0:
|
||||
d[0] = 0
|
||||
d[1] = 0
|
||||
d[2] = 0
|
||||
d[3] = a
|
||||
case 0xff:
|
||||
s := img.Pix[i : i+4 : i+4]
|
||||
d[0] = s[0]
|
||||
d[1] = s[1]
|
||||
d[2] = s[2]
|
||||
d[3] = a
|
||||
default:
|
||||
s := img.Pix[i : i+4 : i+4]
|
||||
r16 := uint16(s[0])
|
||||
g16 := uint16(s[1])
|
||||
b16 := uint16(s[2])
|
||||
a16 := uint16(a)
|
||||
d[0] = uint8(r16 * 0xff / a16)
|
||||
d[1] = uint8(g16 * 0xff / a16)
|
||||
d[2] = uint8(b16 * 0xff / a16)
|
||||
d[3] = a
|
||||
}
|
||||
j += 4
|
||||
i += 4
|
||||
}
|
||||
}
|
||||
|
||||
case *image.RGBA64:
|
||||
j := 0
|
||||
for y := y1; y < y2; y++ {
|
||||
i := y*img.Stride + x1*8
|
||||
for x := x1; x < x2; x++ {
|
||||
s := img.Pix[i : i+8 : i+8]
|
||||
d := dst[j : j+4 : j+4]
|
||||
a := s[6]
|
||||
switch a {
|
||||
case 0:
|
||||
d[0] = 0
|
||||
d[1] = 0
|
||||
d[2] = 0
|
||||
case 0xff:
|
||||
d[0] = s[0]
|
||||
d[1] = s[2]
|
||||
d[2] = s[4]
|
||||
default:
|
||||
r32 := uint32(s[0])<<8 | uint32(s[1])
|
||||
g32 := uint32(s[2])<<8 | uint32(s[3])
|
||||
b32 := uint32(s[4])<<8 | uint32(s[5])
|
||||
a32 := uint32(s[6])<<8 | uint32(s[7])
|
||||
d[0] = uint8((r32 * 0xffff / a32) >> 8)
|
||||
d[1] = uint8((g32 * 0xffff / a32) >> 8)
|
||||
d[2] = uint8((b32 * 0xffff / a32) >> 8)
|
||||
}
|
||||
d[3] = a
|
||||
j += 4
|
||||
i += 8
|
||||
}
|
||||
}
|
||||
|
||||
case *image.Gray:
|
||||
j := 0
|
||||
for y := y1; y < y2; y++ {
|
||||
i := y*img.Stride + x1
|
||||
for x := x1; x < x2; x++ {
|
||||
c := img.Pix[i]
|
||||
d := dst[j : j+4 : j+4]
|
||||
d[0] = c
|
||||
d[1] = c
|
||||
d[2] = c
|
||||
d[3] = 0xff
|
||||
j += 4
|
||||
i++
|
||||
}
|
||||
}
|
||||
|
||||
case *image.Gray16:
|
||||
j := 0
|
||||
for y := y1; y < y2; y++ {
|
||||
i := y*img.Stride + x1*2
|
||||
for x := x1; x < x2; x++ {
|
||||
c := img.Pix[i]
|
||||
d := dst[j : j+4 : j+4]
|
||||
d[0] = c
|
||||
d[1] = c
|
||||
d[2] = c
|
||||
d[3] = 0xff
|
||||
j += 4
|
||||
i += 2
|
||||
}
|
||||
}
|
||||
|
||||
case *image.YCbCr:
|
||||
j := 0
|
||||
x1 += img.Rect.Min.X
|
||||
x2 += img.Rect.Min.X
|
||||
y1 += img.Rect.Min.Y
|
||||
y2 += img.Rect.Min.Y
|
||||
|
||||
hy := img.Rect.Min.Y / 2
|
||||
hx := img.Rect.Min.X / 2
|
||||
for y := y1; y < y2; y++ {
|
||||
iy := (y-img.Rect.Min.Y)*img.YStride + (x1 - img.Rect.Min.X)
|
||||
|
||||
var yBase int
|
||||
switch img.SubsampleRatio {
|
||||
case image.YCbCrSubsampleRatio444, image.YCbCrSubsampleRatio422:
|
||||
yBase = (y - img.Rect.Min.Y) * img.CStride
|
||||
case image.YCbCrSubsampleRatio420, image.YCbCrSubsampleRatio440:
|
||||
yBase = (y/2 - hy) * img.CStride
|
||||
}
|
||||
|
||||
for x := x1; x < x2; x++ {
|
||||
var ic int
|
||||
switch img.SubsampleRatio {
|
||||
case image.YCbCrSubsampleRatio444, image.YCbCrSubsampleRatio440:
|
||||
ic = yBase + (x - img.Rect.Min.X)
|
||||
case image.YCbCrSubsampleRatio422, image.YCbCrSubsampleRatio420:
|
||||
ic = yBase + (x/2 - hx)
|
||||
default:
|
||||
ic = img.COffset(x, y)
|
||||
}
|
||||
|
||||
yy1 := int32(img.Y[iy]) * 0x10101
|
||||
cb1 := int32(img.Cb[ic]) - 128
|
||||
cr1 := int32(img.Cr[ic]) - 128
|
||||
|
||||
r := yy1 + 91881*cr1
|
||||
if uint32(r)&0xff000000 == 0 {
|
||||
r >>= 16
|
||||
} else {
|
||||
r = ^(r >> 31)
|
||||
}
|
||||
|
||||
g := yy1 - 22554*cb1 - 46802*cr1
|
||||
if uint32(g)&0xff000000 == 0 {
|
||||
g >>= 16
|
||||
} else {
|
||||
g = ^(g >> 31)
|
||||
}
|
||||
|
||||
b := yy1 + 116130*cb1
|
||||
if uint32(b)&0xff000000 == 0 {
|
||||
b >>= 16
|
||||
} else {
|
||||
b = ^(b >> 31)
|
||||
}
|
||||
|
||||
d := dst[j : j+4 : j+4]
|
||||
d[0] = uint8(r)
|
||||
d[1] = uint8(g)
|
||||
d[2] = uint8(b)
|
||||
d[3] = 0xff
|
||||
|
||||
iy++
|
||||
j += 4
|
||||
}
|
||||
}
|
||||
|
||||
case *image.Paletted:
|
||||
j := 0
|
||||
for y := y1; y < y2; y++ {
|
||||
i := y*img.Stride + x1
|
||||
for x := x1; x < x2; x++ {
|
||||
c := s.palette[img.Pix[i]]
|
||||
d := dst[j : j+4 : j+4]
|
||||
d[0] = c.R
|
||||
d[1] = c.G
|
||||
d[2] = c.B
|
||||
d[3] = c.A
|
||||
j += 4
|
||||
i++
|
||||
}
|
||||
}
|
||||
|
||||
default:
|
||||
j := 0
|
||||
b := s.image.Bounds()
|
||||
x1 += b.Min.X
|
||||
x2 += b.Min.X
|
||||
y1 += b.Min.Y
|
||||
y2 += b.Min.Y
|
||||
for y := y1; y < y2; y++ {
|
||||
for x := x1; x < x2; x++ {
|
||||
r16, g16, b16, a16 := s.image.At(x, y).RGBA()
|
||||
d := dst[j : j+4 : j+4]
|
||||
switch a16 {
|
||||
case 0xffff:
|
||||
d[0] = uint8(r16 >> 8)
|
||||
d[1] = uint8(g16 >> 8)
|
||||
d[2] = uint8(b16 >> 8)
|
||||
d[3] = 0xff
|
||||
case 0:
|
||||
d[0] = 0
|
||||
d[1] = 0
|
||||
d[2] = 0
|
||||
d[3] = 0
|
||||
default:
|
||||
d[0] = uint8(((r16 * 0xffff) / a16) >> 8)
|
||||
d[1] = uint8(((g16 * 0xffff) / a16) >> 8)
|
||||
d[2] = uint8(((b16 * 0xffff) / a16) >> 8)
|
||||
d[3] = uint8(a16 >> 8)
|
||||
}
|
||||
j += 4
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,247 @@
|
|||
package imaging
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"image"
|
||||
"image/color"
|
||||
"math"
|
||||
)
|
||||
|
||||
// New creates a new image with the specified width and height, and fills it with the specified color.
|
||||
func New(width, height int, fillColor color.Color) *image.NRGBA {
|
||||
if width <= 0 || height <= 0 {
|
||||
return &image.NRGBA{}
|
||||
}
|
||||
|
||||
c := color.NRGBAModel.Convert(fillColor).(color.NRGBA)
|
||||
if (c == color.NRGBA{0, 0, 0, 0}) {
|
||||
return image.NewNRGBA(image.Rect(0, 0, width, height))
|
||||
}
|
||||
|
||||
return &image.NRGBA{
|
||||
Pix: bytes.Repeat([]byte{c.R, c.G, c.B, c.A}, width*height),
|
||||
Stride: 4 * width,
|
||||
Rect: image.Rect(0, 0, width, height),
|
||||
}
|
||||
}
|
||||
|
||||
// Clone returns a copy of the given image.
|
||||
func Clone(img image.Image) *image.NRGBA {
|
||||
src := newScanner(img)
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
|
||||
size := src.w * 4
|
||||
parallel(0, src.h, func(ys <-chan int) {
|
||||
for y := range ys {
|
||||
i := y * dst.Stride
|
||||
src.scan(0, y, src.w, y+1, dst.Pix[i:i+size])
|
||||
}
|
||||
})
|
||||
return dst
|
||||
}
|
||||
|
||||
// Anchor is the anchor point for image alignment.
|
||||
type Anchor int
|
||||
|
||||
// Anchor point positions.
|
||||
const (
|
||||
Center Anchor = iota
|
||||
TopLeft
|
||||
Top
|
||||
TopRight
|
||||
Left
|
||||
Right
|
||||
BottomLeft
|
||||
Bottom
|
||||
BottomRight
|
||||
)
|
||||
|
||||
func anchorPt(b image.Rectangle, w, h int, anchor Anchor) image.Point {
|
||||
var x, y int
|
||||
switch anchor {
|
||||
case TopLeft:
|
||||
x = b.Min.X
|
||||
y = b.Min.Y
|
||||
case Top:
|
||||
x = b.Min.X + (b.Dx()-w)/2
|
||||
y = b.Min.Y
|
||||
case TopRight:
|
||||
x = b.Max.X - w
|
||||
y = b.Min.Y
|
||||
case Left:
|
||||
x = b.Min.X
|
||||
y = b.Min.Y + (b.Dy()-h)/2
|
||||
case Right:
|
||||
x = b.Max.X - w
|
||||
y = b.Min.Y + (b.Dy()-h)/2
|
||||
case BottomLeft:
|
||||
x = b.Min.X
|
||||
y = b.Max.Y - h
|
||||
case Bottom:
|
||||
x = b.Min.X + (b.Dx()-w)/2
|
||||
y = b.Max.Y - h
|
||||
case BottomRight:
|
||||
x = b.Max.X - w
|
||||
y = b.Max.Y - h
|
||||
default:
|
||||
x = b.Min.X + (b.Dx()-w)/2
|
||||
y = b.Min.Y + (b.Dy()-h)/2
|
||||
}
|
||||
return image.Pt(x, y)
|
||||
}
|
||||
|
||||
// Crop cuts out a rectangular region with the specified bounds
|
||||
// from the image and returns the cropped image.
|
||||
func Crop(img image.Image, rect image.Rectangle) *image.NRGBA {
|
||||
r := rect.Intersect(img.Bounds()).Sub(img.Bounds().Min)
|
||||
if r.Empty() {
|
||||
return &image.NRGBA{}
|
||||
}
|
||||
src := newScanner(img)
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, r.Dx(), r.Dy()))
|
||||
rowSize := r.Dx() * 4
|
||||
parallel(r.Min.Y, r.Max.Y, func(ys <-chan int) {
|
||||
for y := range ys {
|
||||
i := (y - r.Min.Y) * dst.Stride
|
||||
src.scan(r.Min.X, y, r.Max.X, y+1, dst.Pix[i:i+rowSize])
|
||||
}
|
||||
})
|
||||
return dst
|
||||
}
|
||||
|
||||
// CropAnchor cuts out a rectangular region with the specified size
|
||||
// from the image using the specified anchor point and returns the cropped image.
|
||||
func CropAnchor(img image.Image, width, height int, anchor Anchor) *image.NRGBA {
|
||||
srcBounds := img.Bounds()
|
||||
pt := anchorPt(srcBounds, width, height, anchor)
|
||||
r := image.Rect(0, 0, width, height).Add(pt)
|
||||
b := srcBounds.Intersect(r)
|
||||
return Crop(img, b)
|
||||
}
|
||||
|
||||
// CropCenter cuts out a rectangular region with the specified size
|
||||
// from the center of the image and returns the cropped image.
|
||||
func CropCenter(img image.Image, width, height int) *image.NRGBA {
|
||||
return CropAnchor(img, width, height, Center)
|
||||
}
|
||||
|
||||
// Paste pastes the img image to the background image at the specified position and returns the combined image.
|
||||
func Paste(background, img image.Image, pos image.Point) *image.NRGBA {
|
||||
dst := Clone(background)
|
||||
pos = pos.Sub(background.Bounds().Min)
|
||||
pasteRect := image.Rectangle{Min: pos, Max: pos.Add(img.Bounds().Size())}
|
||||
interRect := pasteRect.Intersect(dst.Bounds())
|
||||
if interRect.Empty() {
|
||||
return dst
|
||||
}
|
||||
src := newScanner(img)
|
||||
parallel(interRect.Min.Y, interRect.Max.Y, func(ys <-chan int) {
|
||||
for y := range ys {
|
||||
x1 := interRect.Min.X - pasteRect.Min.X
|
||||
x2 := interRect.Max.X - pasteRect.Min.X
|
||||
y1 := y - pasteRect.Min.Y
|
||||
y2 := y1 + 1
|
||||
i1 := y*dst.Stride + interRect.Min.X*4
|
||||
i2 := i1 + interRect.Dx()*4
|
||||
src.scan(x1, y1, x2, y2, dst.Pix[i1:i2])
|
||||
}
|
||||
})
|
||||
return dst
|
||||
}
|
||||
|
||||
// PasteCenter pastes the img image to the center of the background image and returns the combined image.
|
||||
func PasteCenter(background, img image.Image) *image.NRGBA {
|
||||
bgBounds := background.Bounds()
|
||||
bgW := bgBounds.Dx()
|
||||
bgH := bgBounds.Dy()
|
||||
bgMinX := bgBounds.Min.X
|
||||
bgMinY := bgBounds.Min.Y
|
||||
|
||||
centerX := bgMinX + bgW/2
|
||||
centerY := bgMinY + bgH/2
|
||||
|
||||
x0 := centerX - img.Bounds().Dx()/2
|
||||
y0 := centerY - img.Bounds().Dy()/2
|
||||
|
||||
return Paste(background, img, image.Pt(x0, y0))
|
||||
}
|
||||
|
||||
// Overlay draws the img image over the background image at given position
|
||||
// and returns the combined image. Opacity parameter is the opacity of the img
|
||||
// image layer, used to compose the images, it must be from 0.0 to 1.0.
|
||||
//
|
||||
// Usage examples:
|
||||
//
|
||||
// // Draw spriteImage over backgroundImage at the given position (x=50, y=50).
|
||||
// dstImage := imaging.Overlay(backgroundImage, spriteImage, image.Pt(50, 50), 1.0)
|
||||
//
|
||||
// // Blend two opaque images of the same size.
|
||||
// dstImage := imaging.Overlay(imageOne, imageTwo, image.Pt(0, 0), 0.5)
|
||||
//
|
||||
func Overlay(background, img image.Image, pos image.Point, opacity float64) *image.NRGBA {
|
||||
opacity = math.Min(math.Max(opacity, 0.0), 1.0) // Ensure 0.0 <= opacity <= 1.0.
|
||||
dst := Clone(background)
|
||||
pos = pos.Sub(background.Bounds().Min)
|
||||
pasteRect := image.Rectangle{Min: pos, Max: pos.Add(img.Bounds().Size())}
|
||||
interRect := pasteRect.Intersect(dst.Bounds())
|
||||
if interRect.Empty() {
|
||||
return dst
|
||||
}
|
||||
src := newScanner(img)
|
||||
parallel(interRect.Min.Y, interRect.Max.Y, func(ys <-chan int) {
|
||||
scanLine := make([]uint8, interRect.Dx()*4)
|
||||
for y := range ys {
|
||||
x1 := interRect.Min.X - pasteRect.Min.X
|
||||
x2 := interRect.Max.X - pasteRect.Min.X
|
||||
y1 := y - pasteRect.Min.Y
|
||||
y2 := y1 + 1
|
||||
src.scan(x1, y1, x2, y2, scanLine)
|
||||
i := y*dst.Stride + interRect.Min.X*4
|
||||
j := 0
|
||||
for x := interRect.Min.X; x < interRect.Max.X; x++ {
|
||||
r1 := float64(dst.Pix[i+0])
|
||||
g1 := float64(dst.Pix[i+1])
|
||||
b1 := float64(dst.Pix[i+2])
|
||||
a1 := float64(dst.Pix[i+3])
|
||||
|
||||
r2 := float64(scanLine[j+0])
|
||||
g2 := float64(scanLine[j+1])
|
||||
b2 := float64(scanLine[j+2])
|
||||
a2 := float64(scanLine[j+3])
|
||||
|
||||
coef2 := opacity * a2 / 255
|
||||
coef1 := (1 - coef2) * a1 / 255
|
||||
coefSum := coef1 + coef2
|
||||
coef1 /= coefSum
|
||||
coef2 /= coefSum
|
||||
|
||||
dst.Pix[i+0] = uint8(r1*coef1 + r2*coef2)
|
||||
dst.Pix[i+1] = uint8(g1*coef1 + g2*coef2)
|
||||
dst.Pix[i+2] = uint8(b1*coef1 + b2*coef2)
|
||||
dst.Pix[i+3] = uint8(math.Min(a1+a2*opacity*(255-a1)/255, 255))
|
||||
|
||||
i += 4
|
||||
j += 4
|
||||
}
|
||||
}
|
||||
})
|
||||
return dst
|
||||
}
|
||||
|
||||
// OverlayCenter overlays the img image to the center of the background image and
|
||||
// returns the combined image. Opacity parameter is the opacity of the img
|
||||
// image layer, used to compose the images, it must be from 0.0 to 1.0.
|
||||
func OverlayCenter(background, img image.Image, opacity float64) *image.NRGBA {
|
||||
bgBounds := background.Bounds()
|
||||
bgW := bgBounds.Dx()
|
||||
bgH := bgBounds.Dy()
|
||||
bgMinX := bgBounds.Min.X
|
||||
bgMinY := bgBounds.Min.Y
|
||||
|
||||
centerX := bgMinX + bgW/2
|
||||
centerY := bgMinY + bgH/2
|
||||
|
||||
x0 := centerX - img.Bounds().Dx()/2
|
||||
y0 := centerY - img.Bounds().Dy()/2
|
||||
|
||||
return Overlay(background, img, image.Point{x0, y0}, opacity)
|
||||
}
|
|
@ -0,0 +1,271 @@
|
|||
package imaging
|
||||
|
||||
import (
|
||||
"image"
|
||||
"image/color"
|
||||
"math"
|
||||
)
|
||||
|
||||
// FlipH flips the image horizontally (from left to right) and returns the transformed image.
|
||||
func FlipH(img image.Image) *image.NRGBA {
|
||||
src := newScanner(img)
|
||||
dstW := src.w
|
||||
dstH := src.h
|
||||
rowSize := dstW * 4
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, dstW, dstH))
|
||||
parallel(0, dstH, func(ys <-chan int) {
|
||||
for dstY := range ys {
|
||||
i := dstY * dst.Stride
|
||||
srcY := dstY
|
||||
src.scan(0, srcY, src.w, srcY+1, dst.Pix[i:i+rowSize])
|
||||
reverse(dst.Pix[i : i+rowSize])
|
||||
}
|
||||
})
|
||||
return dst
|
||||
}
|
||||
|
||||
// FlipV flips the image vertically (from top to bottom) and returns the transformed image.
|
||||
func FlipV(img image.Image) *image.NRGBA {
|
||||
src := newScanner(img)
|
||||
dstW := src.w
|
||||
dstH := src.h
|
||||
rowSize := dstW * 4
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, dstW, dstH))
|
||||
parallel(0, dstH, func(ys <-chan int) {
|
||||
for dstY := range ys {
|
||||
i := dstY * dst.Stride
|
||||
srcY := dstH - dstY - 1
|
||||
src.scan(0, srcY, src.w, srcY+1, dst.Pix[i:i+rowSize])
|
||||
}
|
||||
})
|
||||
return dst
|
||||
}
|
||||
|
||||
// Transpose flips the image horizontally and rotates 90 degrees counter-clockwise.
|
||||
func Transpose(img image.Image) *image.NRGBA {
|
||||
src := newScanner(img)
|
||||
dstW := src.h
|
||||
dstH := src.w
|
||||
rowSize := dstW * 4
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, dstW, dstH))
|
||||
parallel(0, dstH, func(ys <-chan int) {
|
||||
for dstY := range ys {
|
||||
i := dstY * dst.Stride
|
||||
srcX := dstY
|
||||
src.scan(srcX, 0, srcX+1, src.h, dst.Pix[i:i+rowSize])
|
||||
}
|
||||
})
|
||||
return dst
|
||||
}
|
||||
|
||||
// Transverse flips the image vertically and rotates 90 degrees counter-clockwise.
|
||||
func Transverse(img image.Image) *image.NRGBA {
|
||||
src := newScanner(img)
|
||||
dstW := src.h
|
||||
dstH := src.w
|
||||
rowSize := dstW * 4
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, dstW, dstH))
|
||||
parallel(0, dstH, func(ys <-chan int) {
|
||||
for dstY := range ys {
|
||||
i := dstY * dst.Stride
|
||||
srcX := dstH - dstY - 1
|
||||
src.scan(srcX, 0, srcX+1, src.h, dst.Pix[i:i+rowSize])
|
||||
reverse(dst.Pix[i : i+rowSize])
|
||||
}
|
||||
})
|
||||
return dst
|
||||
}
|
||||
|
||||
// Rotate90 rotates the image 90 degrees counter-clockwise and returns the transformed image.
|
||||
func Rotate90(img image.Image) *image.NRGBA {
|
||||
src := newScanner(img)
|
||||
dstW := src.h
|
||||
dstH := src.w
|
||||
rowSize := dstW * 4
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, dstW, dstH))
|
||||
parallel(0, dstH, func(ys <-chan int) {
|
||||
for dstY := range ys {
|
||||
i := dstY * dst.Stride
|
||||
srcX := dstH - dstY - 1
|
||||
src.scan(srcX, 0, srcX+1, src.h, dst.Pix[i:i+rowSize])
|
||||
}
|
||||
})
|
||||
return dst
|
||||
}
|
||||
|
||||
// Rotate180 rotates the image 180 degrees counter-clockwise and returns the transformed image.
|
||||
func Rotate180(img image.Image) *image.NRGBA {
|
||||
src := newScanner(img)
|
||||
dstW := src.w
|
||||
dstH := src.h
|
||||
rowSize := dstW * 4
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, dstW, dstH))
|
||||
parallel(0, dstH, func(ys <-chan int) {
|
||||
for dstY := range ys {
|
||||
i := dstY * dst.Stride
|
||||
srcY := dstH - dstY - 1
|
||||
src.scan(0, srcY, src.w, srcY+1, dst.Pix[i:i+rowSize])
|
||||
reverse(dst.Pix[i : i+rowSize])
|
||||
}
|
||||
})
|
||||
return dst
|
||||
}
|
||||
|
||||
// Rotate270 rotates the image 270 degrees counter-clockwise and returns the transformed image.
|
||||
func Rotate270(img image.Image) *image.NRGBA {
|
||||
src := newScanner(img)
|
||||
dstW := src.h
|
||||
dstH := src.w
|
||||
rowSize := dstW * 4
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, dstW, dstH))
|
||||
parallel(0, dstH, func(ys <-chan int) {
|
||||
for dstY := range ys {
|
||||
i := dstY * dst.Stride
|
||||
srcX := dstY
|
||||
src.scan(srcX, 0, srcX+1, src.h, dst.Pix[i:i+rowSize])
|
||||
reverse(dst.Pix[i : i+rowSize])
|
||||
}
|
||||
})
|
||||
return dst
|
||||
}
|
||||
|
||||
// Rotate rotates an image by the given angle counter-clockwise .
|
||||
// The angle parameter is the rotation angle in degrees.
|
||||
// The bgColor parameter specifies the color of the uncovered zone after the rotation.
|
||||
func Rotate(img image.Image, angle float64, bgColor color.Color) *image.NRGBA {
|
||||
angle = angle - math.Floor(angle/360)*360
|
||||
|
||||
switch angle {
|
||||
case 0:
|
||||
return Clone(img)
|
||||
case 90:
|
||||
return Rotate90(img)
|
||||
case 180:
|
||||
return Rotate180(img)
|
||||
case 270:
|
||||
return Rotate270(img)
|
||||
}
|
||||
|
||||
src := toNRGBA(img)
|
||||
srcW := src.Bounds().Max.X
|
||||
srcH := src.Bounds().Max.Y
|
||||
dstW, dstH := rotatedSize(srcW, srcH, angle)
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, dstW, dstH))
|
||||
|
||||
if dstW <= 0 || dstH <= 0 {
|
||||
return dst
|
||||
}
|
||||
|
||||
srcXOff := float64(srcW)/2 - 0.5
|
||||
srcYOff := float64(srcH)/2 - 0.5
|
||||
dstXOff := float64(dstW)/2 - 0.5
|
||||
dstYOff := float64(dstH)/2 - 0.5
|
||||
|
||||
bgColorNRGBA := color.NRGBAModel.Convert(bgColor).(color.NRGBA)
|
||||
sin, cos := math.Sincos(math.Pi * angle / 180)
|
||||
|
||||
parallel(0, dstH, func(ys <-chan int) {
|
||||
for dstY := range ys {
|
||||
for dstX := 0; dstX < dstW; dstX++ {
|
||||
xf, yf := rotatePoint(float64(dstX)-dstXOff, float64(dstY)-dstYOff, sin, cos)
|
||||
xf, yf = xf+srcXOff, yf+srcYOff
|
||||
interpolatePoint(dst, dstX, dstY, src, xf, yf, bgColorNRGBA)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return dst
|
||||
}
|
||||
|
||||
func rotatePoint(x, y, sin, cos float64) (float64, float64) {
|
||||
return x*cos - y*sin, x*sin + y*cos
|
||||
}
|
||||
|
||||
func rotatedSize(w, h int, angle float64) (int, int) {
|
||||
if w <= 0 || h <= 0 {
|
||||
return 0, 0
|
||||
}
|
||||
|
||||
sin, cos := math.Sincos(math.Pi * angle / 180)
|
||||
x1, y1 := rotatePoint(float64(w-1), 0, sin, cos)
|
||||
x2, y2 := rotatePoint(float64(w-1), float64(h-1), sin, cos)
|
||||
x3, y3 := rotatePoint(0, float64(h-1), sin, cos)
|
||||
|
||||
minx := math.Min(x1, math.Min(x2, math.Min(x3, 0)))
|
||||
maxx := math.Max(x1, math.Max(x2, math.Max(x3, 0)))
|
||||
miny := math.Min(y1, math.Min(y2, math.Min(y3, 0)))
|
||||
maxy := math.Max(y1, math.Max(y2, math.Max(y3, 0)))
|
||||
|
||||
neww := maxx - minx + 1
|
||||
if neww-math.Floor(neww) > 0.1 {
|
||||
neww++
|
||||
}
|
||||
newh := maxy - miny + 1
|
||||
if newh-math.Floor(newh) > 0.1 {
|
||||
newh++
|
||||
}
|
||||
|
||||
return int(neww), int(newh)
|
||||
}
|
||||
|
||||
func interpolatePoint(dst *image.NRGBA, dstX, dstY int, src *image.NRGBA, xf, yf float64, bgColor color.NRGBA) {
|
||||
dstIndex := dstY*dst.Stride + dstX*4
|
||||
|
||||
x0 := int(math.Floor(xf))
|
||||
y0 := int(math.Floor(yf))
|
||||
bounds := src.Bounds()
|
||||
if !image.Pt(x0, y0).In(image.Rect(bounds.Min.X-1, bounds.Min.Y-1, bounds.Max.X, bounds.Max.Y)) {
|
||||
dst.Pix[dstIndex+0] = bgColor.R
|
||||
dst.Pix[dstIndex+1] = bgColor.G
|
||||
dst.Pix[dstIndex+2] = bgColor.B
|
||||
dst.Pix[dstIndex+3] = bgColor.A
|
||||
return
|
||||
}
|
||||
|
||||
xq := xf - float64(x0)
|
||||
yq := yf - float64(y0)
|
||||
|
||||
var pxs [4]color.NRGBA
|
||||
var cfs [4]float64
|
||||
|
||||
for i := 0; i < 2; i++ {
|
||||
for j := 0; j < 2; j++ {
|
||||
k := i*2 + j
|
||||
pt := image.Pt(x0+j, y0+i)
|
||||
if pt.In(bounds) {
|
||||
l := pt.Y*src.Stride + pt.X*4
|
||||
pxs[k].R = src.Pix[l+0]
|
||||
pxs[k].G = src.Pix[l+1]
|
||||
pxs[k].B = src.Pix[l+2]
|
||||
pxs[k].A = src.Pix[l+3]
|
||||
} else {
|
||||
pxs[k] = bgColor
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cfs[0] = (1 - xq) * (1 - yq)
|
||||
cfs[1] = xq * (1 - yq)
|
||||
cfs[2] = (1 - xq) * yq
|
||||
cfs[3] = xq * yq
|
||||
|
||||
var r, g, b, a float64
|
||||
for i := range pxs {
|
||||
wa := float64(pxs[i].A) * cfs[i]
|
||||
r += float64(pxs[i].R) * wa
|
||||
g += float64(pxs[i].G) * wa
|
||||
b += float64(pxs[i].B) * wa
|
||||
a += wa
|
||||
}
|
||||
|
||||
if a != 0 {
|
||||
r /= a
|
||||
g /= a
|
||||
b /= a
|
||||
}
|
||||
|
||||
dst.Pix[dstIndex+0] = clamp(r)
|
||||
dst.Pix[dstIndex+1] = clamp(g)
|
||||
dst.Pix[dstIndex+2] = clamp(b)
|
||||
dst.Pix[dstIndex+3] = clamp(a)
|
||||
}
|
|
@ -0,0 +1,83 @@
|
|||
package imaging
|
||||
|
||||
import (
|
||||
"image"
|
||||
"runtime"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// parallel processes the data in separate goroutines.
|
||||
func parallel(start, stop int, fn func(<-chan int)) {
|
||||
count := stop - start
|
||||
if count < 1 {
|
||||
return
|
||||
}
|
||||
|
||||
procs := runtime.GOMAXPROCS(0)
|
||||
if procs > count {
|
||||
procs = count
|
||||
}
|
||||
|
||||
c := make(chan int, count)
|
||||
for i := start; i < stop; i++ {
|
||||
c <- i
|
||||
}
|
||||
close(c)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < procs; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
fn(c)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
// absint returns the absolute value of i.
|
||||
func absint(i int) int {
|
||||
if i < 0 {
|
||||
return -i
|
||||
}
|
||||
return i
|
||||
}
|
||||
|
||||
// clamp rounds and clamps float64 value to fit into uint8.
|
||||
func clamp(x float64) uint8 {
|
||||
v := int64(x + 0.5)
|
||||
if v > 255 {
|
||||
return 255
|
||||
}
|
||||
if v > 0 {
|
||||
return uint8(v)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func reverse(pix []uint8) {
|
||||
if len(pix) <= 4 {
|
||||
return
|
||||
}
|
||||
i := 0
|
||||
j := len(pix) - 4
|
||||
for i < j {
|
||||
pix[i+0], pix[j+0] = pix[j+0], pix[i+0]
|
||||
pix[i+1], pix[j+1] = pix[j+1], pix[i+1]
|
||||
pix[i+2], pix[j+2] = pix[j+2], pix[i+2]
|
||||
pix[i+3], pix[j+3] = pix[j+3], pix[i+3]
|
||||
i += 4
|
||||
j -= 4
|
||||
}
|
||||
}
|
||||
|
||||
func toNRGBA(img image.Image) *image.NRGBA {
|
||||
if img, ok := img.(*image.NRGBA); ok {
|
||||
return &image.NRGBA{
|
||||
Pix: img.Pix,
|
||||
Stride: img.Stride,
|
||||
Rect: img.Rect.Sub(img.Rect.Min),
|
||||
}
|
||||
}
|
||||
return Clone(img)
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
Copyright (c) 2005-2008 Dustin Sallings <dustin@spy.net>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
<http://www.opensource.org/licenses/mit-license.php>
|
|
@ -0,0 +1,124 @@
|
|||
# Humane Units [![Build Status](https://travis-ci.org/dustin/go-humanize.svg?branch=master)](https://travis-ci.org/dustin/go-humanize) [![GoDoc](https://godoc.org/github.com/dustin/go-humanize?status.svg)](https://godoc.org/github.com/dustin/go-humanize)
|
||||
|
||||
Just a few functions for helping humanize times and sizes.
|
||||
|
||||
`go get` it as `github.com/dustin/go-humanize`, import it as
|
||||
`"github.com/dustin/go-humanize"`, use it as `humanize`.
|
||||
|
||||
See [godoc](https://godoc.org/github.com/dustin/go-humanize) for
|
||||
complete documentation.
|
||||
|
||||
## Sizes
|
||||
|
||||
This lets you take numbers like `82854982` and convert them to useful
|
||||
strings like, `83 MB` or `79 MiB` (whichever you prefer).
|
||||
|
||||
Example:
|
||||
|
||||
```go
|
||||
fmt.Printf("That file is %s.", humanize.Bytes(82854982)) // That file is 83 MB.
|
||||
```
|
||||
|
||||
## Times
|
||||
|
||||
This lets you take a `time.Time` and spit it out in relative terms.
|
||||
For example, `12 seconds ago` or `3 days from now`.
|
||||
|
||||
Example:
|
||||
|
||||
```go
|
||||
fmt.Printf("This was touched %s.", humanize.Time(someTimeInstance)) // This was touched 7 hours ago.
|
||||
```
|
||||
|
||||
Thanks to Kyle Lemons for the time implementation from an IRC
|
||||
conversation one day. It's pretty neat.
|
||||
|
||||
## Ordinals
|
||||
|
||||
From a [mailing list discussion][odisc] where a user wanted to be able
|
||||
to label ordinals.
|
||||
|
||||
0 -> 0th
|
||||
1 -> 1st
|
||||
2 -> 2nd
|
||||
3 -> 3rd
|
||||
4 -> 4th
|
||||
[...]
|
||||
|
||||
Example:
|
||||
|
||||
```go
|
||||
fmt.Printf("You're my %s best friend.", humanize.Ordinal(193)) // You are my 193rd best friend.
|
||||
```
|
||||
|
||||
## Commas
|
||||
|
||||
Want to shove commas into numbers? Be my guest.
|
||||
|
||||
0 -> 0
|
||||
100 -> 100
|
||||
1000 -> 1,000
|
||||
1000000000 -> 1,000,000,000
|
||||
-100000 -> -100,000
|
||||
|
||||
Example:
|
||||
|
||||
```go
|
||||
fmt.Printf("You owe $%s.\n", humanize.Comma(6582491)) // You owe $6,582,491.
|
||||
```
|
||||
|
||||
## Ftoa
|
||||
|
||||
Nicer float64 formatter that removes trailing zeros.
|
||||
|
||||
```go
|
||||
fmt.Printf("%f", 2.24) // 2.240000
|
||||
fmt.Printf("%s", humanize.Ftoa(2.24)) // 2.24
|
||||
fmt.Printf("%f", 2.0) // 2.000000
|
||||
fmt.Printf("%s", humanize.Ftoa(2.0)) // 2
|
||||
```
|
||||
|
||||
## SI notation
|
||||
|
||||
Format numbers with [SI notation][sinotation].
|
||||
|
||||
Example:
|
||||
|
||||
```go
|
||||
humanize.SI(0.00000000223, "M") // 2.23 nM
|
||||
```
|
||||
|
||||
## English-specific functions
|
||||
|
||||
The following functions are in the `humanize/english` subpackage.
|
||||
|
||||
### Plurals
|
||||
|
||||
Simple English pluralization
|
||||
|
||||
```go
|
||||
english.PluralWord(1, "object", "") // object
|
||||
english.PluralWord(42, "object", "") // objects
|
||||
english.PluralWord(2, "bus", "") // buses
|
||||
english.PluralWord(99, "locus", "loci") // loci
|
||||
|
||||
english.Plural(1, "object", "") // 1 object
|
||||
english.Plural(42, "object", "") // 42 objects
|
||||
english.Plural(2, "bus", "") // 2 buses
|
||||
english.Plural(99, "locus", "loci") // 99 loci
|
||||
```
|
||||
|
||||
### Word series
|
||||
|
||||
Format comma-separated words lists with conjuctions:
|
||||
|
||||
```go
|
||||
english.WordSeries([]string{"foo"}, "and") // foo
|
||||
english.WordSeries([]string{"foo", "bar"}, "and") // foo and bar
|
||||
english.WordSeries([]string{"foo", "bar", "baz"}, "and") // foo, bar and baz
|
||||
|
||||
english.OxfordWordSeries([]string{"foo", "bar", "baz"}, "and") // foo, bar, and baz
|
||||
```
|
||||
|
||||
[odisc]: https://groups.google.com/d/topic/golang-nuts/l8NhI74jl-4/discussion
|
||||
[sinotation]: http://en.wikipedia.org/wiki/Metric_prefix
|
|
@ -0,0 +1,31 @@
|
|||
package humanize
|
||||
|
||||
import (
|
||||
"math/big"
|
||||
)
|
||||
|
||||
// order of magnitude (to a max order)
|
||||
func oomm(n, b *big.Int, maxmag int) (float64, int) {
|
||||
mag := 0
|
||||
m := &big.Int{}
|
||||
for n.Cmp(b) >= 0 {
|
||||
n.DivMod(n, b, m)
|
||||
mag++
|
||||
if mag == maxmag && maxmag >= 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
return float64(n.Int64()) + (float64(m.Int64()) / float64(b.Int64())), mag
|
||||
}
|
||||
|
||||
// total order of magnitude
|
||||
// (same as above, but with no upper limit)
|
||||
func oom(n, b *big.Int) (float64, int) {
|
||||
mag := 0
|
||||
m := &big.Int{}
|
||||
for n.Cmp(b) >= 0 {
|
||||
n.DivMod(n, b, m)
|
||||
mag++
|
||||
}
|
||||
return float64(n.Int64()) + (float64(m.Int64()) / float64(b.Int64())), mag
|
||||
}
|
|
@ -0,0 +1,173 @@
|
|||
package humanize
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/big"
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
var (
|
||||
bigIECExp = big.NewInt(1024)
|
||||
|
||||
// BigByte is one byte in bit.Ints
|
||||
BigByte = big.NewInt(1)
|
||||
// BigKiByte is 1,024 bytes in bit.Ints
|
||||
BigKiByte = (&big.Int{}).Mul(BigByte, bigIECExp)
|
||||
// BigMiByte is 1,024 k bytes in bit.Ints
|
||||
BigMiByte = (&big.Int{}).Mul(BigKiByte, bigIECExp)
|
||||
// BigGiByte is 1,024 m bytes in bit.Ints
|
||||
BigGiByte = (&big.Int{}).Mul(BigMiByte, bigIECExp)
|
||||
// BigTiByte is 1,024 g bytes in bit.Ints
|
||||
BigTiByte = (&big.Int{}).Mul(BigGiByte, bigIECExp)
|
||||
// BigPiByte is 1,024 t bytes in bit.Ints
|
||||
BigPiByte = (&big.Int{}).Mul(BigTiByte, bigIECExp)
|
||||
// BigEiByte is 1,024 p bytes in bit.Ints
|
||||
BigEiByte = (&big.Int{}).Mul(BigPiByte, bigIECExp)
|
||||
// BigZiByte is 1,024 e bytes in bit.Ints
|
||||
BigZiByte = (&big.Int{}).Mul(BigEiByte, bigIECExp)
|
||||
// BigYiByte is 1,024 z bytes in bit.Ints
|
||||
BigYiByte = (&big.Int{}).Mul(BigZiByte, bigIECExp)
|
||||
)
|
||||
|
||||
var (
|
||||
bigSIExp = big.NewInt(1000)
|
||||
|
||||
// BigSIByte is one SI byte in big.Ints
|
||||
BigSIByte = big.NewInt(1)
|
||||
// BigKByte is 1,000 SI bytes in big.Ints
|
||||
BigKByte = (&big.Int{}).Mul(BigSIByte, bigSIExp)
|
||||
// BigMByte is 1,000 SI k bytes in big.Ints
|
||||
BigMByte = (&big.Int{}).Mul(BigKByte, bigSIExp)
|
||||
// BigGByte is 1,000 SI m bytes in big.Ints
|
||||
BigGByte = (&big.Int{}).Mul(BigMByte, bigSIExp)
|
||||
// BigTByte is 1,000 SI g bytes in big.Ints
|
||||
BigTByte = (&big.Int{}).Mul(BigGByte, bigSIExp)
|
||||
// BigPByte is 1,000 SI t bytes in big.Ints
|
||||
BigPByte = (&big.Int{}).Mul(BigTByte, bigSIExp)
|
||||
// BigEByte is 1,000 SI p bytes in big.Ints
|
||||
BigEByte = (&big.Int{}).Mul(BigPByte, bigSIExp)
|
||||
// BigZByte is 1,000 SI e bytes in big.Ints
|
||||
BigZByte = (&big.Int{}).Mul(BigEByte, bigSIExp)
|
||||
// BigYByte is 1,000 SI z bytes in big.Ints
|
||||
BigYByte = (&big.Int{}).Mul(BigZByte, bigSIExp)
|
||||
)
|
||||
|
||||
var bigBytesSizeTable = map[string]*big.Int{
|
||||
"b": BigByte,
|
||||
"kib": BigKiByte,
|
||||
"kb": BigKByte,
|
||||
"mib": BigMiByte,
|
||||
"mb": BigMByte,
|
||||
"gib": BigGiByte,
|
||||
"gb": BigGByte,
|
||||
"tib": BigTiByte,
|
||||
"tb": BigTByte,
|
||||
"pib": BigPiByte,
|
||||
"pb": BigPByte,
|
||||
"eib": BigEiByte,
|
||||
"eb": BigEByte,
|
||||
"zib": BigZiByte,
|
||||
"zb": BigZByte,
|
||||
"yib": BigYiByte,
|
||||
"yb": BigYByte,
|
||||
// Without suffix
|
||||
"": BigByte,
|
||||
"ki": BigKiByte,
|
||||
"k": BigKByte,
|
||||
"mi": BigMiByte,
|
||||
"m": BigMByte,
|
||||
"gi": BigGiByte,
|
||||
"g": BigGByte,
|
||||
"ti": BigTiByte,
|
||||
"t": BigTByte,
|
||||
"pi": BigPiByte,
|
||||
"p": BigPByte,
|
||||
"ei": BigEiByte,
|
||||
"e": BigEByte,
|
||||
"z": BigZByte,
|
||||
"zi": BigZiByte,
|
||||
"y": BigYByte,
|
||||
"yi": BigYiByte,
|
||||
}
|
||||
|
||||
var ten = big.NewInt(10)
|
||||
|
||||
func humanateBigBytes(s, base *big.Int, sizes []string) string {
|
||||
if s.Cmp(ten) < 0 {
|
||||
return fmt.Sprintf("%d B", s)
|
||||
}
|
||||
c := (&big.Int{}).Set(s)
|
||||
val, mag := oomm(c, base, len(sizes)-1)
|
||||
suffix := sizes[mag]
|
||||
f := "%.0f %s"
|
||||
if val < 10 {
|
||||
f = "%.1f %s"
|
||||
}
|
||||
|
||||
return fmt.Sprintf(f, val, suffix)
|
||||
|
||||
}
|
||||
|
||||
// BigBytes produces a human readable representation of an SI size.
|
||||
//
|
||||
// See also: ParseBigBytes.
|
||||
//
|
||||
// BigBytes(82854982) -> 83 MB
|
||||
func BigBytes(s *big.Int) string {
|
||||
sizes := []string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}
|
||||
return humanateBigBytes(s, bigSIExp, sizes)
|
||||
}
|
||||
|
||||
// BigIBytes produces a human readable representation of an IEC size.
|
||||
//
|
||||
// See also: ParseBigBytes.
|
||||
//
|
||||
// BigIBytes(82854982) -> 79 MiB
|
||||
func BigIBytes(s *big.Int) string {
|
||||
sizes := []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"}
|
||||
return humanateBigBytes(s, bigIECExp, sizes)
|
||||
}
|
||||
|
||||
// ParseBigBytes parses a string representation of bytes into the number
|
||||
// of bytes it represents.
|
||||
//
|
||||
// See also: BigBytes, BigIBytes.
|
||||
//
|
||||
// ParseBigBytes("42 MB") -> 42000000, nil
|
||||
// ParseBigBytes("42 mib") -> 44040192, nil
|
||||
func ParseBigBytes(s string) (*big.Int, error) {
|
||||
lastDigit := 0
|
||||
hasComma := false
|
||||
for _, r := range s {
|
||||
if !(unicode.IsDigit(r) || r == '.' || r == ',') {
|
||||
break
|
||||
}
|
||||
if r == ',' {
|
||||
hasComma = true
|
||||
}
|
||||
lastDigit++
|
||||
}
|
||||
|
||||
num := s[:lastDigit]
|
||||
if hasComma {
|
||||
num = strings.Replace(num, ",", "", -1)
|
||||
}
|
||||
|
||||
val := &big.Rat{}
|
||||
_, err := fmt.Sscanf(num, "%f", val)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
extra := strings.ToLower(strings.TrimSpace(s[lastDigit:]))
|
||||
if m, ok := bigBytesSizeTable[extra]; ok {
|
||||
mv := (&big.Rat{}).SetInt(m)
|
||||
val.Mul(val, mv)
|
||||
rv := &big.Int{}
|
||||
rv.Div(val.Num(), val.Denom())
|
||||
return rv, nil
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("unhandled size name: %v", extra)
|
||||
}
|
|
@ -0,0 +1,143 @@
|
|||
package humanize
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
// IEC Sizes.
|
||||
// kibis of bits
|
||||
const (
|
||||
Byte = 1 << (iota * 10)
|
||||
KiByte
|
||||
MiByte
|
||||
GiByte
|
||||
TiByte
|
||||
PiByte
|
||||
EiByte
|
||||
)
|
||||
|
||||
// SI Sizes.
|
||||
const (
|
||||
IByte = 1
|
||||
KByte = IByte * 1000
|
||||
MByte = KByte * 1000
|
||||
GByte = MByte * 1000
|
||||
TByte = GByte * 1000
|
||||
PByte = TByte * 1000
|
||||
EByte = PByte * 1000
|
||||
)
|
||||
|
||||
var bytesSizeTable = map[string]uint64{
|
||||
"b": Byte,
|
||||
"kib": KiByte,
|
||||
"kb": KByte,
|
||||
"mib": MiByte,
|
||||
"mb": MByte,
|
||||
"gib": GiByte,
|
||||
"gb": GByte,
|
||||
"tib": TiByte,
|
||||
"tb": TByte,
|
||||
"pib": PiByte,
|
||||
"pb": PByte,
|
||||
"eib": EiByte,
|
||||
"eb": EByte,
|
||||
// Without suffix
|
||||
"": Byte,
|
||||
"ki": KiByte,
|
||||
"k": KByte,
|
||||
"mi": MiByte,
|
||||
"m": MByte,
|
||||
"gi": GiByte,
|
||||
"g": GByte,
|
||||
"ti": TiByte,
|
||||
"t": TByte,
|
||||
"pi": PiByte,
|
||||
"p": PByte,
|
||||
"ei": EiByte,
|
||||
"e": EByte,
|
||||
}
|
||||
|
||||
func logn(n, b float64) float64 {
|
||||
return math.Log(n) / math.Log(b)
|
||||
}
|
||||
|
||||
func humanateBytes(s uint64, base float64, sizes []string) string {
|
||||
if s < 10 {
|
||||
return fmt.Sprintf("%d B", s)
|
||||
}
|
||||
e := math.Floor(logn(float64(s), base))
|
||||
suffix := sizes[int(e)]
|
||||
val := math.Floor(float64(s)/math.Pow(base, e)*10+0.5) / 10
|
||||
f := "%.0f %s"
|
||||
if val < 10 {
|
||||
f = "%.1f %s"
|
||||
}
|
||||
|
||||
return fmt.Sprintf(f, val, suffix)
|
||||
}
|
||||
|
||||
// Bytes produces a human readable representation of an SI size.
|
||||
//
|
||||
// See also: ParseBytes.
|
||||
//
|
||||
// Bytes(82854982) -> 83 MB
|
||||
func Bytes(s uint64) string {
|
||||
sizes := []string{"B", "kB", "MB", "GB", "TB", "PB", "EB"}
|
||||
return humanateBytes(s, 1000, sizes)
|
||||
}
|
||||
|
||||
// IBytes produces a human readable representation of an IEC size.
|
||||
//
|
||||
// See also: ParseBytes.
|
||||
//
|
||||
// IBytes(82854982) -> 79 MiB
|
||||
func IBytes(s uint64) string {
|
||||
sizes := []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"}
|
||||
return humanateBytes(s, 1024, sizes)
|
||||
}
|
||||
|
||||
// ParseBytes parses a string representation of bytes into the number
|
||||
// of bytes it represents.
|
||||
//
|
||||
// See Also: Bytes, IBytes.
|
||||
//
|
||||
// ParseBytes("42 MB") -> 42000000, nil
|
||||
// ParseBytes("42 mib") -> 44040192, nil
|
||||
func ParseBytes(s string) (uint64, error) {
|
||||
lastDigit := 0
|
||||
hasComma := false
|
||||
for _, r := range s {
|
||||
if !(unicode.IsDigit(r) || r == '.' || r == ',') {
|
||||
break
|
||||
}
|
||||
if r == ',' {
|
||||
hasComma = true
|
||||
}
|
||||
lastDigit++
|
||||
}
|
||||
|
||||
num := s[:lastDigit]
|
||||
if hasComma {
|
||||
num = strings.Replace(num, ",", "", -1)
|
||||
}
|
||||
|
||||
f, err := strconv.ParseFloat(num, 64)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
extra := strings.ToLower(strings.TrimSpace(s[lastDigit:]))
|
||||
if m, ok := bytesSizeTable[extra]; ok {
|
||||
f *= float64(m)
|
||||
if f >= math.MaxUint64 {
|
||||
return 0, fmt.Errorf("too large: %v", s)
|
||||
}
|
||||
return uint64(f), nil
|
||||
}
|
||||
|
||||
return 0, fmt.Errorf("unhandled size name: %v", extra)
|
||||
}
|
|
@ -0,0 +1,116 @@
|
|||
package humanize
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"math"
|
||||
"math/big"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Comma produces a string form of the given number in base 10 with
|
||||
// commas after every three orders of magnitude.
|
||||
//
|
||||
// e.g. Comma(834142) -> 834,142
|
||||
func Comma(v int64) string {
|
||||
sign := ""
|
||||
|
||||
// Min int64 can't be negated to a usable value, so it has to be special cased.
|
||||
if v == math.MinInt64 {
|
||||
return "-9,223,372,036,854,775,808"
|
||||
}
|
||||
|
||||
if v < 0 {
|
||||
sign = "-"
|
||||
v = 0 - v
|
||||
}
|
||||
|
||||
parts := []string{"", "", "", "", "", "", ""}
|
||||
j := len(parts) - 1
|
||||
|
||||
for v > 999 {
|
||||
parts[j] = strconv.FormatInt(v%1000, 10)
|
||||
switch len(parts[j]) {
|
||||
case 2:
|
||||
parts[j] = "0" + parts[j]
|
||||
case 1:
|
||||
parts[j] = "00" + parts[j]
|
||||
}
|
||||
v = v / 1000
|
||||
j--
|
||||
}
|
||||
parts[j] = strconv.Itoa(int(v))
|
||||
return sign + strings.Join(parts[j:], ",")
|
||||
}
|
||||
|
||||
// Commaf produces a string form of the given number in base 10 with
|
||||
// commas after every three orders of magnitude.
|
||||
//
|
||||
// e.g. Commaf(834142.32) -> 834,142.32
|
||||
func Commaf(v float64) string {
|
||||
buf := &bytes.Buffer{}
|
||||
if v < 0 {
|
||||
buf.Write([]byte{'-'})
|
||||
v = 0 - v
|
||||
}
|
||||
|
||||
comma := []byte{','}
|
||||
|
||||
parts := strings.Split(strconv.FormatFloat(v, 'f', -1, 64), ".")
|
||||
pos := 0
|
||||
if len(parts[0])%3 != 0 {
|
||||
pos += len(parts[0]) % 3
|
||||
buf.WriteString(parts[0][:pos])
|
||||
buf.Write(comma)
|
||||
}
|
||||
for ; pos < len(parts[0]); pos += 3 {
|
||||
buf.WriteString(parts[0][pos : pos+3])
|
||||
buf.Write(comma)
|
||||
}
|
||||
buf.Truncate(buf.Len() - 1)
|
||||
|
||||
if len(parts) > 1 {
|
||||
buf.Write([]byte{'.'})
|
||||
buf.WriteString(parts[1])
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
// CommafWithDigits works like the Commaf but limits the resulting
|
||||
// string to the given number of decimal places.
|
||||
//
|
||||
// e.g. CommafWithDigits(834142.32, 1) -> 834,142.3
|
||||
func CommafWithDigits(f float64, decimals int) string {
|
||||
return stripTrailingDigits(Commaf(f), decimals)
|
||||
}
|
||||
|
||||
// BigComma produces a string form of the given big.Int in base 10
|
||||
// with commas after every three orders of magnitude.
|
||||
func BigComma(b *big.Int) string {
|
||||
sign := ""
|
||||
if b.Sign() < 0 {
|
||||
sign = "-"
|
||||
b.Abs(b)
|
||||
}
|
||||
|
||||
athousand := big.NewInt(1000)
|
||||
c := (&big.Int{}).Set(b)
|
||||
_, m := oom(c, athousand)
|
||||
parts := make([]string, m+1)
|
||||
j := len(parts) - 1
|
||||
|
||||
mod := &big.Int{}
|
||||
for b.Cmp(athousand) >= 0 {
|
||||
b.DivMod(b, athousand, mod)
|
||||
parts[j] = strconv.FormatInt(mod.Int64(), 10)
|
||||
switch len(parts[j]) {
|
||||
case 2:
|
||||
parts[j] = "0" + parts[j]
|
||||
case 1:
|
||||
parts[j] = "00" + parts[j]
|
||||
}
|
||||
j--
|
||||
}
|
||||
parts[j] = strconv.Itoa(int(b.Int64()))
|
||||
return sign + strings.Join(parts[j:], ",")
|
||||
}
|
|
@ -0,0 +1,40 @@
|
|||
// +build go1.6
|
||||
|
||||
package humanize
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"math/big"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// BigCommaf produces a string form of the given big.Float in base 10
|
||||
// with commas after every three orders of magnitude.
|
||||
func BigCommaf(v *big.Float) string {
|
||||
buf := &bytes.Buffer{}
|
||||
if v.Sign() < 0 {
|
||||
buf.Write([]byte{'-'})
|
||||
v.Abs(v)
|
||||
}
|
||||
|
||||
comma := []byte{','}
|
||||
|
||||
parts := strings.Split(v.Text('f', -1), ".")
|
||||
pos := 0
|
||||
if len(parts[0])%3 != 0 {
|
||||
pos += len(parts[0]) % 3
|
||||
buf.WriteString(parts[0][:pos])
|
||||
buf.Write(comma)
|
||||
}
|
||||
for ; pos < len(parts[0]); pos += 3 {
|
||||
buf.WriteString(parts[0][pos : pos+3])
|
||||
buf.Write(comma)
|
||||
}
|
||||
buf.Truncate(buf.Len() - 1)
|
||||
|
||||
if len(parts) > 1 {
|
||||
buf.Write([]byte{'.'})
|
||||
buf.WriteString(parts[1])
|
||||
}
|
||||
return buf.String()
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
package humanize
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func stripTrailingZeros(s string) string {
|
||||
offset := len(s) - 1
|
||||
for offset > 0 {
|
||||
if s[offset] == '.' {
|
||||
offset--
|
||||
break
|
||||
}
|
||||
if s[offset] != '0' {
|
||||
break
|
||||
}
|
||||
offset--
|
||||
}
|
||||
return s[:offset+1]
|
||||
}
|
||||
|
||||
func stripTrailingDigits(s string, digits int) string {
|
||||
if i := strings.Index(s, "."); i >= 0 {
|
||||
if digits <= 0 {
|
||||
return s[:i]
|
||||
}
|
||||
i++
|
||||
if i+digits >= len(s) {
|
||||
return s
|
||||
}
|
||||
return s[:i+digits]
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// Ftoa converts a float to a string with no trailing zeros.
|
||||
func Ftoa(num float64) string {
|
||||
return stripTrailingZeros(strconv.FormatFloat(num, 'f', 6, 64))
|
||||
}
|
||||
|
||||
// FtoaWithDigits converts a float to a string but limits the resulting string
|
||||
// to the given number of decimal places, and no trailing zeros.
|
||||
func FtoaWithDigits(num float64, digits int) string {
|
||||
return stripTrailingZeros(stripTrailingDigits(strconv.FormatFloat(num, 'f', 6, 64), digits))
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
/*
|
||||
Package humanize converts boring ugly numbers to human-friendly strings and back.
|
||||
|
||||
Durations can be turned into strings such as "3 days ago", numbers
|
||||
representing sizes like 82854982 into useful strings like, "83 MB" or
|
||||
"79 MiB" (whichever you prefer).
|
||||
*/
|
||||
package humanize
|
|
@ -0,0 +1,192 @@
|
|||
package humanize
|
||||
|
||||
/*
|
||||
Slightly adapted from the source to fit go-humanize.
|
||||
|
||||
Author: https://github.com/gorhill
|
||||
Source: https://gist.github.com/gorhill/5285193
|
||||
|
||||
*/
|
||||
|
||||
import (
|
||||
"math"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
var (
|
||||
renderFloatPrecisionMultipliers = [...]float64{
|
||||
1,
|
||||
10,
|
||||
100,
|
||||
1000,
|
||||
10000,
|
||||
100000,
|
||||
1000000,
|
||||
10000000,
|
||||
100000000,
|
||||
1000000000,
|
||||
}
|
||||
|
||||
renderFloatPrecisionRounders = [...]float64{
|
||||
0.5,
|
||||
0.05,
|
||||
0.005,
|
||||
0.0005,
|
||||
0.00005,
|
||||
0.000005,
|
||||
0.0000005,
|
||||
0.00000005,
|
||||
0.000000005,
|
||||
0.0000000005,
|
||||
}
|
||||
)
|
||||
|
||||
// FormatFloat produces a formatted number as string based on the following user-specified criteria:
|
||||
// * thousands separator
|
||||
// * decimal separator
|
||||
// * decimal precision
|
||||
//
|
||||
// Usage: s := RenderFloat(format, n)
|
||||
// The format parameter tells how to render the number n.
|
||||
//
|
||||
// See examples: http://play.golang.org/p/LXc1Ddm1lJ
|
||||
//
|
||||
// Examples of format strings, given n = 12345.6789:
|
||||
// "#,###.##" => "12,345.67"
|
||||
// "#,###." => "12,345"
|
||||
// "#,###" => "12345,678"
|
||||
// "#\u202F###,##" => "12 345,68"
|
||||
// "#.###,###### => 12.345,678900
|
||||
// "" (aka default format) => 12,345.67
|
||||
//
|
||||
// The highest precision allowed is 9 digits after the decimal symbol.
|
||||
// There is also a version for integer number, FormatInteger(),
|
||||
// which is convenient for calls within template.
|
||||
func FormatFloat(format string, n float64) string {
|
||||
// Special cases:
|
||||
// NaN = "NaN"
|
||||
// +Inf = "+Infinity"
|
||||
// -Inf = "-Infinity"
|
||||
if math.IsNaN(n) {
|
||||
return "NaN"
|
||||
}
|
||||
if n > math.MaxFloat64 {
|
||||
return "Infinity"
|
||||
}
|
||||
if n < -math.MaxFloat64 {
|
||||
return "-Infinity"
|
||||
}
|
||||
|
||||
// default format
|
||||
precision := 2
|
||||
decimalStr := "."
|
||||
thousandStr := ","
|
||||
positiveStr := ""
|
||||
negativeStr := "-"
|
||||
|
||||
if len(format) > 0 {
|
||||
format := []rune(format)
|
||||
|
||||
// If there is an explicit format directive,
|
||||
// then default values are these:
|
||||
precision = 9
|
||||
thousandStr = ""
|
||||
|
||||
// collect indices of meaningful formatting directives
|
||||
formatIndx := []int{}
|
||||
for i, char := range format {
|
||||
if char != '#' && char != '0' {
|
||||
formatIndx = append(formatIndx, i)
|
||||
}
|
||||
}
|
||||
|
||||
if len(formatIndx) > 0 {
|
||||
// Directive at index 0:
|
||||
// Must be a '+'
|
||||
// Raise an error if not the case
|
||||
// index: 0123456789
|
||||
// +0.000,000
|
||||
// +000,000.0
|
||||
// +0000.00
|
||||
// +0000
|
||||
if formatIndx[0] == 0 {
|
||||
if format[formatIndx[0]] != '+' {
|
||||
panic("RenderFloat(): invalid positive sign directive")
|
||||
}
|
||||
positiveStr = "+"
|
||||
formatIndx = formatIndx[1:]
|
||||
}
|
||||
|
||||
// Two directives:
|
||||
// First is thousands separator
|
||||
// Raise an error if not followed by 3-digit
|
||||
// 0123456789
|
||||
// 0.000,000
|
||||
// 000,000.00
|
||||
if len(formatIndx) == 2 {
|
||||
if (formatIndx[1] - formatIndx[0]) != 4 {
|
||||
panic("RenderFloat(): thousands separator directive must be followed by 3 digit-specifiers")
|
||||
}
|
||||
thousandStr = string(format[formatIndx[0]])
|
||||
formatIndx = formatIndx[1:]
|
||||
}
|
||||
|
||||
// One directive:
|
||||
// Directive is decimal separator
|
||||
// The number of digit-specifier following the separator indicates wanted precision
|
||||
// 0123456789
|
||||
// 0.00
|
||||
// 000,0000
|
||||
if len(formatIndx) == 1 {
|
||||
decimalStr = string(format[formatIndx[0]])
|
||||
precision = len(format) - formatIndx[0] - 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// generate sign part
|
||||
var signStr string
|
||||
if n >= 0.000000001 {
|
||||
signStr = positiveStr
|
||||
} else if n <= -0.000000001 {
|
||||
signStr = negativeStr
|
||||
n = -n
|
||||
} else {
|
||||
signStr = ""
|
||||
n = 0.0
|
||||
}
|
||||
|
||||
// split number into integer and fractional parts
|
||||
intf, fracf := math.Modf(n + renderFloatPrecisionRounders[precision])
|
||||
|
||||
// generate integer part string
|
||||
intStr := strconv.FormatInt(int64(intf), 10)
|
||||
|
||||
// add thousand separator if required
|
||||
if len(thousandStr) > 0 {
|
||||
for i := len(intStr); i > 3; {
|
||||
i -= 3
|
||||
intStr = intStr[:i] + thousandStr + intStr[i:]
|
||||
}
|
||||
}
|
||||
|
||||
// no fractional part, we can leave now
|
||||
if precision == 0 {
|
||||
return signStr + intStr
|
||||
}
|
||||
|
||||
// generate fractional part
|
||||
fracStr := strconv.Itoa(int(fracf * renderFloatPrecisionMultipliers[precision]))
|
||||
// may need padding
|
||||
if len(fracStr) < precision {
|
||||
fracStr = "000000000000000"[:precision-len(fracStr)] + fracStr
|
||||
}
|
||||
|
||||
return signStr + intStr + decimalStr + fracStr
|
||||
}
|
||||
|
||||
// FormatInteger produces a formatted number as string.
|
||||
// See FormatFloat.
|
||||
func FormatInteger(format string, n int) string {
|
||||
return FormatFloat(format, float64(n))
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package humanize
|
||||
|
||||
import "strconv"
|
||||
|
||||
// Ordinal gives you the input number in a rank/ordinal format.
|
||||
//
|
||||
// Ordinal(3) -> 3rd
|
||||
func Ordinal(x int) string {
|
||||
suffix := "th"
|
||||
switch x % 10 {
|
||||
case 1:
|
||||
if x%100 != 11 {
|
||||
suffix = "st"
|
||||
}
|
||||
case 2:
|
||||
if x%100 != 12 {
|
||||
suffix = "nd"
|
||||
}
|
||||
case 3:
|
||||
if x%100 != 13 {
|
||||
suffix = "rd"
|
||||
}
|
||||
}
|
||||
return strconv.Itoa(x) + suffix
|
||||
}
|
|
@ -0,0 +1,123 @@
|
|||
package humanize
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"math"
|
||||
"regexp"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
var siPrefixTable = map[float64]string{
|
||||
-24: "y", // yocto
|
||||
-21: "z", // zepto
|
||||
-18: "a", // atto
|
||||
-15: "f", // femto
|
||||
-12: "p", // pico
|
||||
-9: "n", // nano
|
||||
-6: "µ", // micro
|
||||
-3: "m", // milli
|
||||
0: "",
|
||||
3: "k", // kilo
|
||||
6: "M", // mega
|
||||
9: "G", // giga
|
||||
12: "T", // tera
|
||||
15: "P", // peta
|
||||
18: "E", // exa
|
||||
21: "Z", // zetta
|
||||
24: "Y", // yotta
|
||||
}
|
||||
|
||||
var revSIPrefixTable = revfmap(siPrefixTable)
|
||||
|
||||
// revfmap reverses the map and precomputes the power multiplier
|
||||
func revfmap(in map[float64]string) map[string]float64 {
|
||||
rv := map[string]float64{}
|
||||
for k, v := range in {
|
||||
rv[v] = math.Pow(10, k)
|
||||
}
|
||||
return rv
|
||||
}
|
||||
|
||||
var riParseRegex *regexp.Regexp
|
||||
|
||||
func init() {
|
||||
ri := `^([\-0-9.]+)\s?([`
|
||||
for _, v := range siPrefixTable {
|
||||
ri += v
|
||||
}
|
||||
ri += `]?)(.*)`
|
||||
|
||||
riParseRegex = regexp.MustCompile(ri)
|
||||
}
|
||||
|
||||
// ComputeSI finds the most appropriate SI prefix for the given number
|
||||
// and returns the prefix along with the value adjusted to be within
|
||||
// that prefix.
|
||||
//
|
||||
// See also: SI, ParseSI.
|
||||
//
|
||||
// e.g. ComputeSI(2.2345e-12) -> (2.2345, "p")
|
||||
func ComputeSI(input float64) (float64, string) {
|
||||
if input == 0 {
|
||||
return 0, ""
|
||||
}
|
||||
mag := math.Abs(input)
|
||||
exponent := math.Floor(logn(mag, 10))
|
||||
exponent = math.Floor(exponent/3) * 3
|
||||
|
||||
value := mag / math.Pow(10, exponent)
|
||||
|
||||
// Handle special case where value is exactly 1000.0
|
||||
// Should return 1 M instead of 1000 k
|
||||
if value == 1000.0 {
|
||||
exponent += 3
|
||||
value = mag / math.Pow(10, exponent)
|
||||
}
|
||||
|
||||
value = math.Copysign(value, input)
|
||||
|
||||
prefix := siPrefixTable[exponent]
|
||||
return value, prefix
|
||||
}
|
||||
|
||||
// SI returns a string with default formatting.
|
||||
//
|
||||
// SI uses Ftoa to format float value, removing trailing zeros.
|
||||
//
|
||||
// See also: ComputeSI, ParseSI.
|
||||
//
|
||||
// e.g. SI(1000000, "B") -> 1 MB
|
||||
// e.g. SI(2.2345e-12, "F") -> 2.2345 pF
|
||||
func SI(input float64, unit string) string {
|
||||
value, prefix := ComputeSI(input)
|
||||
return Ftoa(value) + " " + prefix + unit
|
||||
}
|
||||
|
||||
// SIWithDigits works like SI but limits the resulting string to the
|
||||
// given number of decimal places.
|
||||
//
|
||||
// e.g. SIWithDigits(1000000, 0, "B") -> 1 MB
|
||||
// e.g. SIWithDigits(2.2345e-12, 2, "F") -> 2.23 pF
|
||||
func SIWithDigits(input float64, decimals int, unit string) string {
|
||||
value, prefix := ComputeSI(input)
|
||||
return FtoaWithDigits(value, decimals) + " " + prefix + unit
|
||||
}
|
||||
|
||||
var errInvalid = errors.New("invalid input")
|
||||
|
||||
// ParseSI parses an SI string back into the number and unit.
|
||||
//
|
||||
// See also: SI, ComputeSI.
|
||||
//
|
||||
// e.g. ParseSI("2.2345 pF") -> (2.2345e-12, "F", nil)
|
||||
func ParseSI(input string) (float64, string, error) {
|
||||
found := riParseRegex.FindStringSubmatch(input)
|
||||
if len(found) != 4 {
|
||||
return 0, "", errInvalid
|
||||
}
|
||||
mag := revSIPrefixTable[found[2]]
|
||||
unit := found[3]
|
||||
|
||||
base, err := strconv.ParseFloat(found[1], 64)
|
||||
return base * mag, unit, err
|
||||
}
|
|
@ -0,0 +1,117 @@
|
|||
package humanize
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"sort"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Seconds-based time units
|
||||
const (
|
||||
Day = 24 * time.Hour
|
||||
Week = 7 * Day
|
||||
Month = 30 * Day
|
||||
Year = 12 * Month
|
||||
LongTime = 37 * Year
|
||||
)
|
||||
|
||||
// Time formats a time into a relative string.
|
||||
//
|
||||
// Time(someT) -> "3 weeks ago"
|
||||
func Time(then time.Time) string {
|
||||
return RelTime(then, time.Now(), "ago", "from now")
|
||||
}
|
||||
|
||||
// A RelTimeMagnitude struct contains a relative time point at which
|
||||
// the relative format of time will switch to a new format string. A
|
||||
// slice of these in ascending order by their "D" field is passed to
|
||||
// CustomRelTime to format durations.
|
||||
//
|
||||
// The Format field is a string that may contain a "%s" which will be
|
||||
// replaced with the appropriate signed label (e.g. "ago" or "from
|
||||
// now") and a "%d" that will be replaced by the quantity.
|
||||
//
|
||||
// The DivBy field is the amount of time the time difference must be
|
||||
// divided by in order to display correctly.
|
||||
//
|
||||
// e.g. if D is 2*time.Minute and you want to display "%d minutes %s"
|
||||
// DivBy should be time.Minute so whatever the duration is will be
|
||||
// expressed in minutes.
|
||||
type RelTimeMagnitude struct {
|
||||
D time.Duration
|
||||
Format string
|
||||
DivBy time.Duration
|
||||
}
|
||||
|
||||
var defaultMagnitudes = []RelTimeMagnitude{
|
||||
{time.Second, "now", time.Second},
|
||||
{2 * time.Second, "1 second %s", 1},
|
||||
{time.Minute, "%d seconds %s", time.Second},
|
||||
{2 * time.Minute, "1 minute %s", 1},
|
||||
{time.Hour, "%d minutes %s", time.Minute},
|
||||
{2 * time.Hour, "1 hour %s", 1},
|
||||
{Day, "%d hours %s", time.Hour},
|
||||
{2 * Day, "1 day %s", 1},
|
||||
{Week, "%d days %s", Day},
|
||||
{2 * Week, "1 week %s", 1},
|
||||
{Month, "%d weeks %s", Week},
|
||||
{2 * Month, "1 month %s", 1},
|
||||
{Year, "%d months %s", Month},
|
||||
{18 * Month, "1 year %s", 1},
|
||||
{2 * Year, "2 years %s", 1},
|
||||
{LongTime, "%d years %s", Year},
|
||||
{math.MaxInt64, "a long while %s", 1},
|
||||
}
|
||||
|
||||
// RelTime formats a time into a relative string.
|
||||
//
|
||||
// It takes two times and two labels. In addition to the generic time
|
||||
// delta string (e.g. 5 minutes), the labels are used applied so that
|
||||
// the label corresponding to the smaller time is applied.
|
||||
//
|
||||
// RelTime(timeInPast, timeInFuture, "earlier", "later") -> "3 weeks earlier"
|
||||
func RelTime(a, b time.Time, albl, blbl string) string {
|
||||
return CustomRelTime(a, b, albl, blbl, defaultMagnitudes)
|
||||
}
|
||||
|
||||
// CustomRelTime formats a time into a relative string.
|
||||
//
|
||||
// It takes two times two labels and a table of relative time formats.
|
||||
// In addition to the generic time delta string (e.g. 5 minutes), the
|
||||
// labels are used applied so that the label corresponding to the
|
||||
// smaller time is applied.
|
||||
func CustomRelTime(a, b time.Time, albl, blbl string, magnitudes []RelTimeMagnitude) string {
|
||||
lbl := albl
|
||||
diff := b.Sub(a)
|
||||
|
||||
if a.After(b) {
|
||||
lbl = blbl
|
||||
diff = a.Sub(b)
|
||||
}
|
||||
|
||||
n := sort.Search(len(magnitudes), func(i int) bool {
|
||||
return magnitudes[i].D > diff
|
||||
})
|
||||
|
||||
if n >= len(magnitudes) {
|
||||
n = len(magnitudes) - 1
|
||||
}
|
||||
mag := magnitudes[n]
|
||||
args := []interface{}{}
|
||||
escaped := false
|
||||
for _, ch := range mag.Format {
|
||||
if escaped {
|
||||
switch ch {
|
||||
case 's':
|
||||
args = append(args, lbl)
|
||||
case 'd':
|
||||
args = append(args, diff/mag.DivBy)
|
||||
}
|
||||
escaped = false
|
||||
} else {
|
||||
escaped = ch == '%'
|
||||
}
|
||||
}
|
||||
return fmt.Sprintf(mag.Format, args...)
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014 Fatih Arslan
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
|
@ -0,0 +1,170 @@
|
|||
# Archived project. No maintenance.
|
||||
|
||||
This project is not maintained anymore and is archived. Feel free to fork and
|
||||
make your own changes if needed. For more detail read my blog post: [Taking an indefinite sabbatical from my projects](https://arslan.io/2018/10/09/taking-an-indefinite-sabbatical-from-my-projects/)
|
||||
|
||||
Thanks to everyone for their valuable feedback and contributions.
|
||||
|
||||
# Structs [![GoDoc](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)](http://godoc.org/github.com/fatih/structs) [![Build Status](http://img.shields.io/travis/fatih/structs.svg?style=flat-square)](https://travis-ci.org/fatih/structs) [![Coverage Status](http://img.shields.io/coveralls/fatih/structs.svg?style=flat-square)](https://coveralls.io/r/fatih/structs)
|
||||
|
||||
Structs contains various utilities to work with Go (Golang) structs. It was
|
||||
initially used by me to convert a struct into a `map[string]interface{}`. With
|
||||
time I've added other utilities for structs. It's basically a high level
|
||||
package based on primitives from the reflect package. Feel free to add new
|
||||
functions or improve the existing code.
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
go get github.com/fatih/structs
|
||||
```
|
||||
|
||||
## Usage and Examples
|
||||
|
||||
Just like the standard lib `strings`, `bytes` and co packages, `structs` has
|
||||
many global functions to manipulate or organize your struct data. Lets define
|
||||
and declare a struct:
|
||||
|
||||
```go
|
||||
type Server struct {
|
||||
Name string `json:"name,omitempty"`
|
||||
ID int
|
||||
Enabled bool
|
||||
users []string // not exported
|
||||
http.Server // embedded
|
||||
}
|
||||
|
||||
server := &Server{
|
||||
Name: "gopher",
|
||||
ID: 123456,
|
||||
Enabled: true,
|
||||
}
|
||||
```
|
||||
|
||||
```go
|
||||
// Convert a struct to a map[string]interface{}
|
||||
// => {"Name":"gopher", "ID":123456, "Enabled":true}
|
||||
m := structs.Map(server)
|
||||
|
||||
// Convert the values of a struct to a []interface{}
|
||||
// => ["gopher", 123456, true]
|
||||
v := structs.Values(server)
|
||||
|
||||
// Convert the names of a struct to a []string
|
||||
// (see "Names methods" for more info about fields)
|
||||
n := structs.Names(server)
|
||||
|
||||
// Convert the values of a struct to a []*Field
|
||||
// (see "Field methods" for more info about fields)
|
||||
f := structs.Fields(server)
|
||||
|
||||
// Return the struct name => "Server"
|
||||
n := structs.Name(server)
|
||||
|
||||
// Check if any field of a struct is initialized or not.
|
||||
h := structs.HasZero(server)
|
||||
|
||||
// Check if all fields of a struct is initialized or not.
|
||||
z := structs.IsZero(server)
|
||||
|
||||
// Check if server is a struct or a pointer to struct
|
||||
i := structs.IsStruct(server)
|
||||
```
|
||||
|
||||
### Struct methods
|
||||
|
||||
The structs functions can be also used as independent methods by creating a new
|
||||
`*structs.Struct`. This is handy if you want to have more control over the
|
||||
structs (such as retrieving a single Field).
|
||||
|
||||
```go
|
||||
// Create a new struct type:
|
||||
s := structs.New(server)
|
||||
|
||||
m := s.Map() // Get a map[string]interface{}
|
||||
v := s.Values() // Get a []interface{}
|
||||
f := s.Fields() // Get a []*Field
|
||||
n := s.Names() // Get a []string
|
||||
f := s.Field(name) // Get a *Field based on the given field name
|
||||
f, ok := s.FieldOk(name) // Get a *Field based on the given field name
|
||||
n := s.Name() // Get the struct name
|
||||
h := s.HasZero() // Check if any field is uninitialized
|
||||
z := s.IsZero() // Check if all fields are uninitialized
|
||||
```
|
||||
|
||||
### Field methods
|
||||
|
||||
We can easily examine a single Field for more detail. Below you can see how we
|
||||
get and interact with various field methods:
|
||||
|
||||
|
||||
```go
|
||||
s := structs.New(server)
|
||||
|
||||
// Get the Field struct for the "Name" field
|
||||
name := s.Field("Name")
|
||||
|
||||
// Get the underlying value, value => "gopher"
|
||||
value := name.Value().(string)
|
||||
|
||||
// Set the field's value
|
||||
name.Set("another gopher")
|
||||
|
||||
// Get the field's kind, kind => "string"
|
||||
name.Kind()
|
||||
|
||||
// Check if the field is exported or not
|
||||
if name.IsExported() {
|
||||
fmt.Println("Name field is exported")
|
||||
}
|
||||
|
||||
// Check if the value is a zero value, such as "" for string, 0 for int
|
||||
if !name.IsZero() {
|
||||
fmt.Println("Name is initialized")
|
||||
}
|
||||
|
||||
// Check if the field is an anonymous (embedded) field
|
||||
if !name.IsEmbedded() {
|
||||
fmt.Println("Name is not an embedded field")
|
||||
}
|
||||
|
||||
// Get the Field's tag value for tag name "json", tag value => "name,omitempty"
|
||||
tagValue := name.Tag("json")
|
||||
```
|
||||
|
||||
Nested structs are supported too:
|
||||
|
||||
```go
|
||||
addrField := s.Field("Server").Field("Addr")
|
||||
|
||||
// Get the value for addr
|
||||
a := addrField.Value().(string)
|
||||
|
||||
// Or get all fields
|
||||
httpServer := s.Field("Server").Fields()
|
||||
```
|
||||
|
||||
We can also get a slice of Fields from the Struct type to iterate over all
|
||||
fields. This is handy if you wish to examine all fields:
|
||||
|
||||
```go
|
||||
s := structs.New(server)
|
||||
|
||||
for _, f := range s.Fields() {
|
||||
fmt.Printf("field name: %+v\n", f.Name())
|
||||
|
||||
if f.IsExported() {
|
||||
fmt.Printf("value : %+v\n", f.Value())
|
||||
fmt.Printf("is zero : %+v\n", f.IsZero())
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Credits
|
||||
|
||||
* [Fatih Arslan](https://github.com/fatih)
|
||||
* [Cihangir Savas](https://github.com/cihangir)
|
||||
|
||||
## License
|
||||
|
||||
The MIT License (MIT) - see LICENSE.md for more details
|
|
@ -0,0 +1,141 @@
|
|||
package structs
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
var (
|
||||
errNotExported = errors.New("field is not exported")
|
||||
errNotSettable = errors.New("field is not settable")
|
||||
)
|
||||
|
||||
// Field represents a single struct field that encapsulates high level
|
||||
// functions around the field.
|
||||
type Field struct {
|
||||
value reflect.Value
|
||||
field reflect.StructField
|
||||
defaultTag string
|
||||
}
|
||||
|
||||
// Tag returns the value associated with key in the tag string. If there is no
|
||||
// such key in the tag, Tag returns the empty string.
|
||||
func (f *Field) Tag(key string) string {
|
||||
return f.field.Tag.Get(key)
|
||||
}
|
||||
|
||||
// Value returns the underlying value of the field. It panics if the field
|
||||
// is not exported.
|
||||
func (f *Field) Value() interface{} {
|
||||
return f.value.Interface()
|
||||
}
|
||||
|
||||
// IsEmbedded returns true if the given field is an anonymous field (embedded)
|
||||
func (f *Field) IsEmbedded() bool {
|
||||
return f.field.Anonymous
|
||||
}
|
||||
|
||||
// IsExported returns true if the given field is exported.
|
||||
func (f *Field) IsExported() bool {
|
||||
return f.field.PkgPath == ""
|
||||
}
|
||||
|
||||
// IsZero returns true if the given field is not initialized (has a zero value).
|
||||
// It panics if the field is not exported.
|
||||
func (f *Field) IsZero() bool {
|
||||
zero := reflect.Zero(f.value.Type()).Interface()
|
||||
current := f.Value()
|
||||
|
||||
return reflect.DeepEqual(current, zero)
|
||||
}
|
||||
|
||||
// Name returns the name of the given field
|
||||
func (f *Field) Name() string {
|
||||
return f.field.Name
|
||||
}
|
||||
|
||||
// Kind returns the fields kind, such as "string", "map", "bool", etc ..
|
||||
func (f *Field) Kind() reflect.Kind {
|
||||
return f.value.Kind()
|
||||
}
|
||||
|
||||
// Set sets the field to given value v. It returns an error if the field is not
|
||||
// settable (not addressable or not exported) or if the given value's type
|
||||
// doesn't match the fields type.
|
||||
func (f *Field) Set(val interface{}) error {
|
||||
// we can't set unexported fields, so be sure this field is exported
|
||||
if !f.IsExported() {
|
||||
return errNotExported
|
||||
}
|
||||
|
||||
// do we get here? not sure...
|
||||
if !f.value.CanSet() {
|
||||
return errNotSettable
|
||||
}
|
||||
|
||||
given := reflect.ValueOf(val)
|
||||
|
||||
if f.value.Kind() != given.Kind() {
|
||||
return fmt.Errorf("wrong kind. got: %s want: %s", given.Kind(), f.value.Kind())
|
||||
}
|
||||
|
||||
f.value.Set(given)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Zero sets the field to its zero value. It returns an error if the field is not
|
||||
// settable (not addressable or not exported).
|
||||
func (f *Field) Zero() error {
|
||||
zero := reflect.Zero(f.value.Type()).Interface()
|
||||
return f.Set(zero)
|
||||
}
|
||||
|
||||
// Fields returns a slice of Fields. This is particular handy to get the fields
|
||||
// of a nested struct . A struct tag with the content of "-" ignores the
|
||||
// checking of that particular field. Example:
|
||||
//
|
||||
// // Field is ignored by this package.
|
||||
// Field *http.Request `structs:"-"`
|
||||
//
|
||||
// It panics if field is not exported or if field's kind is not struct
|
||||
func (f *Field) Fields() []*Field {
|
||||
return getFields(f.value, f.defaultTag)
|
||||
}
|
||||
|
||||
// Field returns the field from a nested struct. It panics if the nested struct
|
||||
// is not exported or if the field was not found.
|
||||
func (f *Field) Field(name string) *Field {
|
||||
field, ok := f.FieldOk(name)
|
||||
if !ok {
|
||||
panic("field not found")
|
||||
}
|
||||
|
||||
return field
|
||||
}
|
||||
|
||||
// FieldOk returns the field from a nested struct. The boolean returns whether
|
||||
// the field was found (true) or not (false).
|
||||
func (f *Field) FieldOk(name string) (*Field, bool) {
|
||||
value := &f.value
|
||||
// value must be settable so we need to make sure it holds the address of the
|
||||
// variable and not a copy, so we can pass the pointer to strctVal instead of a
|
||||
// copy (which is not assigned to any variable, hence not settable).
|
||||
// see "https://blog.golang.org/laws-of-reflection#TOC_8."
|
||||
if f.value.Kind() != reflect.Ptr {
|
||||
a := f.value.Addr()
|
||||
value = &a
|
||||
}
|
||||
v := strctVal(value.Interface())
|
||||
t := v.Type()
|
||||
|
||||
field, ok := t.FieldByName(name)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
return &Field{
|
||||
field: field,
|
||||
value: v.FieldByName(name),
|
||||
}, true
|
||||
}
|
|
@ -0,0 +1,584 @@
|
|||
// Package structs contains various utilities functions to work with structs.
|
||||
package structs
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"reflect"
|
||||
)
|
||||
|
||||
var (
|
||||
// DefaultTagName is the default tag name for struct fields which provides
|
||||
// a more granular to tweak certain structs. Lookup the necessary functions
|
||||
// for more info.
|
||||
DefaultTagName = "structs" // struct's field default tag name
|
||||
)
|
||||
|
||||
// Struct encapsulates a struct type to provide several high level functions
|
||||
// around the struct.
|
||||
type Struct struct {
|
||||
raw interface{}
|
||||
value reflect.Value
|
||||
TagName string
|
||||
}
|
||||
|
||||
// New returns a new *Struct with the struct s. It panics if the s's kind is
|
||||
// not struct.
|
||||
func New(s interface{}) *Struct {
|
||||
return &Struct{
|
||||
raw: s,
|
||||
value: strctVal(s),
|
||||
TagName: DefaultTagName,
|
||||
}
|
||||
}
|
||||
|
||||
// Map converts the given struct to a map[string]interface{}, where the keys
|
||||
// of the map are the field names and the values of the map the associated
|
||||
// values of the fields. The default key string is the struct field name but
|
||||
// can be changed in the struct field's tag value. The "structs" key in the
|
||||
// struct's field tag value is the key name. Example:
|
||||
//
|
||||
// // Field appears in map as key "myName".
|
||||
// Name string `structs:"myName"`
|
||||
//
|
||||
// A tag value with the content of "-" ignores that particular field. Example:
|
||||
//
|
||||
// // Field is ignored by this package.
|
||||
// Field bool `structs:"-"`
|
||||
//
|
||||
// A tag value with the content of "string" uses the stringer to get the value. Example:
|
||||
//
|
||||
// // The value will be output of Animal's String() func.
|
||||
// // Map will panic if Animal does not implement String().
|
||||
// Field *Animal `structs:"field,string"`
|
||||
//
|
||||
// A tag value with the option of "flatten" used in a struct field is to flatten its fields
|
||||
// in the output map. Example:
|
||||
//
|
||||
// // The FieldStruct's fields will be flattened into the output map.
|
||||
// FieldStruct time.Time `structs:",flatten"`
|
||||
//
|
||||
// A tag value with the option of "omitnested" stops iterating further if the type
|
||||
// is a struct. Example:
|
||||
//
|
||||
// // Field is not processed further by this package.
|
||||
// Field time.Time `structs:"myName,omitnested"`
|
||||
// Field *http.Request `structs:",omitnested"`
|
||||
//
|
||||
// A tag value with the option of "omitempty" ignores that particular field if
|
||||
// the field value is empty. Example:
|
||||
//
|
||||
// // Field appears in map as key "myName", but the field is
|
||||
// // skipped if empty.
|
||||
// Field string `structs:"myName,omitempty"`
|
||||
//
|
||||
// // Field appears in map as key "Field" (the default), but
|
||||
// // the field is skipped if empty.
|
||||
// Field string `structs:",omitempty"`
|
||||
//
|
||||
// Note that only exported fields of a struct can be accessed, non exported
|
||||
// fields will be neglected.
|
||||
func (s *Struct) Map() map[string]interface{} {
|
||||
out := make(map[string]interface{})
|
||||
s.FillMap(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// FillMap is the same as Map. Instead of returning the output, it fills the
|
||||
// given map.
|
||||
func (s *Struct) FillMap(out map[string]interface{}) {
|
||||
if out == nil {
|
||||
return
|
||||
}
|
||||
|
||||
fields := s.structFields()
|
||||
|
||||
for _, field := range fields {
|
||||
name := field.Name
|
||||
val := s.value.FieldByName(name)
|
||||
isSubStruct := false
|
||||
var finalVal interface{}
|
||||
|
||||
tagName, tagOpts := parseTag(field.Tag.Get(s.TagName))
|
||||
if tagName != "" {
|
||||
name = tagName
|
||||
}
|
||||
|
||||
// if the value is a zero value and the field is marked as omitempty do
|
||||
// not include
|
||||
if tagOpts.Has("omitempty") {
|
||||
zero := reflect.Zero(val.Type()).Interface()
|
||||
current := val.Interface()
|
||||
|
||||
if reflect.DeepEqual(current, zero) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
if !tagOpts.Has("omitnested") {
|
||||
finalVal = s.nested(val)
|
||||
|
||||
v := reflect.ValueOf(val.Interface())
|
||||
if v.Kind() == reflect.Ptr {
|
||||
v = v.Elem()
|
||||
}
|
||||
|
||||
switch v.Kind() {
|
||||
case reflect.Map, reflect.Struct:
|
||||
isSubStruct = true
|
||||
}
|
||||
} else {
|
||||
finalVal = val.Interface()
|
||||
}
|
||||
|
||||
if tagOpts.Has("string") {
|
||||
s, ok := val.Interface().(fmt.Stringer)
|
||||
if ok {
|
||||
out[name] = s.String()
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if isSubStruct && (tagOpts.Has("flatten")) {
|
||||
for k := range finalVal.(map[string]interface{}) {
|
||||
out[k] = finalVal.(map[string]interface{})[k]
|
||||
}
|
||||
} else {
|
||||
out[name] = finalVal
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Values converts the given s struct's field values to a []interface{}. A
|
||||
// struct tag with the content of "-" ignores the that particular field.
|
||||
// Example:
|
||||
//
|
||||
// // Field is ignored by this package.
|
||||
// Field int `structs:"-"`
|
||||
//
|
||||
// A value with the option of "omitnested" stops iterating further if the type
|
||||
// is a struct. Example:
|
||||
//
|
||||
// // Fields is not processed further by this package.
|
||||
// Field time.Time `structs:",omitnested"`
|
||||
// Field *http.Request `structs:",omitnested"`
|
||||
//
|
||||
// A tag value with the option of "omitempty" ignores that particular field and
|
||||
// is not added to the values if the field value is empty. Example:
|
||||
//
|
||||
// // Field is skipped if empty
|
||||
// Field string `structs:",omitempty"`
|
||||
//
|
||||
// Note that only exported fields of a struct can be accessed, non exported
|
||||
// fields will be neglected.
|
||||
func (s *Struct) Values() []interface{} {
|
||||
fields := s.structFields()
|
||||
|
||||
var t []interface{}
|
||||
|
||||
for _, field := range fields {
|
||||
val := s.value.FieldByName(field.Name)
|
||||
|
||||
_, tagOpts := parseTag(field.Tag.Get(s.TagName))
|
||||
|
||||
// if the value is a zero value and the field is marked as omitempty do
|
||||
// not include
|
||||
if tagOpts.Has("omitempty") {
|
||||
zero := reflect.Zero(val.Type()).Interface()
|
||||
current := val.Interface()
|
||||
|
||||
if reflect.DeepEqual(current, zero) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
if tagOpts.Has("string") {
|
||||
s, ok := val.Interface().(fmt.Stringer)
|
||||
if ok {
|
||||
t = append(t, s.String())
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if IsStruct(val.Interface()) && !tagOpts.Has("omitnested") {
|
||||
// look out for embedded structs, and convert them to a
|
||||
// []interface{} to be added to the final values slice
|
||||
t = append(t, Values(val.Interface())...)
|
||||
} else {
|
||||
t = append(t, val.Interface())
|
||||
}
|
||||
}
|
||||
|
||||
return t
|
||||
}
|
||||
|
||||
// Fields returns a slice of Fields. A struct tag with the content of "-"
|
||||
// ignores the checking of that particular field. Example:
|
||||
//
|
||||
// // Field is ignored by this package.
|
||||
// Field bool `structs:"-"`
|
||||
//
|
||||
// It panics if s's kind is not struct.
|
||||
func (s *Struct) Fields() []*Field {
|
||||
return getFields(s.value, s.TagName)
|
||||
}
|
||||
|
||||
// Names returns a slice of field names. A struct tag with the content of "-"
|
||||
// ignores the checking of that particular field. Example:
|
||||
//
|
||||
// // Field is ignored by this package.
|
||||
// Field bool `structs:"-"`
|
||||
//
|
||||
// It panics if s's kind is not struct.
|
||||
func (s *Struct) Names() []string {
|
||||
fields := getFields(s.value, s.TagName)
|
||||
|
||||
names := make([]string, len(fields))
|
||||
|
||||
for i, field := range fields {
|
||||
names[i] = field.Name()
|
||||
}
|
||||
|
||||
return names
|
||||
}
|
||||
|
||||
func getFields(v reflect.Value, tagName string) []*Field {
|
||||
if v.Kind() == reflect.Ptr {
|
||||
v = v.Elem()
|
||||
}
|
||||
|
||||
t := v.Type()
|
||||
|
||||
var fields []*Field
|
||||
|
||||
for i := 0; i < t.NumField(); i++ {
|
||||
field := t.Field(i)
|
||||
|
||||
if tag := field.Tag.Get(tagName); tag == "-" {
|
||||
continue
|
||||
}
|
||||
|
||||
f := &Field{
|
||||
field: field,
|
||||
value: v.FieldByName(field.Name),
|
||||
}
|
||||
|
||||
fields = append(fields, f)
|
||||
|
||||
}
|
||||
|
||||
return fields
|
||||
}
|
||||
|
||||
// Field returns a new Field struct that provides several high level functions
|
||||
// around a single struct field entity. It panics if the field is not found.
|
||||
func (s *Struct) Field(name string) *Field {
|
||||
f, ok := s.FieldOk(name)
|
||||
if !ok {
|
||||
panic("field not found")
|
||||
}
|
||||
|
||||
return f
|
||||
}
|
||||
|
||||
// FieldOk returns a new Field struct that provides several high level functions
|
||||
// around a single struct field entity. The boolean returns true if the field
|
||||
// was found.
|
||||
func (s *Struct) FieldOk(name string) (*Field, bool) {
|
||||
t := s.value.Type()
|
||||
|
||||
field, ok := t.FieldByName(name)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
return &Field{
|
||||
field: field,
|
||||
value: s.value.FieldByName(name),
|
||||
defaultTag: s.TagName,
|
||||
}, true
|
||||
}
|
||||
|
||||
// IsZero returns true if all fields in a struct is a zero value (not
|
||||
// initialized) A struct tag with the content of "-" ignores the checking of
|
||||
// that particular field. Example:
|
||||
//
|
||||
// // Field is ignored by this package.
|
||||
// Field bool `structs:"-"`
|
||||
//
|
||||
// A value with the option of "omitnested" stops iterating further if the type
|
||||
// is a struct. Example:
|
||||
//
|
||||
// // Field is not processed further by this package.
|
||||
// Field time.Time `structs:"myName,omitnested"`
|
||||
// Field *http.Request `structs:",omitnested"`
|
||||
//
|
||||
// Note that only exported fields of a struct can be accessed, non exported
|
||||
// fields will be neglected. It panics if s's kind is not struct.
|
||||
func (s *Struct) IsZero() bool {
|
||||
fields := s.structFields()
|
||||
|
||||
for _, field := range fields {
|
||||
val := s.value.FieldByName(field.Name)
|
||||
|
||||
_, tagOpts := parseTag(field.Tag.Get(s.TagName))
|
||||
|
||||
if IsStruct(val.Interface()) && !tagOpts.Has("omitnested") {
|
||||
ok := IsZero(val.Interface())
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
// zero value of the given field, such as "" for string, 0 for int
|
||||
zero := reflect.Zero(val.Type()).Interface()
|
||||
|
||||
// current value of the given field
|
||||
current := val.Interface()
|
||||
|
||||
if !reflect.DeepEqual(current, zero) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// HasZero returns true if a field in a struct is not initialized (zero value).
|
||||
// A struct tag with the content of "-" ignores the checking of that particular
|
||||
// field. Example:
|
||||
//
|
||||
// // Field is ignored by this package.
|
||||
// Field bool `structs:"-"`
|
||||
//
|
||||
// A value with the option of "omitnested" stops iterating further if the type
|
||||
// is a struct. Example:
|
||||
//
|
||||
// // Field is not processed further by this package.
|
||||
// Field time.Time `structs:"myName,omitnested"`
|
||||
// Field *http.Request `structs:",omitnested"`
|
||||
//
|
||||
// Note that only exported fields of a struct can be accessed, non exported
|
||||
// fields will be neglected. It panics if s's kind is not struct.
|
||||
func (s *Struct) HasZero() bool {
|
||||
fields := s.structFields()
|
||||
|
||||
for _, field := range fields {
|
||||
val := s.value.FieldByName(field.Name)
|
||||
|
||||
_, tagOpts := parseTag(field.Tag.Get(s.TagName))
|
||||
|
||||
if IsStruct(val.Interface()) && !tagOpts.Has("omitnested") {
|
||||
ok := HasZero(val.Interface())
|
||||
if ok {
|
||||
return true
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
// zero value of the given field, such as "" for string, 0 for int
|
||||
zero := reflect.Zero(val.Type()).Interface()
|
||||
|
||||
// current value of the given field
|
||||
current := val.Interface()
|
||||
|
||||
if reflect.DeepEqual(current, zero) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// Name returns the structs's type name within its package. For more info refer
|
||||
// to Name() function.
|
||||
func (s *Struct) Name() string {
|
||||
return s.value.Type().Name()
|
||||
}
|
||||
|
||||
// structFields returns the exported struct fields for a given s struct. This
|
||||
// is a convenient helper method to avoid duplicate code in some of the
|
||||
// functions.
|
||||
func (s *Struct) structFields() []reflect.StructField {
|
||||
t := s.value.Type()
|
||||
|
||||
var f []reflect.StructField
|
||||
|
||||
for i := 0; i < t.NumField(); i++ {
|
||||
field := t.Field(i)
|
||||
// we can't access the value of unexported fields
|
||||
if field.PkgPath != "" {
|
||||
continue
|
||||
}
|
||||
|
||||
// don't check if it's omitted
|
||||
if tag := field.Tag.Get(s.TagName); tag == "-" {
|
||||
continue
|
||||
}
|
||||
|
||||
f = append(f, field)
|
||||
}
|
||||
|
||||
return f
|
||||
}
|
||||
|
||||
func strctVal(s interface{}) reflect.Value {
|
||||
v := reflect.ValueOf(s)
|
||||
|
||||
// if pointer get the underlying element≤
|
||||
for v.Kind() == reflect.Ptr {
|
||||
v = v.Elem()
|
||||
}
|
||||
|
||||
if v.Kind() != reflect.Struct {
|
||||
panic("not struct")
|
||||
}
|
||||
|
||||
return v
|
||||
}
|
||||
|
||||
// Map converts the given struct to a map[string]interface{}. For more info
|
||||
// refer to Struct types Map() method. It panics if s's kind is not struct.
|
||||
func Map(s interface{}) map[string]interface{} {
|
||||
return New(s).Map()
|
||||
}
|
||||
|
||||
// FillMap is the same as Map. Instead of returning the output, it fills the
|
||||
// given map.
|
||||
func FillMap(s interface{}, out map[string]interface{}) {
|
||||
New(s).FillMap(out)
|
||||
}
|
||||
|
||||
// Values converts the given struct to a []interface{}. For more info refer to
|
||||
// Struct types Values() method. It panics if s's kind is not struct.
|
||||
func Values(s interface{}) []interface{} {
|
||||
return New(s).Values()
|
||||
}
|
||||
|
||||
// Fields returns a slice of *Field. For more info refer to Struct types
|
||||
// Fields() method. It panics if s's kind is not struct.
|
||||
func Fields(s interface{}) []*Field {
|
||||
return New(s).Fields()
|
||||
}
|
||||
|
||||
// Names returns a slice of field names. For more info refer to Struct types
|
||||
// Names() method. It panics if s's kind is not struct.
|
||||
func Names(s interface{}) []string {
|
||||
return New(s).Names()
|
||||
}
|
||||
|
||||
// IsZero returns true if all fields is equal to a zero value. For more info
|
||||
// refer to Struct types IsZero() method. It panics if s's kind is not struct.
|
||||
func IsZero(s interface{}) bool {
|
||||
return New(s).IsZero()
|
||||
}
|
||||
|
||||
// HasZero returns true if any field is equal to a zero value. For more info
|
||||
// refer to Struct types HasZero() method. It panics if s's kind is not struct.
|
||||
func HasZero(s interface{}) bool {
|
||||
return New(s).HasZero()
|
||||
}
|
||||
|
||||
// IsStruct returns true if the given variable is a struct or a pointer to
|
||||
// struct.
|
||||
func IsStruct(s interface{}) bool {
|
||||
v := reflect.ValueOf(s)
|
||||
if v.Kind() == reflect.Ptr {
|
||||
v = v.Elem()
|
||||
}
|
||||
|
||||
// uninitialized zero value of a struct
|
||||
if v.Kind() == reflect.Invalid {
|
||||
return false
|
||||
}
|
||||
|
||||
return v.Kind() == reflect.Struct
|
||||
}
|
||||
|
||||
// Name returns the structs's type name within its package. It returns an
|
||||
// empty string for unnamed types. It panics if s's kind is not struct.
|
||||
func Name(s interface{}) string {
|
||||
return New(s).Name()
|
||||
}
|
||||
|
||||
// nested retrieves recursively all types for the given value and returns the
|
||||
// nested value.
|
||||
func (s *Struct) nested(val reflect.Value) interface{} {
|
||||
var finalVal interface{}
|
||||
|
||||
v := reflect.ValueOf(val.Interface())
|
||||
if v.Kind() == reflect.Ptr {
|
||||
v = v.Elem()
|
||||
}
|
||||
|
||||
switch v.Kind() {
|
||||
case reflect.Struct:
|
||||
n := New(val.Interface())
|
||||
n.TagName = s.TagName
|
||||
m := n.Map()
|
||||
|
||||
// do not add the converted value if there are no exported fields, ie:
|
||||
// time.Time
|
||||
if len(m) == 0 {
|
||||
finalVal = val.Interface()
|
||||
} else {
|
||||
finalVal = m
|
||||
}
|
||||
case reflect.Map:
|
||||
// get the element type of the map
|
||||
mapElem := val.Type()
|
||||
switch val.Type().Kind() {
|
||||
case reflect.Ptr, reflect.Array, reflect.Map,
|
||||
reflect.Slice, reflect.Chan:
|
||||
mapElem = val.Type().Elem()
|
||||
if mapElem.Kind() == reflect.Ptr {
|
||||
mapElem = mapElem.Elem()
|
||||
}
|
||||
}
|
||||
|
||||
// only iterate over struct types, ie: map[string]StructType,
|
||||
// map[string][]StructType,
|
||||
if mapElem.Kind() == reflect.Struct ||
|
||||
(mapElem.Kind() == reflect.Slice &&
|
||||
mapElem.Elem().Kind() == reflect.Struct) {
|
||||
m := make(map[string]interface{}, val.Len())
|
||||
for _, k := range val.MapKeys() {
|
||||
m[k.String()] = s.nested(val.MapIndex(k))
|
||||
}
|
||||
finalVal = m
|
||||
break
|
||||
}
|
||||
|
||||
// TODO(arslan): should this be optional?
|
||||
finalVal = val.Interface()
|
||||
case reflect.Slice, reflect.Array:
|
||||
if val.Type().Kind() == reflect.Interface {
|
||||
finalVal = val.Interface()
|
||||
break
|
||||
}
|
||||
|
||||
// TODO(arslan): should this be optional?
|
||||
// do not iterate of non struct types, just pass the value. Ie: []int,
|
||||
// []string, co... We only iterate further if it's a struct.
|
||||
// i.e []foo or []*foo
|
||||
if val.Type().Elem().Kind() != reflect.Struct &&
|
||||
!(val.Type().Elem().Kind() == reflect.Ptr &&
|
||||
val.Type().Elem().Elem().Kind() == reflect.Struct) {
|
||||
finalVal = val.Interface()
|
||||
break
|
||||
}
|
||||
|
||||
slices := make([]interface{}, val.Len())
|
||||
for x := 0; x < val.Len(); x++ {
|
||||
slices[x] = s.nested(val.Index(x))
|
||||
}
|
||||
finalVal = slices
|
||||
default:
|
||||
finalVal = val.Interface()
|
||||
}
|
||||
|
||||
return finalVal
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package structs
|
||||
|
||||
import "strings"
|
||||
|
||||
// tagOptions contains a slice of tag options
|
||||
type tagOptions []string
|
||||
|
||||
// Has returns true if the given option is available in tagOptions
|
||||
func (t tagOptions) Has(opt string) bool {
|
||||
for _, tagOpt := range t {
|
||||
if tagOpt == opt {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// parseTag splits a struct field's tag into its name and a list of options
|
||||
// which comes after a name. A tag is in the form of: "name,option1,option2".
|
||||
// The name can be neglectected.
|
||||
func parseTag(tag string) (string, tagOptions) {
|
||||
// tag is one of followings:
|
||||
// ""
|
||||
// "name"
|
||||
// "name,opt"
|
||||
// "name,opt,opt2"
|
||||
// ",opt"
|
||||
|
||||
res := strings.Split(tag, ",")
|
||||
return res[0], res[1:]
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014 Manuel Martínez-Almeida
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue