PageRenderTime 26ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/string.go

http://github.com/qur/gopy
Go | 89 lines | 71 code | 13 blank | 5 comment | 22 complexity | e78c7e02f0880a660ef741223f3424e7 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. // Copyright 2011 Julian Phillips. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package py
  5. // #include "utils.h"
  6. import "C"
  7. import "unsafe"
  8. type String struct {
  9. AbstractObject
  10. SequenceProtocol
  11. o C.PyStringObject
  12. }
  13. // StringType is the Type object that represents the String type.
  14. var StringType = (*Type)(unsafe.Pointer(&C.PyString_Type))
  15. func stringCheck(obj Object) bool {
  16. return C.stringCheck(c(obj)) != 0
  17. }
  18. func newString(obj *C.PyObject) *String {
  19. return (*String)(unsafe.Pointer(obj))
  20. }
  21. func NewString(s string) (*String, error) {
  22. cs := C.CString(s)
  23. defer C.free(unsafe.Pointer(cs))
  24. ret := C.PyString_FromString(cs)
  25. if ret == nil {
  26. return nil, exception()
  27. }
  28. return newString(ret), nil
  29. }
  30. func (s *String) String() string {
  31. if s == nil {
  32. return "<nil>"
  33. }
  34. ret := C.PyString_AsString(c(s))
  35. if ret == nil {
  36. panic(exception())
  37. }
  38. return C.GoString(ret)
  39. }
  40. func (s *String) Format(args *Tuple) (*String, error) {
  41. ret := C.PyString_Format(c(s), c(args))
  42. if ret == nil {
  43. return nil, exception()
  44. }
  45. return newString(ret), nil
  46. }
  47. func (s *String) Size() int64 {
  48. ret := C.PyString_Size(c(s))
  49. return int64(ret)
  50. }
  51. func (s *String) Decode(encoding, errors string) (Object, error) {
  52. var cEncoding, cErrors *C.char
  53. if encoding == "" {
  54. cEncoding = C.CString(encoding)
  55. defer C.free(unsafe.Pointer(cEncoding))
  56. }
  57. if errors != "" {
  58. cErrors = C.CString(errors)
  59. defer C.free(unsafe.Pointer(cErrors))
  60. }
  61. ret := C.PyString_AsDecodedObject(c(s), cEncoding, cErrors)
  62. return obj2ObjErr(ret)
  63. }
  64. func (s *String) Encode(encoding, errors string) (Object, error) {
  65. var cEncoding, cErrors *C.char
  66. if encoding == "" {
  67. cEncoding = C.CString(encoding)
  68. defer C.free(unsafe.Pointer(cEncoding))
  69. }
  70. if errors != "" {
  71. cErrors = C.CString(errors)
  72. defer C.free(unsafe.Pointer(cErrors))
  73. }
  74. ret := C.PyString_AsEncodedObject(c(s), cEncoding, cErrors)
  75. return obj2ObjErr(ret)
  76. }