PageRenderTime 57ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/Languages/IronPython/IronPython/Runtime/Operations/StringOps.cs

http://github.com/IronLanguages/main
C# | 2751 lines | 2393 code | 267 blank | 91 comment | 426 complexity | 95b482bb7d0d13067ccac8e62c9c8e63 MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception

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 Apache License, Version 2.0. 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 Apache License, Version 2.0, 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 Apache License, Version 2.0.
  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 FEATURE_NUMERICS
  29. using System.Numerics;
  30. #else
  31. using Microsoft.Scripting.Math;
  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. else if (value is Bytes) return Value.Contains(value.ToString());
  143. throw PythonOps.TypeErrorForBadInstance("expected string, got {0}", value);
  144. }
  145. #endregion
  146. }
  147. /// <summary>
  148. /// StringOps is the static class that contains the methods defined on strings, i.e. 'abc'
  149. ///
  150. /// Here we define all of the methods that a Python user would see when doing dir('abc').
  151. /// If the user is running in a CLS aware context they will also see all of the methods
  152. /// defined in the CLS System.String type.
  153. /// </summary>
  154. public static class StringOps {
  155. internal const int LowestUnicodeValue = 0x7f;
  156. internal static object FastNew(CodeContext/*!*/ context, object x) {
  157. if (x == null) {
  158. return "None";
  159. }
  160. string xstr = (x as string);
  161. if (xstr != null) {
  162. return xstr;
  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. #region Python Constructors
  226. [StaticExtensionMethod]
  227. public static object __new__(CodeContext/*!*/ context, PythonType cls) {
  228. if (cls == TypeCache.String) {
  229. return "";
  230. } else {
  231. return cls.CreateInstance(context);
  232. }
  233. }
  234. [StaticExtensionMethod]
  235. public static object __new__(CodeContext/*!*/ context, PythonType cls, object @object) {
  236. if (cls == TypeCache.String) {
  237. return FastNew(context, @object);
  238. } else {
  239. return cls.CreateInstance(context, __new__(context, TypeCache.String, @object));
  240. }
  241. }
  242. [StaticExtensionMethod]
  243. public static object __new__(CodeContext/*!*/ context, PythonType cls, [NotNull]string @object) {
  244. if (cls == TypeCache.String) {
  245. return @object;
  246. } else {
  247. return cls.CreateInstance(context, @object);
  248. }
  249. }
  250. [StaticExtensionMethod]
  251. public static object __new__(CodeContext/*!*/ context, PythonType cls, [NotNull]ExtensibleString @object) {
  252. if (cls == TypeCache.String) {
  253. return FastNew(context, @object);
  254. } else {
  255. return cls.CreateInstance(context, __new__(context, TypeCache.String, @object));
  256. }
  257. }
  258. [StaticExtensionMethod]
  259. public static object __new__(CodeContext/*!*/ context, PythonType cls, char @object) {
  260. if (cls == TypeCache.String) {
  261. return ScriptingRuntimeHelpers.CharToString(@object);
  262. } else {
  263. return cls.CreateInstance(context, __new__(context, TypeCache.String, @object));
  264. }
  265. }
  266. [StaticExtensionMethod]
  267. public static object __new__(CodeContext/*!*/ context, PythonType cls, [NotNull]BigInteger @object) {
  268. if (cls == TypeCache.String) {
  269. return @object.ToString();
  270. } else {
  271. return cls.CreateInstance(context, __new__(context, TypeCache.String, @object));
  272. }
  273. }
  274. [StaticExtensionMethod]
  275. public static object __new__(CodeContext/*!*/ context, PythonType cls, [NotNull]Extensible<BigInteger> @object) {
  276. if (cls == TypeCache.String) {
  277. return FastNew(context, @object);
  278. } else {
  279. return cls.CreateInstance(context, __new__(context, TypeCache.String, @object));
  280. }
  281. }
  282. [StaticExtensionMethod]
  283. public static object __new__(CodeContext/*!*/ context, PythonType cls, int @object) {
  284. if (cls == TypeCache.String) {
  285. return @object.ToString();
  286. } else {
  287. return cls.CreateInstance(context, __new__(context, TypeCache.String, @object));
  288. }
  289. }
  290. [StaticExtensionMethod]
  291. public static object __new__(CodeContext/*!*/ context, PythonType cls, bool @object) {
  292. if (cls == TypeCache.String) {
  293. return @object.ToString();
  294. } else {
  295. return cls.CreateInstance(context, __new__(context, TypeCache.String, @object));
  296. }
  297. }
  298. [StaticExtensionMethod]
  299. public static object __new__(CodeContext/*!*/ context, PythonType cls, double @object) {
  300. if (cls == TypeCache.String) {
  301. return DoubleOps.__str__(context, @object);
  302. } else {
  303. return cls.CreateInstance(context, __new__(context, TypeCache.String, @object));
  304. }
  305. }
  306. [StaticExtensionMethod]
  307. public static object __new__(CodeContext/*!*/ context, PythonType cls, Extensible<double> @object) {
  308. if (cls == TypeCache.String) {
  309. return FastNew(context, @object);
  310. } else {
  311. return cls.CreateInstance(context, __new__(context, TypeCache.String, @object));
  312. }
  313. }
  314. [StaticExtensionMethod]
  315. public static object __new__(CodeContext/*!*/ context, PythonType cls, float @object) {
  316. if (cls == TypeCache.String) {
  317. return SingleOps.__str__(context, @object);
  318. } else {
  319. return cls.CreateInstance(context, __new__(context, TypeCache.String, @object));
  320. }
  321. }
  322. [StaticExtensionMethod]
  323. public static object __new__(CodeContext/*!*/ context, PythonType cls,
  324. object @string,
  325. [DefaultParameterValue(null)] string encoding,
  326. [DefaultParameterValue("strict")] string errors) {
  327. string str = @string as string;
  328. if (str == null) throw PythonOps.TypeError("converting to unicode: need string, got {0}", DynamicHelpers.GetPythonType(@string).Name);
  329. if (cls == TypeCache.String) {
  330. return decode(context, str, encoding ?? PythonContext.GetContext(context).GetDefaultEncodingName(), errors);
  331. } else {
  332. return cls.CreateInstance(context, __new__(context, TypeCache.String, str, encoding, errors));
  333. }
  334. }
  335. #endregion
  336. #region Python __ methods
  337. public static bool __contains__(string s, [BytesConversion]string item) {
  338. return s.Contains(item);
  339. }
  340. public static bool __contains__(string s, char item) {
  341. return s.IndexOf(item) != -1;
  342. }
  343. public static string __format__(CodeContext/*!*/ context, string self, [BytesConversion]string formatSpec) {
  344. return ObjectOps.__format__(context, self, formatSpec);
  345. }
  346. public static int __len__(string s) {
  347. return s.Length;
  348. }
  349. [SpecialName]
  350. public static string GetItem(string s, int index) {
  351. return ScriptingRuntimeHelpers.CharToString(s[PythonOps.FixIndex(index, s.Length)]);
  352. }
  353. [SpecialName]
  354. public static string GetItem(string s, object index) {
  355. return GetItem(s, Converter.ConvertToIndex(index));
  356. }
  357. [SpecialName]
  358. public static string GetItem(string s, Slice slice) {
  359. if (slice == null) throw PythonOps.TypeError("string indices must be slices or integers");
  360. int start, stop, step;
  361. slice.indices(s.Length, out start, out stop, out step);
  362. if (step == 1) {
  363. return stop > start ? s.Substring(start, stop - start) : String.Empty;
  364. } else {
  365. int index = 0;
  366. char[] newData;
  367. if (step > 0) {
  368. if (start > stop) return String.Empty;
  369. int icnt = (stop - start + step - 1) / step;
  370. newData = new char[icnt];
  371. for (int i = start; i < stop; i += step) {
  372. newData[index++] = s[i];
  373. }
  374. } else {
  375. if (start < stop) return String.Empty;
  376. int icnt = (stop - start + step + 1) / step;
  377. newData = new char[icnt];
  378. for (int i = start; i > stop; i += step) {
  379. newData[index++] = s[i];
  380. }
  381. }
  382. return new string(newData);
  383. }
  384. }
  385. public static string __getslice__(string self, int x, int y) {
  386. Slice.FixSliceArguments(self.Length, ref x, ref y);
  387. if (x >= y) return String.Empty;
  388. return self.Substring(x, y - x);
  389. }
  390. #endregion
  391. #region Public Python methods
  392. /// <summary>
  393. /// Returns a copy of this string converted to uppercase
  394. /// </summary>
  395. public static string capitalize(this string self) {
  396. if (self.Length == 0) return self;
  397. return Char.ToUpperInvariant(self[0]) + self.Substring(1).ToLowerInvariant();
  398. }
  399. // default fillchar (padding char) is a space
  400. public static string center(this string self, int width) {
  401. return center(self, width, ' ');
  402. }
  403. public static string center(this string self, int width, char fillchar) {
  404. int spaces = width - self.Length;
  405. if (spaces <= 0) return self;
  406. StringBuilder ret = new StringBuilder(width);
  407. ret.Append(fillchar, spaces / 2);
  408. ret.Append(self);
  409. ret.Append(fillchar, (spaces + 1) / 2);
  410. return ret.ToString();
  411. }
  412. public static int count(this string self, [BytesConversion]string sub) {
  413. return count(self, sub, 0, self.Length);
  414. }
  415. public static int count(this string self, [BytesConversion]string sub, int start) {
  416. return count(self, sub, start, self.Length);
  417. }
  418. public static int count(this string self, [BytesConversion]string ssub, int start, int end) {
  419. if (ssub == null) throw PythonOps.TypeError("expected string for 'sub' argument, got NoneType");
  420. if (start > self.Length) {
  421. return 0;
  422. }
  423. start = PythonOps.FixSliceIndex(start, self.Length);
  424. end = PythonOps.FixSliceIndex(end, self.Length);
  425. if (ssub.Length == 0) {
  426. return Math.Max((end - start) + 1, 0);
  427. }
  428. int count = 0;
  429. CompareInfo c = CultureInfo.InvariantCulture.CompareInfo;
  430. while (true) {
  431. if (end <= start) break;
  432. int index = c.IndexOf(self, ssub, start, end - start, CompareOptions.Ordinal);
  433. if (index == -1) break;
  434. count++;
  435. start = index + ssub.Length;
  436. }
  437. return count;
  438. }
  439. public static string decode(CodeContext/*!*/ context, string s) {
  440. return decode(context, s, Missing.Value, "strict");
  441. }
  442. public static string decode(CodeContext/*!*/ context, string s, [Optional]object encoding, [DefaultParameterValue("strict")]string errors) {
  443. return RawDecode(context, s, encoding, errors);
  444. }
  445. public static string encode(CodeContext/*!*/ context, string s, [Optional]object encoding, [DefaultParameterValue("strict")]string errors) {
  446. return RawEncode(context, s, encoding, errors);
  447. }
  448. private static string CastString(object o) {
  449. string res = o as string;
  450. if (res != null) {
  451. return res;
  452. }
  453. return ((Extensible<string>)o).Value;
  454. }
  455. internal static string AsString(object o) {
  456. string res = o as string;
  457. if (res != null) {
  458. return res;
  459. }
  460. Extensible<string> es = o as Extensible<string>;
  461. if (es != null) {
  462. return es.Value;
  463. }
  464. return null;
  465. }
  466. public static bool endswith(this string self, object suffix) {
  467. TryStringOrTuple(suffix);
  468. if (suffix is PythonTuple)
  469. return endswith(self, (PythonTuple)suffix);
  470. else
  471. return endswith(self, CastString(suffix));
  472. }
  473. public static bool endswith(this string self, object suffix, int start) {
  474. TryStringOrTuple(suffix);
  475. if (suffix is PythonTuple)
  476. return endswith(self, (PythonTuple)suffix, start);
  477. else
  478. return endswith(self, CastString(suffix), start);
  479. }
  480. public static bool endswith(this string self, object suffix, int start, int end) {
  481. TryStringOrTuple(suffix);
  482. if (suffix is PythonTuple)
  483. return endswith(self, (PythonTuple)suffix, start, end);
  484. else
  485. return endswith(self, CastString(suffix), start, end);
  486. }
  487. public static string expandtabs(string self) {
  488. return expandtabs(self, 8);
  489. }
  490. public static string expandtabs(this string self, int tabsize) {
  491. StringBuilder ret = new StringBuilder(self.Length * 2);
  492. string v = self;
  493. int col = 0;
  494. for (int i = 0; i < v.Length; i++) {
  495. char ch = v[i];
  496. switch (ch) {
  497. case '\n':
  498. case '\r': col = 0; ret.Append(ch); break;
  499. case '\t':
  500. if (tabsize > 0) {
  501. int tabs = tabsize - (col % tabsize);
  502. int existingSize = ret.Capacity;
  503. ret.Capacity = checked(existingSize + tabs);
  504. ret.Append(' ', tabs);
  505. col = 0;
  506. }
  507. break;
  508. default:
  509. col++;
  510. ret.Append(ch);
  511. break;
  512. }
  513. }
  514. return ret.ToString();
  515. }
  516. public static int find(this string self, [BytesConversion]string sub) {
  517. if (sub == null) throw PythonOps.TypeError("expected string, got NoneType");
  518. if (sub.Length == 1) return self.IndexOf(sub[0]);
  519. CompareInfo c = CultureInfo.InvariantCulture.CompareInfo;
  520. return c.IndexOf(self, sub, CompareOptions.Ordinal);
  521. }
  522. public static int find(this string self, [BytesConversion]string sub, int start) {
  523. if (sub == null) throw PythonOps.TypeError("expected string, got NoneType");
  524. if (start > self.Length) return -1;
  525. start = PythonOps.FixSliceIndex(start, self.Length);
  526. CompareInfo c = CultureInfo.InvariantCulture.CompareInfo;
  527. return c.IndexOf(self, sub, start, CompareOptions.Ordinal);
  528. }
  529. public static int find(this string self, [BytesConversion]string sub, BigInteger start) {
  530. if (sub == null) throw PythonOps.TypeError("expected string, got NoneType");
  531. if (start > self.Length) return -1;
  532. return find(self, sub, (int)start);
  533. }
  534. public static int find(this string self, [BytesConversion]string sub, int start, int end) {
  535. if (sub == null) throw PythonOps.TypeError("expected string, got NoneType");
  536. if (start > self.Length) return -1;
  537. start = PythonOps.FixSliceIndex(start, self.Length);
  538. end = PythonOps.FixSliceIndex(end, self.Length);
  539. if (end < start) return -1;
  540. CompareInfo c = CultureInfo.InvariantCulture.CompareInfo;
  541. return c.IndexOf(self, sub, start, end - start, CompareOptions.Ordinal);
  542. }
  543. public static int find(this string self, [BytesConversion]string sub, BigInteger start, BigInteger end) {
  544. if (sub == null) throw PythonOps.TypeError("expected string, got NoneType");
  545. if (start > self.Length) return -1;
  546. return find(self, sub, (int)start, (int)end);
  547. }
  548. public static int find(this string self, [BytesConversion]string sub, object start, [DefaultParameterValue(null)]object end) {
  549. return find(self, sub, CheckIndex(start, 0), CheckIndex(end, self.Length));
  550. }
  551. public static int index(this string self, [BytesConversion]string sub) {
  552. if (sub == null) throw PythonOps.TypeError("expected string, got NoneType");
  553. return index(self, sub, 0, self.Length);
  554. }
  555. public static int index(this string self, [BytesConversion]string sub, int start) {
  556. if (sub == null) throw PythonOps.TypeError("expected string, got NoneType");
  557. return index(self, sub, start, self.Length);
  558. }
  559. public static int index(this string self, [BytesConversion]string sub, int start, int end) {
  560. if (sub == null) throw PythonOps.TypeError("expected string, got NoneType");
  561. int ret = find(self, sub, start, end);
  562. if (ret == -1) throw PythonOps.ValueError("substring {0} not found in {1}", sub, self);
  563. return ret;
  564. }
  565. public static int index(this string self, [BytesConversion]string sub, object start, [DefaultParameterValue(null)]object end) {
  566. return index(self, sub, CheckIndex(start, 0), CheckIndex(end, self.Length));
  567. }
  568. public static bool isalnum(this string self) {
  569. if (self.Length == 0) return false;
  570. string v = self;
  571. for (int i = v.Length - 1; i >= 0; i--) {
  572. if (!Char.IsLetterOrDigit(v, i)) return false;
  573. }
  574. return true;
  575. }
  576. public static bool isalpha(this string self) {
  577. if (self.Length == 0) return false;
  578. string v = self;
  579. for (int i = v.Length - 1; i >= 0; i--) {
  580. if (!Char.IsLetter(v, i)) return false;
  581. }
  582. return true;
  583. }
  584. public static bool isdigit(this string self) {
  585. if (self.Length == 0) return false;
  586. string v = self;
  587. for (int i = v.Length - 1; i >= 0; i--) {
  588. // CPython considers the circled digits to be digits
  589. if (!Char.IsDigit(v, i) && (v[i] < '\u2460' || v[i] > '\u2468')) return false;
  590. }
  591. return true;
  592. }
  593. public static bool isspace(this string self) {
  594. if (self.Length == 0) return false;
  595. string v = self;
  596. for (int i = v.Length - 1; i >= 0; i--) {
  597. if (!Char.IsWhiteSpace(v, i)) return false;
  598. }
  599. return true;
  600. }
  601. public static bool isdecimal(this string self) {
  602. return isnumeric(self);
  603. }
  604. public static bool isnumeric(this string self) {
  605. if (String.IsNullOrEmpty(self)) return false;
  606. foreach (char c in self) {
  607. if (!Char.IsDigit(c)) return false;
  608. }
  609. return true;
  610. }
  611. public static bool islower(this string self) {
  612. if (self.Length == 0) return false;
  613. string v = self;
  614. bool hasLower = false;
  615. for (int i = v.Length - 1; i >= 0; i--) {
  616. if (!hasLower && Char.IsLower(v, i)) hasLower = true;
  617. if (Char.IsUpper(v, i)) return false;
  618. }
  619. return hasLower;
  620. }
  621. public static bool isupper(this string self) {
  622. if (self.Length == 0) return false;
  623. string v = self;
  624. bool hasUpper = false;
  625. for (int i = v.Length - 1; i >= 0; i--) {
  626. if (!hasUpper && Char.IsUpper(v, i)) hasUpper = true;
  627. if (Char.IsLower(v, i)) return false;
  628. }
  629. return hasUpper;
  630. }
  631. /// <summary>
  632. /// return true if self is a titlecased string and there is at least one
  633. /// character in self; also, uppercase characters may only follow uncased
  634. /// characters (e.g. whitespace) and lowercase characters only cased ones.
  635. /// return false otherwise.
  636. /// </summary>
  637. public static bool istitle(this string self) {
  638. if (self == null || self.Length == 0) return false;
  639. string v = self;
  640. bool prevCharCased = false, currCharCased = false, containsUpper = false;
  641. for (int i = 0; i < v.Length; i++) {
  642. if (Char.IsUpper(v, i) || CharUnicodeInfo.GetUnicodeCategory(v, i) == UnicodeCategory.TitlecaseLetter) {
  643. containsUpper = true;
  644. if (prevCharCased)
  645. return false;
  646. else
  647. currCharCased = true;
  648. } else if (Char.IsLower(v, i))
  649. if (!prevCharCased)
  650. return false;
  651. else
  652. currCharCased = true;
  653. else
  654. currCharCased = false;
  655. prevCharCased = currCharCased;
  656. }
  657. // if we've gone through the whole string and haven't encountered any rule
  658. // violations but also haven't seen an Uppercased char, then this is not a
  659. // title e.g. '\n', all whitespace etc.
  660. return containsUpper;
  661. }
  662. public static bool isunicode(this string self) {
  663. foreach (char c in self) {
  664. if (c >= LowestUnicodeValue) return true;
  665. }
  666. return false;
  667. }
  668. /// <summary>
  669. /// Return a string which is the concatenation of the strings
  670. /// in the sequence seq. The separator between elements is the
  671. /// string providing this method
  672. /// </summary>
  673. public static string join(this string self, object sequence) {
  674. IEnumerator seq = PythonOps.GetEnumerator(sequence);
  675. if (!seq.MoveNext()) return "";
  676. // check if we have just a sequence of just one value - if so just
  677. // return that value.
  678. object curVal = seq.Current;
  679. if (!seq.MoveNext()) return Converter.ConvertToString(curVal);
  680. StringBuilder ret = new StringBuilder();
  681. AppendJoin(curVal, 0, ret);
  682. int index = 1;
  683. do {
  684. ret.Append(self);
  685. AppendJoin(seq.Current, index, ret);
  686. index++;
  687. } while (seq.MoveNext());
  688. return ret.ToString();
  689. }
  690. public static string join(this string/*!*/ self, [NotNull]List/*!*/ sequence) {
  691. if (sequence.__len__() == 0) return String.Empty;
  692. lock (sequence) {
  693. if (sequence.__len__() == 1) {
  694. return Converter.ConvertToString(sequence[0]);
  695. }
  696. StringBuilder ret = new StringBuilder();
  697. AppendJoin(sequence._data[0], 0, ret);
  698. for (int i = 1; i < sequence._size; i++) {
  699. if (!String.IsNullOrEmpty(self)) {
  700. ret.Append(self);
  701. }
  702. AppendJoin(sequence._data[i], i, ret);
  703. }
  704. return ret.ToString();
  705. }
  706. }
  707. public static string ljust(this string self, int width) {
  708. return ljust(self, width, ' ');
  709. }
  710. public static string ljust(this string self, int width, char fillchar) {
  711. if (width < 0) return self;
  712. int spaces = width - self.Length;
  713. if (spaces <= 0) return self;
  714. StringBuilder ret = new StringBuilder(width);
  715. ret.Append(self);
  716. ret.Append(fillchar, spaces);
  717. return ret.ToString();
  718. }
  719. // required for better match with cpython upper/lower
  720. private static CultureInfo CasingCultureInfo = new CultureInfo("en");
  721. public static string lower(this string self) {
  722. return CasingCultureInfo.TextInfo.ToLower(self);
  723. }
  724. internal static string ToLowerAsciiTriggered(this string self) {
  725. for (int i = 0; i < self.Length; i++) {
  726. if (self[i] >= 'A' && self[i] <= 'Z') {
  727. return self.ToLowerInvariant();
  728. }
  729. }
  730. return self;
  731. }
  732. public static string lstrip(this string self) {
  733. return self.TrimStart();
  734. }
  735. public static string lstrip(this string self, [BytesConversion]string chars) {
  736. if (chars == null) return lstrip(self);
  737. return self.TrimStart(chars.ToCharArray());
  738. }
  739. [return: SequenceTypeInfo(typeof(string))]
  740. public static PythonTuple partition(this string self, [BytesConversion]string sep) {
  741. if (sep == null)
  742. throw PythonOps.TypeError("expected string, got NoneType");
  743. if (sep.Length == 0)
  744. throw PythonOps.ValueError("empty separator");
  745. object[] obj = new object[3] { "", "", "" };
  746. if (self.Length != 0) {
  747. int index = find(self, sep);
  748. if (index == -1) {
  749. obj[0] = self;
  750. } else {
  751. obj[0] = self.Substring(0, index);
  752. obj[1] = sep;
  753. obj[2] = self.Substring(index + sep.Length, self.Length - index - sep.Length);
  754. }
  755. }
  756. return new PythonTuple(obj);
  757. }
  758. public static string replace(this string self, [BytesConversion]string old, [BytesConversion]string @new,
  759. [DefaultParameterValue(-1)]int count) {
  760. if (old == null) {
  761. throw PythonOps.TypeError("expected a character buffer object"); // cpython message
  762. }
  763. if (old.Length == 0) return ReplaceEmpty(self, @new, count);
  764. string v = self;
  765. int replacements = StringOps.count(v, old);
  766. replacements = (count < 0 || count > replacements) ? replacements : count;
  767. int newLength = v.Length;
  768. newLength -= replacements * old.Length;
  769. newLength = checked(newLength + replacements * @new.Length);
  770. StringBuilder ret = new StringBuilder(newLength);
  771. int index;
  772. int start = 0;
  773. while (count != 0 && (index = v.IndexOf(old, start, StringComparison.Ordinal)) != -1) {
  774. ret.Append(v, start, index - start);
  775. ret.Append(@new);
  776. start = index + old.Length;
  777. count--;
  778. }
  779. ret.Append(v.Substring(start));
  780. return ret.ToString();
  781. }
  782. public static int rfind(this string self, [BytesConversion]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, [BytesConversion]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, [BytesConversion]string sub, BigInteger start) {
  792. if (sub == null) throw PythonOps.TypeError("expected string, got NoneType");
  793. if (start > self.Length) return -1;
  794. return rfind(self, sub, (int)start, self.Length);
  795. }
  796. public static int rfind(this string self, [BytesConversion]string sub, int start, int end) {
  797. if (sub == null) throw PythonOps.TypeError("expected string, got NoneType");
  798. if (start > self.Length) return -1;
  799. start = PythonOps.FixSliceIndex(start, self.Length);
  800. end = PythonOps.FixSliceIndex(end, self.Length);
  801. if (start > end) return -1; // can't possibly match anything, not even an empty string
  802. if (sub.Length == 0) return end; // match at the end
  803. if (end == 0) return -1; // can't possibly find anything
  804. CompareInfo c = CultureInfo.InvariantCulture.CompareInfo;
  805. return c.LastIndexOf(self, sub, end - 1, end - start, CompareOptions.Ordinal);
  806. }
  807. public static int rfind(this string self, [BytesConversion]string sub, BigInteger start, BigInteger end) {
  808. if (sub == null) throw PythonOps.TypeError("expected string, got NoneType");
  809. if (start > self.Length) return -1;
  810. return rfind(self, sub, (int)start, (int)end);
  811. }
  812. public static int rfind(this string self, [BytesConversion]string sub, object start, [DefaultParameterValue(null)]object end) {
  813. return rfind(self, sub, CheckIndex(start, 0), CheckIndex(end, self.Length));
  814. }
  815. public static int rindex(this string self, [BytesConversion]string sub) {
  816. return rindex(self, sub, 0, self.Length);
  817. }
  818. public static int rindex(this string self, [BytesConversion]string sub, int start) {
  819. return rindex(self, sub, start, self.Length);
  820. }
  821. public static int rindex(this string self, [BytesConversion]string sub, int start, int end) {
  822. int ret = rfind(self, sub, start, end);
  823. if (ret == -1) throw PythonOps.ValueError("substring {0} not found in {1}", sub, self);
  824. return ret;
  825. }
  826. public static int rindex(this string self, [BytesConversion]string sub, object start, [DefaultParameterValue(null)]object end) {
  827. return rindex(self, sub, CheckIndex(start, 0), CheckIndex(end, self.Length));
  828. }
  829. public static string rjust(this string self, int width) {
  830. return rjust(self, width, ' ');
  831. }
  832. public static string rjust(this string self, int width, char fillchar) {
  833. int spaces = width - self.Length;
  834. if (spaces <= 0) return self;
  835. StringBuilder ret = new StringBuilder(width);
  836. ret.Append(fillchar, spaces);
  837. ret.Append(self);
  838. return ret.ToString();
  839. }
  840. [return: SequenceTypeInfo(typeof(string))]
  841. public static PythonTuple rpartition(this string self, [BytesConversion]string sep) {
  842. if (sep == null)
  843. throw PythonOps.TypeError("expected string, got NoneType");
  844. if (sep.Length == 0)
  845. throw PythonOps.ValueError("empty separator");
  846. object[] obj = new object[3] { "", "", "" };
  847. if (self.Length != 0) {
  848. int index = rfind(self, sep);
  849. if (index == -1) {
  850. obj[2] = self;
  851. } else {
  852. obj[0] = self.Substring(0, index);
  853. obj[1] = sep;
  854. obj[2] = self.Substring(index + sep.Length, self.Length - index - sep.Length);
  855. }
  856. }
  857. return new PythonTuple(obj);
  858. }
  859. // when no maxsplit arg is given then just use split
  860. public static List rsplit(this string self) {
  861. return SplitInternal(self, (char[])null, -1);
  862. }
  863. public static List rsplit(this string self, [BytesConversion]string sep) {
  864. return rsplit(self, sep, -1);
  865. }
  866. public static List rsplit(this string self, [BytesConversion]string sep, int maxsplit) {
  867. // rsplit works like split but needs to split from the right;
  868. // reverse the original string (and the sep), split, reverse
  869. // the split list and finally reverse each element of the list
  870. string reversed = Reverse(self);
  871. if (sep != null) sep = Reverse(sep);
  872. List temp = null, ret = null;
  873. temp = split(reversed, sep, maxsplit);
  874. temp.reverse();
  875. int resultlen = temp.__len__();
  876. if (resultlen != 0) {
  877. ret = new List(resultlen);
  878. foreach (string s in temp)
  879. ret.AddNoLock(Reverse(s));
  880. } else {
  881. ret = temp;
  882. }
  883. return ret;
  884. }
  885. public static string rstrip(this string self) {
  886. return self.TrimEnd();
  887. }
  888. public static string rstrip(this string self, [BytesConversion]string chars) {
  889. if (chars == null) return rstrip(self);
  890. return self.TrimEnd(chars.ToCharArray());
  891. }
  892. public static List split(this string self) {
  893. return SplitInternal(self, (char[])null, -1);
  894. }
  895. public static List split(this string self, [BytesConversion]string sep) {
  896. return split(self, sep, -1);
  897. }
  898. public static List split(this string self, [BytesConversion]string sep, int maxsplit) {
  899. if (sep == null) {
  900. if (maxsplit == 0) {
  901. // Corner case for CPython compatibility
  902. List result = PythonOps.MakeEmptyList(1);
  903. result.AddNoLock(self.TrimStart());
  904. return result;
  905. } else {
  906. return SplitInternal(self, (char[])null, maxsplit);
  907. }
  908. }
  909. if (sep.Length == 0) {
  910. throw PythonOps.ValueError("empty separator");
  911. } else if (sep.Length == 1) {
  912. return SplitInternal(self, new char[] { sep[0] }, maxsplit);
  913. } else {
  914. return SplitInternal(self, sep, maxsplit);
  915. }
  916. }
  917. public static List splitlines(this string self) {
  918. return splitlines(self, false);
  919. }
  920. public static List splitlines(this string self, bool keepends) {
  921. List ret = new List();
  922. int i, linestart;
  923. for (i = 0, linestart = 0; i < self.Length; i++) {
  924. if (self[i] == '\n' || self[i] == '\r' || self[i] == '\x2028') {
  925. // special case of "\r\n" as end of line marker
  926. if (i < self.Length - 1 && self[i] == '\r' && self[i + 1] == '\n') {
  927. if (keepends)
  928. ret.AddNoLock(self.Substring(linestart, i - linestart + 2));
  929. else
  930. ret.AddNoLock(self.Substring(linestart, i - linestart));
  931. linestart = i + 2;
  932. i++;
  933. } else { //'\r', '\n', or unicode new line as end of line marker
  934. if (keepends)
  935. ret.AddNoLock(self.Substring(linestart, i - linestart + 1));
  936. else
  937. ret.AddNoLock(self.Substring(linestart, i - linestart));
  938. linestart = i + 1;
  939. }
  940. }
  941. }
  942. // the last line needs to be accounted for if it is not empty
  943. if (i - linestart != 0)
  944. ret.AddNoLock(self.Substring(linestart, i - linestart));
  945. return ret;
  946. }
  947. public static bool startswith(this string self, object prefix) {
  948. TryStringOrTuple(prefix);
  949. if (prefix is PythonTuple)
  950. return startswith(self, (PythonTuple)prefix);
  951. else
  952. return startswith(self, CastString(prefix));
  953. }
  954. public static bool startswith(this string self, object prefix, int start) {
  955. TryStringOrTuple(prefix);
  956. if (prefix is PythonTuple)
  957. return startswith(self, (PythonTuple)prefix, start);
  958. else
  959. return startswith(self, CastString(prefix), start);
  960. }
  961. public static bool startswith(this string self, object prefix, int start, int end) {
  962. TryStringOrTuple(prefix);
  963. if (prefix is PythonTuple)
  964. return startswith(self, (PythonTuple)prefix, start, end);
  965. else
  966. return startswith(self, CastString(prefix), start, end);
  967. }
  968. public static string strip(this string self) {
  969. return self.Trim();
  970. }
  971. public static string strip(this string self, [BytesConversion]string chars) {
  972. if (chars == null) return strip(self);
  973. return self.Trim(chars.ToCharArray());
  974. }
  975. public static string swapcase(this string self) {
  976. StringBuilder ret = new StringBuilder(self);
  977. for (int i = 0; i < ret.Length; i++) {
  978. char ch = ret[i];
  979. if (Char.IsUpper(ch)) ret[i] = Char.ToLowerInvariant(ch);
  980. else if (Char.IsLower(ch)) ret[i] = Char.ToUpperInvariant(ch);
  981. }
  982. return ret.ToString();
  983. }
  984. public static string title(this string self) {
  985. if (self == null || self.Length == 0) return self;
  986. char[] retchars = self.ToCharArray();
  987. bool prevCharCased = false;
  988. bool currCharCased = false;
  989. int i = 0;
  990. do {
  991. if (Char.IsUpper(retchars[i]) || Char.IsLower(retchars[i])) {
  992. if (!prevCharCased)
  993. retchars[i] = Char.ToUpperInvariant(retchars[i]);
  994. else
  995. retchars[i] = Char.ToLowerInvariant(retchars[i]);
  996. currCharCased = true;
  997. } else {
  998. currCharCased = false;
  999. }
  1000. i++;
  1001. prevCharCased = currCharCased;
  1002. }
  1003. while (i < retchars.Length);
  1004. return new string(retchars);
  1005. }
  1006. //translate on a unicode string differs from that on an ascii
  1007. //for unicode, the table argument is actually a dictionary with
  1008. //character ordinals as keys and the replacement strings as values
  1009. public static string translate(this string self, [NotNull]PythonDictionary table) {
  1010. if (table == null || self.Length == 0) {
  1011. return self;
  1012. }
  1013. StringBuilder ret = new StringBuilder();
  1014. for (int i = 0, idx = 0; i < self.Length; i++) {
  1015. idx = (int)self[i];
  1016. if (table.__contains__(idx)) {
  1017. var mapped = table[idx];
  1018. if (mapped == null) {
  1019. continue;
  1020. }
  1021. if (mapped is int) {
  1022. var mappedInt = (int) mapped;
  1023. if (mappedInt > 0xFFFF) {
  1024. throw PythonOps.TypeError("character mapping must be in range(0x%lx)");
  1025. }
  1026. ret.Append((char)(int)mapped);
  1027. } else if (mapped is String) {
  1028. ret.Append(mapped);
  1029. } else {
  1030. throw PythonOps.TypeError("character mapping must return integer, None or unicode");
  1031. }
  1032. } else {
  1033. ret.Append(self[i]);
  1034. }
  1035. }
  1036. return ret.ToString();
  1037. }
  1038. public static string translate(this string self, [BytesConversion]string table) {
  1039. return translate(self, table, (string)null);
  1040. }
  1041. public static string translate(this string self, [BytesConversion]string table, [BytesConversion]string deletechars) {
  1042. if (table != null && table.Length != 256) {
  1043. throw PythonOps.ValueError("translation table must be 256 characters long");
  1044. } else if (self.Length == 0) {
  1045. return self;
  1046. }
  1047. // List<char> is about 2/3rds as expensive as StringBuilder appending individual
  1048. // char's so we use that instead of a StringBuilder
  1049. List<char> res = new List<char>();
  1050. for (int i = 0; i < self.Length; i++) {
  1051. if (deletechars == null || !deletechars.Contains(Char.ToString(self[i]))) {
  1052. if (table != null) {
  1053. int idx = (int)self[i];
  1054. if (idx >= 0 && idx < 256) {
  1055. res.Add(table[idx]);
  1056. }
  1057. } else {
  1058. res.Add(self[i]);
  1059. }
  1060. }
  1061. }
  1062. return new String(res.ToArray());
  1063. }
  1064. public static string upper(this string self) {
  1065. return CasingCultureInfo.TextInfo.ToUpper(self);
  1066. }
  1067. public static string zfill(this string self, int width) {
  1068. int spaces = width - self.Length;
  1069. if (spaces <= 0) return self;
  1070. StringBuilder ret = new StringBuilder(width);
  1071. if (self.Length > 0 &&

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