PageRenderTime 55ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/DICK.B1/IronPython/Runtime/Operations/StringOps.cs

https://bitbucket.org/williamybs/uidipythontool
C# | 2678 lines | 2322 code | 266 blank | 90 comment | 402 complexity | 13d29dd77800c801907fbcb1c1b4590f MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. /* ****************************************************************************
  2. *
  3. * Copyright (c) Microsoft Corporation.
  4. *
  5. * This source code is subject to terms and conditions of the Microsoft Public License. A
  6. * copy of the license can be found in the License.html file at the root of this distribution. If
  7. * you cannot locate the Microsoft Public License, please send an email to
  8. * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
  9. * by the terms of the Microsoft Public License.
  10. *
  11. * You must not remove this notice, or any other, from this software.
  12. *
  13. *
  14. * ***************************************************************************/
  15. using System;
  16. using System.Collections;
  17. using System.Collections.Generic;
  18. using System.Diagnostics;
  19. using System.Globalization;
  20. using System.Reflection;
  21. using System.Runtime.InteropServices;
  22. using System.Text;
  23. using IronPython.Runtime.Exceptions;
  24. using IronPython.Runtime.Types;
  25. using Microsoft.Scripting;
  26. using Microsoft.Scripting.Runtime;
  27. using Microsoft.Scripting.Utils;
  28. #if CLR2
  29. using Microsoft.Scripting.Math;
  30. #else
  31. using System.Numerics;
  32. #endif
  33. using SpecialNameAttribute = System.Runtime.CompilerServices.SpecialNameAttribute;
  34. namespace IronPython.Runtime.Operations {
  35. /// <summary>
  36. /// ExtensibleString is the base class that is used for types the user defines
  37. /// that derive from string. It carries along with it the string's value and
  38. /// our converter recognizes it as a string.
  39. /// </summary>
  40. public class ExtensibleString : Extensible<string>, ICodeFormattable, IStructuralEquatable
  41. #if CLR2
  42. , IValueEquality
  43. #endif
  44. {
  45. public ExtensibleString() : base(String.Empty) { }
  46. public ExtensibleString(string self) : base(self) { }
  47. public override string ToString() {
  48. return Value;
  49. }
  50. #region ICodeFormattable Members
  51. public virtual string/*!*/ __repr__(CodeContext/*!*/ context) {
  52. return StringOps.Quote(Value);
  53. }
  54. #endregion
  55. [return: MaybeNotImplemented]
  56. public object __eq__(object other) {
  57. if (other is string || other is ExtensibleString || other is Bytes) {
  58. return ScriptingRuntimeHelpers.BooleanToObject(EqualsWorker(other));
  59. }
  60. return NotImplementedType.Value;
  61. }
  62. [return: MaybeNotImplemented]
  63. public object __ne__(object other) {
  64. if (other is string || other is ExtensibleString || other is Bytes) {
  65. return ScriptingRuntimeHelpers.BooleanToObject(!EqualsWorker(other));
  66. }
  67. return NotImplementedType.Value;
  68. }
  69. #region IValueEquality members
  70. #if CLR2
  71. int IValueEquality.GetValueHashCode() {
  72. return GetHashCode();
  73. }
  74. bool IValueEquality.ValueEquals(object other) {
  75. return EqualsWorker(other);
  76. }
  77. #endif
  78. #endregion
  79. #region IStructuralEquatable Members
  80. int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) {
  81. if (comparer is PythonContext.PythonEqualityComparer) {
  82. return GetHashCode();
  83. }
  84. return ((IStructuralEquatable)PythonTuple.MakeTuple(Value.ToCharArray())).GetHashCode(comparer);
  85. }
  86. bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) {
  87. if (comparer is PythonContext.PythonEqualityComparer) {
  88. return EqualsWorker(other);
  89. }
  90. ExtensibleString es = other as ExtensibleString;
  91. if (es != null) return EqualsWorker(es.Value, comparer);
  92. string os = other as string;
  93. if (os != null) return EqualsWorker(os, comparer);
  94. Bytes tempBytes = other as Bytes;
  95. if (tempBytes != null) return EqualsWorker(tempBytes.ToString(), comparer);
  96. return false;
  97. }
  98. private bool EqualsWorker(object other) {
  99. if (other == null) return false;
  100. ExtensibleString es = other as ExtensibleString;
  101. if (es != null) return Value == es.Value;
  102. string os = other as string;
  103. if (os != null) return Value == os;
  104. Bytes tempBytes = other as Bytes;
  105. if (tempBytes != null) return Value == tempBytes.ToString();
  106. return false;
  107. }
  108. private bool EqualsWorker(string/*!*/ other, IEqualityComparer comparer) {
  109. Debug.Assert(other != null);
  110. if (Value.Length != other.Length) {
  111. return false;
  112. } else if (Value.Length == 0) {
  113. // 2 empty strings are equal
  114. return true;
  115. }
  116. for (int i = 0; i < Value.Length; i++) {
  117. if (!comparer.Equals(Value[i], other[i])) {
  118. return false;
  119. }
  120. }
  121. return true;
  122. }
  123. #endregion
  124. #region ISequence Members
  125. public virtual object this[int index] {
  126. get { return ScriptingRuntimeHelpers.CharToString(Value[index]); }
  127. }
  128. public object this[Slice slice] {
  129. get { return StringOps.GetItem(Value, slice); }
  130. }
  131. public object __getslice__(int start, int stop) {
  132. return StringOps.__getslice__(Value, start, stop);
  133. }
  134. #endregion
  135. #region IPythonContainer Members
  136. public virtual int __len__() {
  137. return Value.Length;
  138. }
  139. public virtual bool __contains__(object value) {
  140. if (value is string) return Value.Contains((string)value);
  141. else if (value is ExtensibleString) return Value.Contains(((ExtensibleString)value).Value);
  142. throw PythonOps.TypeErrorForBadInstance("expected string, got {0}", value);
  143. }
  144. #endregion
  145. }
  146. /// <summary>
  147. /// StringOps is the static class that contains the methods defined on strings, i.e. 'abc'
  148. ///
  149. /// Here we define all of the methods that a Python user would see when doing dir('abc').
  150. /// If the user is running in a CLS aware context they will also see all of the methods
  151. /// defined in the CLS System.String type.
  152. /// </summary>
  153. public static class StringOps {
  154. internal const int LowestUnicodeValue = 0x7f;
  155. private static readonly char[] Whitespace = new char[] { ' ', '\t', '\n', '\r', '\f' };
  156. internal static object FastNew(CodeContext/*!*/ context, object x) {
  157. if (x == null) {
  158. return "None";
  159. }
  160. if (x is string) {
  161. // check ascii
  162. return CheckAsciiString(context, (string)x);
  163. }
  164. // we don't invoke PythonOps.StringRepr here because we want to return the
  165. // Extensible<string> directly back if that's what we received from __str__.
  166. object value = PythonContext.InvokeUnaryOperator(context, UnaryOperators.String, x);
  167. if (value is string || value is Extensible<string>) {
  168. return value;
  169. }
  170. throw PythonOps.TypeError("expected str, got {0} from __str__", DynamicHelpers.GetPythonType(value).Name);
  171. }
  172. internal static string FastNewUnicode(CodeContext context, object value, object encoding, object errors) {
  173. string strErrors = errors as string;
  174. if (strErrors == null) {
  175. throw PythonOps.TypeError("unicode() argument 3 must be string, not {0}", PythonTypeOps.GetName(errors));
  176. }
  177. if (value != null) {
  178. string strValue = value as string;
  179. if (strValue != null) {
  180. return StringOps.RawDecode(context, strValue, encoding, strErrors);
  181. }
  182. Extensible<string> es = value as Extensible<string>;
  183. if (es != null) {
  184. return StringOps.RawDecode(context, es.Value, encoding, strErrors);
  185. }
  186. Bytes bytes = value as Bytes;
  187. if (bytes != null) {
  188. return StringOps.RawDecode(context, bytes.ToString(), encoding, strErrors);
  189. }
  190. PythonBuffer buffer = value as PythonBuffer;
  191. if (buffer != null) {
  192. return StringOps.RawDecode(context, buffer.ToString(), encoding, strErrors);
  193. }
  194. }
  195. throw PythonOps.TypeError("coercing to Unicode: need string or buffer, {0} found", PythonTypeOps.GetName(value));
  196. }
  197. internal static object FastNewUnicode(CodeContext context, object value, object encoding) {
  198. return FastNewUnicode(context, value, encoding, "strict");
  199. }
  200. internal static object FastNewUnicode(CodeContext context, object value) {
  201. if (value == null) {
  202. return "None";
  203. } else if (value is string) {
  204. return value;
  205. }
  206. object res;
  207. OldInstance oi = value as OldInstance;
  208. if (oi != null &&
  209. (oi.TryGetBoundCustomMember(context, "__unicode__", out res) || oi.TryGetBoundCustomMember(context, "__str__", out res))) {
  210. res = context.LanguageContext.Call(context, res);
  211. if (res is string || res is Extensible<string>) {
  212. return res;
  213. }
  214. throw PythonOps.TypeError("coercing to Unicode: expected string, got {0}", PythonTypeOps.GetName(value));
  215. }
  216. if (PythonTypeOps.TryInvokeUnaryOperator(context, value, "__unicode__", out res) ||
  217. PythonTypeOps.TryInvokeUnaryOperator(context, value, "__str__", out res)) {
  218. if (res is string || res is Extensible<string>) {
  219. return res;
  220. }
  221. throw PythonOps.TypeError("coercing to Unicode: expected string, got {0}", PythonTypeOps.GetName(value));
  222. }
  223. return FastNewUnicode(context, value, context.LanguageContext.DefaultEncoding.WebName, "strict");
  224. }
  225. private static object CheckAsciiString(CodeContext context, string s) {
  226. for (int i = 0; i < s.Length; i++) {
  227. if (s[i] > '\x80')
  228. return StringOps.__new__(
  229. context,
  230. (PythonType)DynamicHelpers.GetPythonTypeFromType(typeof(String)),
  231. s,
  232. null,
  233. "strict"
  234. );
  235. }
  236. return s;
  237. }
  238. #region Python Constructors
  239. [StaticExtensionMethod]
  240. public static object __new__(CodeContext/*!*/ context, PythonType cls) {
  241. if (cls == TypeCache.String) {
  242. return "";
  243. } else {
  244. return cls.CreateInstance(context);
  245. }
  246. }
  247. [StaticExtensionMethod]
  248. public static object __new__(CodeContext/*!*/ context, PythonType cls, object @object) {
  249. if (cls == TypeCache.String) {
  250. return FastNew(context, @object);
  251. } else {
  252. return cls.CreateInstance(context, __new__(context, TypeCache.String, @object));
  253. }
  254. }
  255. [StaticExtensionMethod]
  256. public static object __new__(CodeContext/*!*/ context, PythonType cls, [NotNull]string @object) {
  257. if (cls == TypeCache.String) {
  258. return CheckAsciiString(context, @object);
  259. } else {
  260. return cls.CreateInstance(context, @object);
  261. }
  262. }
  263. [StaticExtensionMethod]
  264. public static object __new__(CodeContext/*!*/ context, PythonType cls, [NotNull]ExtensibleString @object) {
  265. if (cls == TypeCache.String) {
  266. return FastNew(context, @object);
  267. } else {
  268. return cls.CreateInstance(context, __new__(context, TypeCache.String, @object));
  269. }
  270. }
  271. [StaticExtensionMethod]
  272. public static object __new__(CodeContext/*!*/ context, PythonType cls, char @object) {
  273. if (cls == TypeCache.String) {
  274. return CheckAsciiString(context, ScriptingRuntimeHelpers.CharToString(@object));
  275. } else {
  276. return cls.CreateInstance(context, __new__(context, TypeCache.String, @object));
  277. }
  278. }
  279. [StaticExtensionMethod]
  280. public static object __new__(CodeContext/*!*/ context, PythonType cls, [NotNull]BigInteger @object) {
  281. if (cls == TypeCache.String) {
  282. return @object.ToString();
  283. } else {
  284. return cls.CreateInstance(context, __new__(context, TypeCache.String, @object));
  285. }
  286. }
  287. [StaticExtensionMethod]
  288. public static object __new__(CodeContext/*!*/ context, PythonType cls, [NotNull]Extensible<BigInteger> @object) {
  289. if (cls == TypeCache.String) {
  290. return FastNew(context, @object);
  291. } else {
  292. return cls.CreateInstance(context, __new__(context, TypeCache.String, @object));
  293. }
  294. }
  295. [StaticExtensionMethod]
  296. public static object __new__(CodeContext/*!*/ context, PythonType cls, int @object) {
  297. if (cls == TypeCache.String) {
  298. return @object.ToString();
  299. } else {
  300. return cls.CreateInstance(context, __new__(context, TypeCache.String, @object));
  301. }
  302. }
  303. [StaticExtensionMethod]
  304. public static object __new__(CodeContext/*!*/ context, PythonType cls, bool @object) {
  305. if (cls == TypeCache.String) {
  306. return @object.ToString();
  307. } else {
  308. return cls.CreateInstance(context, __new__(context, TypeCache.String, @object));
  309. }
  310. }
  311. [StaticExtensionMethod]
  312. public static object __new__(CodeContext/*!*/ context, PythonType cls, double @object) {
  313. if (cls == TypeCache.String) {
  314. return DoubleOps.__str__(context, @object);
  315. } else {
  316. return cls.CreateInstance(context, __new__(context, TypeCache.String, @object));
  317. }
  318. }
  319. [StaticExtensionMethod]
  320. public static object __new__(CodeContext/*!*/ context, PythonType cls, Extensible<double> @object) {
  321. if (cls == TypeCache.String) {
  322. return FastNew(context, @object);
  323. } else {
  324. return cls.CreateInstance(context, __new__(context, TypeCache.String, @object));
  325. }
  326. }
  327. [StaticExtensionMethod]
  328. public static object __new__(CodeContext/*!*/ context, PythonType cls, float @object) {
  329. if (cls == TypeCache.String) {
  330. return SingleOps.__str__(context, @object);
  331. } else {
  332. return cls.CreateInstance(context, __new__(context, TypeCache.String, @object));
  333. }
  334. }
  335. [StaticExtensionMethod]
  336. public static object __new__(CodeContext/*!*/ context, PythonType cls,
  337. object @string,
  338. [DefaultParameterValue(null)] string encoding,
  339. [DefaultParameterValue("strict")] string errors) {
  340. string str = @string as string;
  341. if (str == null) throw PythonOps.TypeError("converting to unicode: need string, got {0}", DynamicHelpers.GetPythonType(@string).Name);
  342. if (cls == TypeCache.String) {
  343. return decode(context, str, encoding ?? PythonContext.GetContext(context).GetDefaultEncodingName(), errors);
  344. } else {
  345. return cls.CreateInstance(context, __new__(context, TypeCache.String, str, encoding, errors));
  346. }
  347. }
  348. #endregion
  349. #region Python __ methods
  350. public static bool __contains__(string s, string item) {
  351. return s.Contains(item);
  352. }
  353. public static bool __contains__(string s, char item) {
  354. return s.IndexOf(item) != -1;
  355. }
  356. public static string __format__(CodeContext/*!*/ context, string self, string formatSpec) {
  357. return ObjectOps.__format__(context, self, formatSpec);
  358. }
  359. public static int __len__(string s) {
  360. return s.Length;
  361. }
  362. [SpecialName]
  363. public static string GetItem(string s, int index) {
  364. return ScriptingRuntimeHelpers.CharToString(s[PythonOps.FixIndex(index, s.Length)]);
  365. }
  366. [SpecialName]
  367. public static string GetItem(string s, object index) {
  368. return GetItem(s, Converter.ConvertToIndex(index));
  369. }
  370. [SpecialName]
  371. public static string GetItem(string s, Slice slice) {
  372. if (slice == null) throw PythonOps.TypeError("string indices must be slices or integers");
  373. int start, stop, step;
  374. slice.indices(s.Length, out start, out stop, out step);
  375. if (step == 1) {
  376. return stop > start ? s.Substring(start, stop - start) : String.Empty;
  377. } else {
  378. int index = 0;
  379. char[] newData;
  380. if (step > 0) {
  381. if (start > stop) return String.Empty;
  382. int icnt = (stop - start + step - 1) / step;
  383. newData = new char[icnt];
  384. for (int i = start; i < stop; i += step) {
  385. newData[index++] = s[i];
  386. }
  387. } else {
  388. if (start < stop) return String.Empty;
  389. int icnt = (stop - start + step + 1) / step;
  390. newData = new char[icnt];
  391. for (int i = start; i > stop; i += step) {
  392. newData[index++] = s[i];
  393. }
  394. }
  395. return new string(newData);
  396. }
  397. }
  398. public static string __getslice__(string self, int x, int y) {
  399. Slice.FixSliceArguments(self.Length, ref x, ref y);
  400. if (x >= y) return String.Empty;
  401. return self.Substring(x, y - x);
  402. }
  403. #endregion
  404. #region Public Python methods
  405. /// <summary>
  406. /// Returns a copy of this string converted to uppercase
  407. /// </summary>
  408. public static string capitalize(this string self) {
  409. if (self.Length == 0) return self;
  410. return Char.ToUpper(self[0], CultureInfo.InvariantCulture) + self.Substring(1).ToLower(CultureInfo.InvariantCulture);
  411. }
  412. // default fillchar (padding char) is a space
  413. public static string center(this string self, int width) {
  414. return center(self, width, ' ');
  415. }
  416. public static string center(this string self, int width, char fillchar) {
  417. int spaces = width - self.Length;
  418. if (spaces <= 0) return self;
  419. StringBuilder ret = new StringBuilder(width);
  420. ret.Append(fillchar, spaces / 2);
  421. ret.Append(self);
  422. ret.Append(fillchar, (spaces + 1) / 2);
  423. return ret.ToString();
  424. }
  425. public static int count(this string self, string sub) {
  426. return count(self, sub, 0, self.Length);
  427. }
  428. public static int count(this string self, string sub, int start) {
  429. return count(self, sub, start, self.Length);
  430. }
  431. public static int count(this string self, string ssub, int start, int end) {
  432. if (ssub == null) throw PythonOps.TypeError("expected string for 'sub' argument, got NoneType");
  433. if (start > self.Length) {
  434. return 0;
  435. }
  436. start = PythonOps.FixSliceIndex(start, self.Length);
  437. end = PythonOps.FixSliceIndex(end, self.Length);
  438. if (ssub.Length == 0) {
  439. return Math.Max((end - start) + 1, 0);
  440. }
  441. int count = 0;
  442. CompareInfo c = CultureInfo.InvariantCulture.CompareInfo;
  443. while (true) {
  444. if (end <= start) break;
  445. int index = c.IndexOf(self, ssub, start, end - start, CompareOptions.Ordinal);
  446. if (index == -1) break;
  447. count++;
  448. start = index + ssub.Length;
  449. }
  450. return count;
  451. }
  452. public static string decode(CodeContext/*!*/ context, string s) {
  453. return decode(context, s, Missing.Value, "strict");
  454. }
  455. public static string decode(CodeContext/*!*/ context, string s, [Optional]object encoding, [DefaultParameterValue("strict")]string errors) {
  456. return RawDecode(context, s, encoding, errors);
  457. }
  458. public static string encode(CodeContext/*!*/ context, string s, [Optional]object encoding, [DefaultParameterValue("strict")]string errors) {
  459. return RawEncode(context, s, encoding, errors);
  460. }
  461. private static string CastString(object o) {
  462. string res = o as string;
  463. if (res != null) {
  464. return res;
  465. }
  466. return ((Extensible<string>)o).Value;
  467. }
  468. internal static string AsString(object o) {
  469. string res = o as string;
  470. if (res != null) {
  471. return res;
  472. }
  473. Extensible<string> es = o as Extensible<string>;
  474. if (es != null) {
  475. return es.Value;
  476. }
  477. return null;
  478. }
  479. public static bool endswith(this string self, object suffix) {
  480. TryStringOrTuple(suffix);
  481. if (suffix is PythonTuple)
  482. return endswith(self, (PythonTuple)suffix);
  483. else
  484. return endswith(self, CastString(suffix));
  485. }
  486. public static bool endswith(this string self, object suffix, int start) {
  487. TryStringOrTuple(suffix);
  488. if (suffix is PythonTuple)
  489. return endswith(self, (PythonTuple)suffix, start);
  490. else
  491. return endswith(self, CastString(suffix), start);
  492. }
  493. public static bool endswith(this string self, object suffix, int start, int end) {
  494. TryStringOrTuple(suffix);
  495. if (suffix is PythonTuple)
  496. return endswith(self, (PythonTuple)suffix, start, end);
  497. else
  498. return endswith(self, CastString(suffix), start, end);
  499. }
  500. public static string expandtabs(string self) {
  501. return expandtabs(self, 8);
  502. }
  503. public static string expandtabs(this string self, int tabsize) {
  504. StringBuilder ret = new StringBuilder(self.Length * 2);
  505. string v = self;
  506. int col = 0;
  507. for (int i = 0; i < v.Length; i++) {
  508. char ch = v[i];
  509. switch (ch) {
  510. case '\n':
  511. case '\r': col = 0; ret.Append(ch); break;
  512. case '\t':
  513. if (tabsize > 0) {
  514. int tabs = tabsize - (col % tabsize);
  515. int existingSize = ret.Capacity;
  516. ret.Capacity = checked(existingSize + tabs);
  517. ret.Append(' ', tabs);
  518. col = 0;
  519. }
  520. break;
  521. default:
  522. col++;
  523. ret.Append(ch);
  524. break;
  525. }
  526. }
  527. return ret.ToString();
  528. }
  529. public static int find(this string self, string sub) {
  530. if (sub == null) throw PythonOps.TypeError("expected string, got NoneType");
  531. if (sub.Length == 1) return self.IndexOf(sub[0]);
  532. CompareInfo c = CultureInfo.InvariantCulture.CompareInfo;
  533. return c.IndexOf(self, sub, CompareOptions.Ordinal);
  534. }
  535. public static int find(this string self, string sub, int start) {
  536. if (sub == null) throw PythonOps.TypeError("expected string, got NoneType");
  537. if (start > self.Length) return -1;
  538. start = PythonOps.FixSliceIndex(start, self.Length);
  539. CompareInfo c = CultureInfo.InvariantCulture.CompareInfo;
  540. return c.IndexOf(self, sub, start, CompareOptions.Ordinal);
  541. }
  542. public static int find(this string self, string sub, int start, int end) {
  543. if (sub == null) throw PythonOps.TypeError("expected string, got NoneType");
  544. if (start > self.Length) return -1;
  545. start = PythonOps.FixSliceIndex(start, self.Length);
  546. end = PythonOps.FixSliceIndex(end, self.Length);
  547. if (end < start) return -1;
  548. CompareInfo c = CultureInfo.InvariantCulture.CompareInfo;
  549. return c.IndexOf(self, sub, start, end - start, CompareOptions.Ordinal);
  550. }
  551. public static int find(this string self, string sub, object start, [DefaultParameterValue(null)]object end) {
  552. return find(self, sub, CheckIndex(start, 0), CheckIndex(end, self.Length));
  553. }
  554. public static int index(this string self, string sub) {
  555. if (sub == null) throw PythonOps.TypeError("expected string, got NoneType");
  556. return index(self, sub, 0, self.Length);
  557. }
  558. public static int index(this string self, string sub, int start) {
  559. if (sub == null) throw PythonOps.TypeError("expected string, got NoneType");
  560. return index(self, sub, start, self.Length);
  561. }
  562. public static int index(this string self, string sub, int start, int end) {
  563. if (sub == null) throw PythonOps.TypeError("expected string, got NoneType");
  564. int ret = find(self, sub, start, end);
  565. if (ret == -1) throw PythonOps.ValueError("substring {0} not found in {1}", sub, self);
  566. return ret;
  567. }
  568. public static int index(this string self, string sub, object start, [DefaultParameterValue(null)]object end) {
  569. return index(self, sub, CheckIndex(start, 0), CheckIndex(end, self.Length));
  570. }
  571. public static bool isalnum(this string self) {
  572. if (self.Length == 0) return false;
  573. string v = self;
  574. for (int i = v.Length - 1; i >= 0; i--) {
  575. if (!Char.IsLetterOrDigit(v, i)) return false;
  576. }
  577. return true;
  578. }
  579. public static bool isalpha(this string self) {
  580. if (self.Length == 0) return false;
  581. string v = self;
  582. for (int i = v.Length - 1; i >= 0; i--) {
  583. if (!Char.IsLetter(v, i)) return false;
  584. }
  585. return true;
  586. }
  587. public static bool isdigit(this string self) {
  588. if (self.Length == 0) return false;
  589. string v = self;
  590. for (int i = v.Length - 1; i >= 0; i--) {
  591. if (!Char.IsDigit(v, i)) return false;
  592. }
  593. return true;
  594. }
  595. public static bool isspace(this string self) {
  596. if (self.Length == 0) return false;
  597. string v = self;
  598. for (int i = v.Length - 1; i >= 0; i--) {
  599. if (!Char.IsWhiteSpace(v, i)) return false;
  600. }
  601. return true;
  602. }
  603. public static bool isdecimal(this string self) {
  604. return isnumeric(self);
  605. }
  606. public static bool isnumeric(this string self) {
  607. if (String.IsNullOrEmpty(self)) return false;
  608. foreach (char c in self) {
  609. if (!Char.IsDigit(c)) return false;
  610. }
  611. return true;
  612. }
  613. public static bool islower(this string self) {
  614. if (self.Length == 0) return false;
  615. string v = self;
  616. bool hasLower = false;
  617. for (int i = v.Length - 1; i >= 0; i--) {
  618. if (!hasLower && Char.IsLower(v, i)) hasLower = true;
  619. if (Char.IsUpper(v, i)) return false;
  620. }
  621. return hasLower;
  622. }
  623. public static bool isupper(this string self) {
  624. if (self.Length == 0) return false;
  625. string v = self;
  626. bool hasUpper = false;
  627. for (int i = v.Length - 1; i >= 0; i--) {
  628. if (!hasUpper && Char.IsUpper(v, i)) hasUpper = true;
  629. if (Char.IsLower(v, i)) return false;
  630. }
  631. return hasUpper;
  632. }
  633. /// <summary>
  634. /// return true if self is a titlecased string and there is at least one
  635. /// character in self; also, uppercase characters may only follow uncased
  636. /// characters (e.g. whitespace) and lowercase characters only cased ones.
  637. /// return false otherwise.
  638. /// </summary>
  639. public static bool istitle(this string self) {
  640. if (self == null || self.Length == 0) return false;
  641. string v = self;
  642. bool prevCharCased = false, currCharCased = false, containsUpper = false;
  643. for (int i = 0; i < v.Length; i++) {
  644. if (Char.IsUpper(v, i) || Char.GetUnicodeCategory(v, i) == UnicodeCategory.TitlecaseLetter) {
  645. containsUpper = true;
  646. if (prevCharCased)
  647. return false;
  648. else
  649. currCharCased = true;
  650. } else if (Char.IsLower(v, i))
  651. if (!prevCharCased)
  652. return false;
  653. else
  654. currCharCased = true;
  655. else
  656. currCharCased = false;
  657. prevCharCased = currCharCased;
  658. }
  659. // if we've gone through the whole string and haven't encountered any rule
  660. // violations but also haven't seen an Uppercased char, then this is not a
  661. // title e.g. '\n', all whitespace etc.
  662. return containsUpper;
  663. }
  664. public static bool isunicode(this string self) {
  665. foreach (char c in self) {
  666. if (c >= LowestUnicodeValue) return true;
  667. }
  668. return false;
  669. }
  670. /// <summary>
  671. /// Return a string which is the concatenation of the strings
  672. /// in the sequence seq. The separator between elements is the
  673. /// string providing this method
  674. /// </summary>
  675. public static string join(this string self, object sequence) {
  676. IEnumerator seq = PythonOps.GetEnumerator(sequence);
  677. if (!seq.MoveNext()) return "";
  678. // check if we have just a sequnce of just one value - if so just
  679. // return that value.
  680. object curVal = seq.Current;
  681. if (!seq.MoveNext()) return Converter.ConvertToString(curVal);
  682. StringBuilder ret = new StringBuilder();
  683. AppendJoin(curVal, 0, ret);
  684. int index = 1;
  685. do {
  686. ret.Append(self);
  687. AppendJoin(seq.Current, index, ret);
  688. index++;
  689. } while (seq.MoveNext());
  690. return ret.ToString();
  691. }
  692. public static string join(this string/*!*/ self, [NotNull]List/*!*/ sequence) {
  693. if (sequence.__len__() == 0) return String.Empty;
  694. lock (sequence) {
  695. if (sequence.__len__() == 1) {
  696. return Converter.ConvertToString(sequence[0]);
  697. }
  698. StringBuilder ret = new StringBuilder();
  699. AppendJoin(sequence._data[0], 0, ret);
  700. for (int i = 1; i < sequence._size; i++) {
  701. if (!String.IsNullOrEmpty(self)) {
  702. ret.Append(self);
  703. }
  704. AppendJoin(sequence._data[i], i, ret);
  705. }
  706. return ret.ToString();
  707. }
  708. }
  709. public static string ljust(this string self, int width) {
  710. return ljust(self, width, ' ');
  711. }
  712. public static string ljust(this string self, int width, char fillchar) {
  713. if (width < 0) return self;
  714. int spaces = width - self.Length;
  715. if (spaces <= 0) return self;
  716. StringBuilder ret = new StringBuilder(width);
  717. ret.Append(self);
  718. ret.Append(fillchar, spaces);
  719. return ret.ToString();
  720. }
  721. public static string lower(this string self) {
  722. return self.ToLower(CultureInfo.InvariantCulture);
  723. }
  724. public static string lstrip(this string self) {
  725. return self.TrimStart(Whitespace);
  726. }
  727. public static string lstrip(this string self, string chars) {
  728. if (chars == null) return lstrip(self);
  729. return self.TrimStart(chars.ToCharArray());
  730. }
  731. public static PythonTuple partition(this string self, string sep) {
  732. if (sep == null)
  733. throw PythonOps.TypeError("expected string, got NoneType");
  734. if (sep.Length == 0)
  735. throw PythonOps.ValueError("empty separator");
  736. object[] obj = new object[3] { "", "", "" };
  737. if (self.Length != 0) {
  738. int index = find(self, sep);
  739. if (index == -1) {
  740. obj[0] = self;
  741. } else {
  742. obj[0] = self.Substring(0, index);
  743. obj[1] = sep;
  744. obj[2] = self.Substring(index + sep.Length, self.Length - index - sep.Length);
  745. }
  746. }
  747. return new PythonTuple(obj);
  748. }
  749. private static string StringOrBuffer(object input) {
  750. string result = (input as string);
  751. if (result != null) {
  752. return result;
  753. }
  754. PythonBuffer buffer = (input as PythonBuffer);
  755. if (buffer != null) {
  756. return buffer.ToString();
  757. }
  758. throw PythonOps.TypeError("expected a character buffer object");
  759. }
  760. public static string replace(this string self, object old, object new_, [DefaultParameterValue(-1)]int maxsplit) {
  761. string oldString = StringOrBuffer(old);
  762. string newString = StringOrBuffer(new_);
  763. if (oldString.Length == 0) return ReplaceEmpty(self, newString, maxsplit);
  764. string v = self;
  765. int replacements = count(v, oldString);
  766. replacements = (maxsplit < 0 || maxsplit > replacements) ? replacements : maxsplit;
  767. int newLength = v.Length;
  768. newLength -= replacements * oldString.Length;
  769. newLength = checked(newLength + replacements * newString.Length);
  770. StringBuilder ret = new StringBuilder(newLength);
  771. int index;
  772. int start = 0;
  773. while (maxsplit != 0 && (index = v.IndexOf(oldString, start)) != -1) {
  774. ret.Append(v, start, index - start);
  775. ret.Append(newString);
  776. start = index + oldString.Length;
  777. maxsplit--;
  778. }
  779. ret.Append(v.Substring(start));
  780. return ret.ToString();
  781. }
  782. public static int rfind(this string self, string sub) {
  783. if (sub == null) throw PythonOps.TypeError("expected string, got NoneType");
  784. return rfind(self, sub, 0, self.Length);
  785. }
  786. public static int rfind(this string self, string sub, int start) {
  787. if (sub == null) throw PythonOps.TypeError("expected string, got NoneType");
  788. if (start > self.Length) return -1;
  789. return rfind(self, sub, start, self.Length);
  790. }
  791. public static int rfind(this string self, string sub, int start, int end) {
  792. if (sub == null) throw PythonOps.TypeError("expected string, got NoneType");
  793. if (start > self.Length) return -1;
  794. start = PythonOps.FixSliceIndex(start, self.Length);
  795. end = PythonOps.FixSliceIndex(end, self.Length);
  796. if (start > end) return -1; // can't possibly match anything, not even an empty string
  797. if (sub.Length == 0) return end; // match at the end
  798. if (end == 0) return -1; // can't possibly find anything
  799. CompareInfo c = CultureInfo.InvariantCulture.CompareInfo;
  800. return c.LastIndexOf(self, sub, end - 1, end - start, CompareOptions.Ordinal);
  801. }
  802. public static int rfind(this string self, string sub, object start, [DefaultParameterValue(null)]object end) {
  803. return rfind(self, sub, CheckIndex(start, 0), CheckIndex(end, self.Length));
  804. }
  805. public static int rindex(this string self, string sub) {
  806. return rindex(self, sub, 0, self.Length);
  807. }
  808. public static int rindex(this string self, string sub, int start) {
  809. return rindex(self, sub, start, self.Length);
  810. }
  811. public static int rindex(this string self, string sub, int start, int end) {
  812. int ret = rfind(self, sub, start, end);
  813. if (ret == -1) throw PythonOps.ValueError("substring {0} not found in {1}", sub, self);
  814. return ret;
  815. }
  816. public static int rindex(this string self, string sub, object start, [DefaultParameterValue(null)]object end) {
  817. return rindex(self, sub, CheckIndex(start, 0), CheckIndex(end, self.Length));
  818. }
  819. public static string rjust(this string self, int width) {
  820. return rjust(self, width, ' ');
  821. }
  822. public static string rjust(this string self, int width, char fillchar) {
  823. int spaces = width - self.Length;
  824. if (spaces <= 0) return self;
  825. StringBuilder ret = new StringBuilder(width);
  826. ret.Append(fillchar, spaces);
  827. ret.Append(self);
  828. return ret.ToString();
  829. }
  830. public static PythonTuple rpartition(this string self, string sep) {
  831. if (sep == null)
  832. throw PythonOps.TypeError("expected string, got NoneType");
  833. if (sep.Length == 0)
  834. throw PythonOps.ValueError("empty separator");
  835. object[] obj = new object[3] { "", "", "" };
  836. if (self.Length != 0) {
  837. int index = rfind(self, sep);
  838. if (index == -1) {
  839. obj[2] = self;
  840. } else {
  841. obj[0] = self.Substring(0, index);
  842. obj[1] = sep;
  843. obj[2] = self.Substring(index + sep.Length, self.Length - index - sep.Length);
  844. }
  845. }
  846. return new PythonTuple(obj);
  847. }
  848. // when no maxsplit arg is given then just use split
  849. public static List rsplit(this string self) {
  850. return SplitInternal(self, (char[])null, -1);
  851. }
  852. public static List rsplit(this string self, string sep) {
  853. return rsplit(self, sep, -1);
  854. }
  855. public static List rsplit(this string self, string sep, int maxsplit) {
  856. // rsplit works like split but needs to split from the right;
  857. // reverse the original string (and the sep), split, reverse
  858. // the split list and finally reverse each element of the list
  859. string reversed = Reverse(self);
  860. if (sep != null) sep = Reverse(sep);
  861. List temp = null, ret = null;
  862. temp = split(reversed, sep, maxsplit);
  863. temp.reverse();
  864. int resultlen = temp.__len__();
  865. if (resultlen != 0) {
  866. ret = new List(resultlen);
  867. foreach (string s in temp)
  868. ret.AddNoLock(Reverse(s));
  869. } else {
  870. ret = temp;
  871. }
  872. return ret;
  873. }
  874. public static string rstrip(this string self) {
  875. return self.TrimEnd(Whitespace);
  876. }
  877. public static string rstrip(this string self, string chars) {
  878. if (chars == null) return rstrip(self);
  879. return self.TrimEnd(chars.ToCharArray());
  880. }
  881. public static List split(this string self) {
  882. return SplitInternal(self, (char[])null, -1);
  883. }
  884. public static List split(this string self, string sep) {
  885. return split(self, sep, -1);
  886. }
  887. public static List split(this string self, string sep, int maxsplit) {
  888. if (sep == null) {
  889. if (maxsplit == 0) {
  890. // Corner case for CPython compatibility
  891. List result = PythonOps.MakeEmptyList(1);
  892. result.AddNoLock(self.TrimStart());
  893. return result;
  894. } else {
  895. return SplitInternal(self, (char[])null, maxsplit);
  896. }
  897. }
  898. if (sep.Length == 0) {
  899. throw PythonOps.ValueError("empty separator");
  900. } else if (sep.Length == 1) {
  901. return SplitInternal(self, new char[] { sep[0] }, maxsplit);
  902. } else {
  903. return SplitInternal(self, sep, maxsplit);
  904. }
  905. }
  906. public static List splitlines(this string self) {
  907. return splitlines(self, false);
  908. }
  909. public static List splitlines(this string self, bool keepends) {
  910. List ret = new List();
  911. int i, linestart;
  912. for (i = 0, linestart = 0; i < self.Length; i++) {
  913. if (self[i] == '\n' || self[i] == '\r' || self[i] == '\x2028') {
  914. // special case of "\r\n" as end of line marker
  915. if (i < self.Length - 1 && self[i] == '\r' && self[i + 1] == '\n') {
  916. if (keepends)
  917. ret.AddNoLock(self.Substring(linestart, i - linestart + 2));
  918. else
  919. ret.AddNoLock(self.Substring(linestart, i - linestart));
  920. linestart = i + 2;
  921. i++;
  922. } else { //'\r', '\n', or unicode new line as end of line marker
  923. if (keepends)
  924. ret.AddNoLock(self.Substring(linestart, i - linestart + 1));
  925. else
  926. ret.AddNoLock(self.Substring(linestart, i - linestart));
  927. linestart = i + 1;
  928. }
  929. }
  930. }
  931. // the last line needs to be accounted for if it is not empty
  932. if (i - linestart != 0)
  933. ret.AddNoLock(self.Substring(linestart, i - linestart));
  934. return ret;
  935. }
  936. public static bool startswith(this string self, object prefix) {
  937. TryStringOrTuple(prefix);
  938. if (prefix is PythonTuple)
  939. return startswith(self, (PythonTuple)prefix);
  940. else
  941. return startswith(self, CastString(prefix));
  942. }
  943. public static bool startswith(this string self, object prefix, int start) {
  944. TryStringOrTuple(prefix);
  945. if (prefix is PythonTuple)
  946. return startswith(self, (PythonTuple)prefix, start);
  947. else
  948. return startswith(self, CastString(prefix), start);
  949. }
  950. public static bool startswith(this string self, object prefix, int start, int end) {
  951. TryStringOrTuple(prefix);
  952. if (prefix is PythonTuple)
  953. return startswith(self, (PythonTuple)prefix, start, end);
  954. else
  955. return startswith(self, CastString(prefix), start, end);
  956. }
  957. public static string strip(this string self) {
  958. return self.Trim();
  959. }
  960. public static string strip(this string self, string chars) {
  961. if (chars == null) return strip(self);
  962. return self.Trim(chars.ToCharArray());
  963. }
  964. public static string swapcase(this string self) {
  965. StringBuilder ret = new StringBuilder(self);
  966. for (int i = 0; i < ret.Length; i++) {
  967. char ch = ret[i];
  968. if (Char.IsUpper(ch)) ret[i] = Char.ToLower(ch, CultureInfo.InvariantCulture);
  969. else if (Char.IsLower(ch)) ret[i] = Char.ToUpper(ch, CultureInfo.InvariantCulture);
  970. }
  971. return ret.ToString();
  972. }
  973. public static string title(this string self) {
  974. if (self == null || self.Length == 0) return self;
  975. char[] retchars = self.ToCharArray();
  976. bool prevCharCased = false;
  977. bool currCharCased = false;
  978. int i = 0;
  979. do {
  980. if (Char.IsUpper(retchars[i]) || Char.IsLower(retchars[i])) {
  981. if (!prevCharCased)
  982. retchars[i] = Char.ToUpper(retchars[i], CultureInfo.InvariantCulture);
  983. else
  984. retchars[i] = Char.ToLower(retchars[i], CultureInfo.InvariantCulture);
  985. currCharCased = true;
  986. } else {
  987. currCharCased = false;
  988. }
  989. i++;
  990. prevCharCased = currCharCased;
  991. }
  992. while (i < retchars.Length);
  993. return new string(retchars);
  994. }
  995. //translate on a unicode string differs from that on an ascii
  996. //for unicode, the table argument is actually a dictionary with
  997. //character ordinals as keys and the replacement strings as values
  998. public static string translate(this string self, [NotNull]PythonDictionary table) {
  999. if (table == null || self.Length == 0) {
  1000. return self;
  1001. }
  1002. StringBuilder ret = new StringBuilder();
  1003. for (int i = 0, idx = 0; i < self.Length; i++) {
  1004. idx = (int)self[i];
  1005. if (table.__contains__(idx))
  1006. ret.Append((string)table[idx]);
  1007. else
  1008. ret.Append(self[i]);
  1009. }
  1010. return ret.ToString();
  1011. }
  1012. public static string translate(this string self, string table) {
  1013. return translate(self, table, (string)null);
  1014. }
  1015. public static string translate(this string self, string table, string deletechars) {
  1016. if (table != null && table.Length != 256) {
  1017. throw PythonOps.ValueError("translation table must be 256 characters long");
  1018. } else if (self.Length == 0) {
  1019. return self;
  1020. }
  1021. // List<char> is about 2/3rds as expensive as StringBuilder appending individual
  1022. // char's so we use that instead of a StringBuilder
  1023. List<char> res = new List<char>();
  1024. for (int i = 0; i < self.Length; i++) {
  1025. if (deletechars == null || !deletechars.Contains(Char.ToString(self[i]))) {
  1026. if (table != null) {
  1027. int idx = (int)self[i];
  1028. if (idx >= 0 && idx < 256) {
  1029. res.Add(table[idx]);
  1030. }
  1031. } else {
  1032. res.Add(self[i]);
  1033. }
  1034. }
  1035. }
  1036. return new String(res.ToArray());
  1037. }
  1038. public static string upper(this string self) {
  1039. return self.ToUpper(CultureInfo.InvariantCulture);
  1040. }
  1041. public static string zfill(this string self, int width) {
  1042. int spaces = width - self.Length;
  1043. if (spaces <= 0) return self;
  1044. StringBuilder ret = new StringBuilder(width);
  1045. if (self.Length > 0 && IsSign(self[0])) {
  1046. ret.Append(self[0]);
  1047. ret.Append('0', spaces);
  1048. ret.Append(self.Substring(1));
  1049. } else {
  1050. ret.Append('0', spaces);
  1051. ret.Append(self);
  1052. }
  1053. return ret.ToString();
  1054. }
  1055. /// <summary>
  1056. /// Replaces each replacement field in the string with the provided arguments.
  1057. ///
  1058. /// replacement_field = "{" field_name ["!" conversion] [":" format_spec] "}"
  1059. /// field_name = (identifier | integer) ("." identifier | "[" element_index "]")*
  1060. ///
  1061. /// format_spec: [[fill]align][sign][#][0][width][.precision][type]
  1062. ///
  1063. /// Conversion can be 'r' for repr or 's' for string.
  1064. /// </summary>

Large files files are truncated, but you can click here to view the full file