From b994d2086710a6a66cc1491fd9eb91debef37b73 Mon Sep 17 00:00:00 2001 From: Michael Rykov Date: Thu, 2 Dec 2021 23:41:22 +0800 Subject: [PATCH] encoding: publicly expose identifier.{MIB,Interface} --- encoding/ianaindex/ianaindex.go | 9 +++++++++ encoding/ianaindex/ianaindex_test.go | 15 +++++++++++++++ encoding/identifier/identifier.go | 12 ++++++++++++ 3 files changed, 36 insertions(+) create mode 100644 encoding/identifier/identifier.go diff --git a/encoding/ianaindex/ianaindex.go b/encoding/ianaindex/ianaindex.go index f4b18875c..4b17b35b1 100644 --- a/encoding/ianaindex/ianaindex.go +++ b/encoding/ianaindex/ianaindex.go @@ -104,6 +104,15 @@ func (x *Index) Name(e encoding.Encoding) (string, error) { return x.names(v), nil } +// FindMIB searches encoding by MIBenum identifier +func (x *Index) FindMIB(mib identifier.MIB) (encoding.Encoding, error) { + v := findMIB(x.toMIB, mib) + if v == -1 { + return nil, errUnsupported + } + return x.enc[v], nil +} + // TODO: the coverage of this index is rather spotty. Allowing users to set // encodings would allow: // - users to increase coverage diff --git a/encoding/ianaindex/ianaindex_test.go b/encoding/ianaindex/ianaindex_test.go index d545fcf23..49b68fce1 100644 --- a/encoding/ianaindex/ianaindex_test.go +++ b/encoding/ianaindex/ianaindex_test.go @@ -105,6 +105,21 @@ func TestEncoding(t *testing.T) { if got, err := tc.index.Name(enc); got != tc.canonical { t.Errorf("%d: Name(Encoding(%q)) = %q; want %q (%v)", i, tc.name, got, tc.canonical, err) } + + id, ok := enc.(identifier.Interface) + if !ok { + t.Errorf("%d: encoding %q has no ID", i, tc.name) + } + mib, _ := id.ID() + if mib == 0 { + t.Errorf("%d: encoding %q returned 0 MIB enum", i, tc.name) + } + mibEnc, err := tc.index.FindMIB(mib) + if err != nil { + t.Errorf("%d: FindMIB error %q", i, err) + } else if mibEnc != enc { + t.Errorf("%d: FindMIB did not match encoding", i) + } } } diff --git a/encoding/identifier/identifier.go b/encoding/identifier/identifier.go new file mode 100644 index 000000000..a31413a39 --- /dev/null +++ b/encoding/identifier/identifier.go @@ -0,0 +1,12 @@ +// Copyright 2015 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. + +package identifier + +import ( + "golang.org/x/text/encoding/internal/identifier" +) + +type Interface = identifier.Interface +type MIB = identifier.MIB