append操作为例

  public mutating func append(_ other: String) {
if self.isEmpty && !_guts.hasNativeStorage {
self = other
return
}
self._guts.append(other._guts)
}

_StringGuts 做了实际的工作

下面是实际进行append的地方

  internal mutating func append(_ slicedOther: _StringGutsSlice) {
defer { self._invariantCheck() } if self.isSmall && slicedOther._guts.isSmall {
// TODO: In-register slicing
let smolSelf = self.asSmall
if let smol = slicedOther.withFastUTF8({ otherUTF8 in
return _SmallString(smolSelf, appending: _SmallString(otherUTF8)!)
}) {
self = _StringGuts(smol)
return
}
}
// 进行 copy-on-write 操作
prepareForAppendInPlace(otherUTF8Count: slicedOther.utf8Count) if slicedOther.isFastUTF8 {
let otherIsASCII = slicedOther.isASCII
slicedOther.withFastUTF8 { otherUTF8 in
self.appendInPlace(otherUTF8, isASCII: otherIsASCII)
}
return
} _foreignAppendInPlace(slicedOther)
}

首先判断是否可以安装小字符串处理,然后是重头戏。
我们以实际存储的是native string为例分析。

分配内存操作

  private mutating func prepareForAppendInPlace(
otherUTF8Count otherCount: Int
) {
defer {
_internalInvariant(self.uniqueNativeUnusedCapacity != nil,
"growth should produce uniqueness")
_internalInvariant(self.uniqueNativeUnusedCapacity! >= otherCount,
"growth should produce enough capacity")
} // See if we can accomodate without growing or copying. If we have
// sufficient capacity, we do not need to grow, and we can skip the copy if
// unique. Otherwise, growth is required.
let sufficientCapacity: Bool
if let unused = self.nativeUnusedCapacity, unused >= otherCount {
sufficientCapacity = true
} else {
sufficientCapacity = false
}
//naivestorage的字符串,一定不是UniqueNative的
if self.isUniqueNative && sufficientCapacity {
return
} let totalCount = self.utf8Count + otherCount // Non-unique storage: just make a copy of the appropriate size, otherwise
// grow like an array.
let growthTarget: Int
if sufficientCapacity {
growthTarget = totalCount
} else {
growthTarget = Swift.max(
totalCount, _growArrayCapacity(nativeCapacity ?? 0))
}
//最后会走到这里来
self.grow(growthTarget)
}

一定会调用grow函数。

  internal mutating func grow(_ n: Int) {
defer { self._invariantCheck() } _internalInvariant(
self.uniqueNativeCapacity == nil || self.uniqueNativeCapacity! < n) let growthTarget = Swift.max(n, (self.uniqueNativeCapacity ?? 0) * 2) if _fastPath(isFastUTF8) {
let isASCII = self.isASCII
let storage = self.withFastUTF8 {
// 分配了内存
__StringStorage.create(
initializingFrom: $0, capacity: growthTarget, isASCII: isASCII)
} self = _StringGuts(storage)
return
} _foreignGrow(growthTarget)
}

grow函数里,分配了内存

在分配好的内存里进行内存copy

  internal mutating func appendInPlace(
_ other: UnsafeBufferPointer<UInt8>, isASCII: Bool
) {
self._object.nativeStorage.appendInPlace(other, isASCII: isASCII) // We re-initialize from the modified storage to pick up new count, flags,
// etc.
self = _StringGuts(self._object.nativeStorage)
}
  @_effects(releasenone)
internal func appendInPlace(
_ other: UnsafeBufferPointer<UInt8>, isASCII: Bool
) {
_internalInvariant(self.capacity >= other.count)
let srcAddr = other.baseAddress._unsafelyUnwrappedUnchecked
let srcCount = other.count
self.mutableEnd.initialize(from: srcAddr, count: srcCount)
_postAppendAdjust(appendedCount: srcCount, appendedIsASCII: isASCII)
}

Swift 里字符串(十)修改字符串的更多相关文章

  1. zzulioj 1206 字符串的修改 (字符串修改)

    不难,理解一下直接过,代码如下: #include<stdio.h> #include<string.h> #include<math.h> #include< ...

  2. Swift语言指南(十)--字符串与字符

    原文:Swift语言指南(十)--字符串与字符 字符串是一段字符的有序集合,如"hellow,world"或"信天翁".Swift 中的字符串由 String ...

  3. [精校版]The Swift Programming Language--语言指南--字符串和字符 (转)

    今天装了10.10.马上就可以实际编写swift了.还是很兴奋啊. 哈哈.字符串和字符是大家最容易打交道的.今天就转一下讲解swift中字符串和字符的文章.希望对大家有帮助. 原文地址:http:// ...

  4. Python字符串的修改以及传参

    前两天去面试web developer,面试官提出一个问题,用JavaScript或者Python实现字符串反转,我选择了Python,然后写出了代码(错误的): #!/usr/bin/env pyt ...

  5. 在Linux中批量修改字符串的命令

    昨天一个朋友忽然问我,在Linux下如何批量修改字符串,当时瞬间懵逼了,完全想不起来....... 今天特意的重温了一下Linux下的一些常用命令,并将这个遗忘的批量修改字符串的命令记录下来(资料来自 ...

  6. unity里c# gc优化 -字符串

    1使用unsafe,直接修改字符串 public static class UnsafeString { public static unsafe void Copy(this string str, ...

  7. linux查找文件夹下的全部文件里是否含有某个字符串

    查找文件夹下的全部文件里是否含有某个字符串  find .|xargs grep -ri "IBM"  查找文件夹下的全部文件里是否含有某个字符串,而且仅仅打印出文件名称  fin ...

  8. Q: 字符串的修改

    题目描述 怎么样,前面的题还可以吧~ 依旧是字符串处理,设A和B是两个字符串.我们要用最少的字符操作次数,将字符串A转换为字符串B.这里所说的字符操作共有三种: 1. 删除一个字符: 2. 插入一个字 ...

  9. String与StringBuffer和StringBuilder的根本区别(String为什么无法修改字符串长度)

    从网上看了很多的信息,说的大部分是关于final修饰的原因,却没有详细的解释!根据自己收集的资料,跟大家分享一下我的观点(有错请指正).1.我们都知道在修改字符串长度的时候,StringBuffer和 ...

  10. 随笔 JS 字符串 分割成字符串数组 并动态添加到指定ID的DOM 里

    JS /* * 字符串 分割成字符串数组 并动态添加到指定ID的DOM 里 * @id 要插入到DOM元素的ID * * 输入值为图片URL 字符串 * */ function addImages(i ...

随机推荐

  1. setTimeout setInterval 详解

      http://www.jb51.net/article/74606.htm   var tttt=setTimeout('northsnow()',1000);//执行一次 clearTimeou ...

  2. AJAX初尝试——ACM/ICPC类比赛气球管理系统

    很早之前做过一个,白板没界面,20秒暴力刷新,数据库每个team一个n列的对应n个题目的标记项,只能对单个比赛暴力把全部user_id导入单独的气球表(也就是cid=1000用这个表的话,cid100 ...

  3. 2018.08.17 洛谷[POI2010]GRA-The Minima Game(线性dp)

    传送门 短代码神奇dp. 自己yy的思路居然1A了好高兴啊! 不难想到每个人选择的时候一定是取连续的最大的那一段数,自然需要先排序. 然后可以用dp[i]表示当前最大数是a[i]的时候先手可以获得的最 ...

  4. 2018.07.17 HAOI2016 找相同字符(SAM)

    传送门 就是给两个字符串,让你求公共字串的个数. 本来大佬们都是用的广义后缀自动机,但我感觉后缀自动机已经可以做这道题了.我们对其中一个字串建出后缀自动机,然后用另外一个后缀自动机在上面统计贡献即可. ...

  5. 29. What Makes a True Leader ? 合格的领导者由何物决定 ?

    29. What Makes a True Leader ? 合格的领导者由何物决定 ? ① Reading leadership literature,you'd sometimes think t ...

  6. DataFrame按行读取:DataFrame之values

    http://blog.csdn.net/u014607457/article/details/51290582 def fill_core(self): RatingTable=pd.read_cs ...

  7. python 文件合并和编号

    # -*- coding:utf-8 -*- import os import re p1=r"([0-9][0-9][AB])\.\w{3}$" pattern1=re.comp ...

  8. Kolakoski

    Kolakoski序列:我们知道的还是太少 上帝创造了整数,其余的则是我们人类的事了.正因为如此,质数.完全数.Fibonacci 数之类的数列才会让数学家们如痴如醉,因为它们的存在是如此自然,没有任 ...

  9. webuploader传递参数

    实际开发过程中,比如我有个工单提交系统,提交工单的时候用webuploader上传图片,如果工单的ID是自增长类型的,那么我在上传图片的时候肯定需要关联上工单的id,这时候就需要通过webupload ...

  10. day08(异常处理,创建异常,finally,throws和throw的区别)

    异常处理, 异常的产生  运行时异常:程序运行中产生的异常:RuntimeException类.   编译时异常:程序在编译时产生的异常:除了RuntimeException类  其他都是编译时产生的 ...